repo_name stringlengths 6 100 | path stringlengths 4 294 | copies stringlengths 1 5 | size stringlengths 4 6 | content stringlengths 606 896k | license stringclasses 15
values |
|---|---|---|---|---|---|
bolkedebruin/airflow | airflow/providers/vertica/hooks/vertica.py | 16 | 1616 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
from vertica_python import connect
from airflow.hooks.dbapi_hook import DbApiHook
class VerticaHook(DbApiHook):
"""
Interact with Vertica.
"""
conn_name_attr = 'vertica_conn_id'
default_conn_name = 'vertica_default'
supports_autocommit = True
def get_conn(self):
"""
Returns verticaql connection object
"""
conn = self.get_connection(self.vertica_conn_id)
conn_config = {
"user": conn.login,
"password": conn.password or '',
"database": conn.schema,
"host": conn.host or 'localhost'
}
if not conn.port:
conn_config["port"] = 5433
else:
conn_config["port"] = int(conn.port)
conn = connect(**conn_config)
return conn
| apache-2.0 |
MaximeBiset/care4care | main/migrations/0040_auto_20141205_1736.py | 1 | 12414 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import multiselectfield.db.fields
import django.core.validators
import re
class Migration(migrations.Migration):
dependencies = [
('main', '0039_merge'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='comments',
field=models.CharField(max_length=255, verbose_name='Additional comments', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='contact',
name='email',
field=models.EmailField(max_length=75, verbose_name='Email address', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='contact',
name='first_name',
field=models.CharField(max_length=30, verbose_name='First name'),
preserve_default=True,
),
migrations.AlterField(
model_name='contact',
name='languages',
field=multiselectfield.db.fields.MultiSelectField(max_length=8, verbose_name='Spoken languages', choices=[('fr', 'French'), ('en', 'English'), ('nl', 'Dutch')], blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='contact',
name='last_name',
field=models.CharField(max_length=30, verbose_name='Name'),
preserve_default=True,
),
migrations.AlterField(
model_name='contact',
name='location',
field=models.CharField(max_length=256, verbose_name='Address', null=True, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='contact',
name='mobile_number',
field=models.CharField(max_length=16, validators=[django.core.validators.RegexValidator(message="Your phone number must be in format '+99999999'. Up to 15 digits.", regex='^\\+?1?\\d{9,15}$')], verbose_name='Phone number (mobile)', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='contact',
name='phone_number',
field=models.CharField(max_length=16, validators=[django.core.validators.RegexValidator(message="Your phone number must be in format '+99999999'. Up to 15 digits.", regex='^\\+?1?\\d{9,15}$')], verbose_name='Phone number (home)', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='contact',
name='relationship',
field=models.CharField(max_length=255, verbose_name='Your relationship with that person', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='emergencycontact',
name='first_name',
field=models.CharField(max_length=30, verbose_name='First name'),
preserve_default=True,
),
migrations.AlterField(
model_name='emergencycontact',
name='languages',
field=multiselectfield.db.fields.MultiSelectField(max_length=8, verbose_name='Spoken languages', choices=[('fr', 'French'), ('en', 'English'), ('nl', 'Dutch')], blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='emergencycontact',
name='last_name',
field=models.CharField(max_length=30, verbose_name='Name'),
preserve_default=True,
),
migrations.AlterField(
model_name='emergencycontact',
name='location',
field=models.CharField(max_length=256, verbose_name='Address', null=True, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='emergencycontact',
name='mobile_number',
field=models.CharField(max_length=16, validators=[django.core.validators.RegexValidator(message="Your phone number must be in format '+99999999'. Up to 15 digits.", regex='^\\+?1?\\d{9,15}$')], verbose_name='Phone number (mobile)', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='emergencycontact',
name='order',
field=models.IntegerField(choices=[(1, 'First contact'), (2, 'Contact'), (3, 'Last contact')], default=0, verbose_name='Priority'),
preserve_default=True,
),
migrations.AlterField(
model_name='emergencycontact',
name='phone_number',
field=models.CharField(max_length=16, validators=[django.core.validators.RegexValidator(message="Your phone number must be in format '+99999999'. Up to 15 digits.", regex='^\\+?1?\\d{9,15}$')], verbose_name='Phone number (home)', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='birth_date',
field=models.DateField(verbose_name='Birthday', null=True, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='credit',
field=models.IntegerField(default=0, verbose_name='Remaining credit'),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(max_length=75, verbose_name='Email address'),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='first_name',
field=models.CharField(max_length=30, verbose_name='First name'),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='how_found',
field=multiselectfield.db.fields.MultiSelectField(max_length=41, verbose_name='How did you hear about care4care ?', choices=[('internet', 'The Internet'), ('show', 'A presentation, brochure, flyer,... '), ('branch', 'The local branch'), ('member', 'Another member'), ('friends', 'Friends or family'), ('other', 'Other')]),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='languages',
field=multiselectfield.db.fields.MultiSelectField(max_length=8, verbose_name='Spoken languages', choices=[('fr', 'French'), ('en', 'English'), ('nl', 'Dutch')], blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='last_name',
field=models.CharField(max_length=30, verbose_name='Name'),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='location',
field=models.CharField(max_length=256, verbose_name='Address', null=True, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='mobile_number',
field=models.CharField(max_length=16, validators=[django.core.validators.RegexValidator(message="Your phone number must be in format '+99999999'. Up to 15 digits.", regex='^\\+?1?\\d{9,15}$')], verbose_name='Phone number (mobile)', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='phone_number',
field=models.CharField(max_length=16, validators=[django.core.validators.RegexValidator(message="Your phone number must be in format '+99999999'. Up to 15 digits.", regex='^\\+?1?\\d{9,15}$')], verbose_name='Phone number (home)', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='status',
field=models.IntegerField(choices=[(1, 'Active'), (2, 'On vacation'), (3, 'Disabled')], default=1),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='user_type',
field=models.IntegerField(choices=[(1, 'Member'), (2, 'Non-member'), (3, 'Verified member')], verbose_name='Account type', default=1, help_text='A member can help or be helped while a non-member is a professional who registers to access patient data. Please choose the one that suits you'),
preserve_default=True,
),
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(max_length=30, unique=True, verbose_name='Username', validators=[django.core.validators.RegexValidator(re.compile('^[\\w.@+-]+$', 32), 'Enter a valid username. No more than 30 characters. There may be numbers andcharacters @/./+/-/_', 'invalid')]),
preserve_default=True,
),
migrations.AlterField(
model_name='verifiedinformation',
name='criminal_record',
field=models.FileField(upload_to='documents/', null=True, verbose_name='Criminal record'),
preserve_default=True,
),
migrations.AlterField(
model_name='verifiedinformation',
name='recomendation_letter_1',
field=models.FileField(upload_to='documents/', null=True, verbose_name='Letter of recommendation n°1'),
preserve_default=True,
),
migrations.AlterField(
model_name='verifiedinformation',
name='recomendation_letter_2',
field=models.FileField(upload_to='documents/', null=True, verbose_name='Letter de recommendation n°2'),
preserve_default=True,
),
migrations.AlterField(
model_name='verifieduser',
name='additional_info',
field=models.TextField(max_length=300, verbose_name='Additional information', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='verifieduser',
name='can_wheelchair',
field=models.BooleanField(choices=[(True, 'Yes'), (False, 'No')], verbose_name='Can you carry a wheelchair in your car?', default=False),
preserve_default=True,
),
migrations.AlterField(
model_name='verifieduser',
name='drive_license',
field=multiselectfield.db.fields.MultiSelectField(max_length=11, verbose_name='Type of driving license', choices=[(1, 'Moped'), (2, 'Motorcycle'), (3, 'Car'), (4, 'Truck'), (5, 'Bus'), (6, 'Tractor')], blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='verifieduser',
name='have_car',
field=models.BooleanField(choices=[(True, 'Yes'), (False, 'No')], verbose_name='Do you have a car?', default=False),
preserve_default=True,
),
migrations.AlterField(
model_name='verifieduser',
name='hobbies',
field=models.TextField(max_length=200, verbose_name='Your hobby', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='verifieduser',
name='mail_preferences',
field=models.IntegerField(choices=[(1, 'Message box'), (2, 'Mail')], default=1, verbose_name='Receive my messages'),
preserve_default=True,
),
migrations.AlterField(
model_name='verifieduser',
name='offered_job',
field=multiselectfield.db.fields.MultiSelectField(max_length=21, verbose_name='What jobs you want to do?', choices=[('1', 'Visit home'), ('2', 'Companionship'), ('3', 'Transport by car'), ('4', 'Shopping'), ('5', 'House sitting'), ('6', 'Manual jobs'), ('7', 'Gardening'), ('8', 'Pet sitting'), ('9', 'Personal care'), ('a', 'Administrative'), ('b', 'Other')], blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='verifieduser',
name='receive_help_from_who',
field=models.IntegerField(choices=[(5, 'All'), (3, 'Verified member'), (6, 'My favorite members')], default=5, verbose_name='Receive offers and demands'),
preserve_default=True,
),
]
| agpl-3.0 |
MIPS/external-chromium_org | third_party/protobuf/python/google/protobuf/internal/descriptor_database_test.py | 213 | 2872 | #! /usr/bin/python
#
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# http://code.google.com/p/protobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests for google.protobuf.descriptor_database."""
__author__ = 'matthewtoia@google.com (Matt Toia)'
import unittest
from google.protobuf import descriptor_pb2
from google.protobuf.internal import factory_test2_pb2
from google.protobuf import descriptor_database
class DescriptorDatabaseTest(unittest.TestCase):
def testAdd(self):
db = descriptor_database.DescriptorDatabase()
file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
factory_test2_pb2.DESCRIPTOR.serialized_pb)
db.Add(file_desc_proto)
self.assertEquals(file_desc_proto, db.FindFileByName(
'net/proto2/python/internal/factory_test2.proto'))
self.assertEquals(file_desc_proto, db.FindFileContainingSymbol(
'net.proto2.python.internal.Factory2Message'))
self.assertEquals(file_desc_proto, db.FindFileContainingSymbol(
'net.proto2.python.internal.Factory2Message.NestedFactory2Message'))
self.assertEquals(file_desc_proto, db.FindFileContainingSymbol(
'net.proto2.python.internal.Factory2Enum'))
self.assertEquals(file_desc_proto, db.FindFileContainingSymbol(
'net.proto2.python.internal.Factory2Message.NestedFactory2Enum'))
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
montanapr/Plugin.Video.Mercy | servers/rapidvideo.py | 34 | 2249 | # -*- coding: iso-8859-1 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para rapidvideo
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core import scrapertools
from core import logger
from core import config
USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:18.0) Gecko/20100101 Firefox/18.0"
def get_video_url( page_url , premium = False , user="" , password="", video_password="" ):
logger.info("[rapidvideo.py] url="+page_url)
video_urls=[]
from lib import mechanize
br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
br.set_handle_robots(False)
res = br.open(page_url)
print res.read()
for form in br.forms():
br.form = form
res = br.submit(name='imhuman')
page = res.read()
page = page.split('mp4|')
idLink = page[1].split('|')
ip2 = idLink[2]
ip3 = idLink[3]
video_urls.append(["[rapidvideo]","http://50.7."+ip3+"."+ip2+":8777/"+idLink[0]+"/v.mp4"])
return video_urls
# Encuentra vídeos de este servidor en el texto pasado
def find_videos(text):
encontrados = set()
devuelve = []
#http://www.rapidvideo.com/view/YK7A0L7FU3A
patronvideos = 'rapidvideo.org/([A-Za-z0-9]+)/'
logger.info("[rapidvideo.py] find_videos #"+patronvideos+"#")
matches = re.compile(patronvideos,re.DOTALL).findall(text)
for match in matches:
titulo = "[rapidvideo]"
url = "http://www.rapidvideo.org/"+match
d = scrapertools.cache_page(url)
ma = scrapertools.find_single_match(d,'"fname" value="([^<]+)"')
ma=titulo+" "+ma
if url not in encontrados:
logger.info(" url="+url)
devuelve.append( [ ma , url , 'rapidvideo' ] )
encontrados.add(url)
else:
logger.info(" url duplicada="+url)
return devuelve
def test():
video_urls = get_video_url("http://www.rapidvideo.com/embed/sy6wen17")
return len(video_urls)>0
| gpl-2.0 |
benjaminrigaud/django | django/core/serializers/base.py | 181 | 6813 | """
Module for abstract serializer/unserializer base classes.
"""
import warnings
from django.db import models
from django.utils import six
from django.utils.deprecation import RemovedInDjango19Warning
class SerializerDoesNotExist(KeyError):
"""The requested serializer was not found."""
pass
class SerializationError(Exception):
"""Something bad happened during serialization."""
pass
class DeserializationError(Exception):
"""Something bad happened during deserialization."""
pass
class Serializer(object):
"""
Abstract serializer base class.
"""
# Indicates if the implemented serializer is only available for
# internal Django use.
internal_use_only = False
def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.pop("stream", six.StringIO())
self.selected_fields = options.pop("fields", None)
self.use_natural_keys = options.pop("use_natural_keys", False)
if self.use_natural_keys:
warnings.warn("``use_natural_keys`` is deprecated; use ``use_natural_foreign_keys`` instead.",
RemovedInDjango19Warning)
self.use_natural_foreign_keys = options.pop('use_natural_foreign_keys', False) or self.use_natural_keys
self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False)
self.start_serialization()
self.first = True
for obj in queryset:
self.start_object(obj)
# Use the concrete parent class' _meta instead of the object's _meta
# This is to avoid local_fields problems for proxy models. Refs #17717.
concrete_model = obj._meta.concrete_model
for field in concrete_model._meta.local_fields:
if field.serialize:
if field.rel is None:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_field(obj, field)
else:
if self.selected_fields is None or field.attname[:-3] in self.selected_fields:
self.handle_fk_field(obj, field)
for field in concrete_model._meta.many_to_many:
if field.serialize:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_m2m_field(obj, field)
self.end_object(obj)
if self.first:
self.first = False
self.end_serialization()
return self.getvalue()
def start_serialization(self):
"""
Called when serializing of the queryset starts.
"""
raise NotImplementedError('subclasses of Serializer must provide a start_serialization() method')
def end_serialization(self):
"""
Called when serializing of the queryset ends.
"""
pass
def start_object(self, obj):
"""
Called when serializing of an object starts.
"""
raise NotImplementedError('subclasses of Serializer must provide a start_object() method')
def end_object(self, obj):
"""
Called when serializing of an object ends.
"""
pass
def handle_field(self, obj, field):
"""
Called to handle each individual (non-relational) field on an object.
"""
raise NotImplementedError('subclasses of Serializer must provide an handle_field() method')
def handle_fk_field(self, obj, field):
"""
Called to handle a ForeignKey field.
"""
raise NotImplementedError('subclasses of Serializer must provide an handle_fk_field() method')
def handle_m2m_field(self, obj, field):
"""
Called to handle a ManyToManyField.
"""
raise NotImplementedError('subclasses of Serializer must provide an handle_m2m_field() method')
def getvalue(self):
"""
Return the fully serialized queryset (or None if the output stream is
not seekable).
"""
if callable(getattr(self.stream, 'getvalue', None)):
return self.stream.getvalue()
class Deserializer(six.Iterator):
"""
Abstract base deserializer class.
"""
def __init__(self, stream_or_string, **options):
"""
Init this serializer given a stream or a string
"""
self.options = options
if isinstance(stream_or_string, six.string_types):
self.stream = six.StringIO(stream_or_string)
else:
self.stream = stream_or_string
def __iter__(self):
return self
def __next__(self):
"""Iteration iterface -- return the next item in the stream"""
raise NotImplementedError('subclasses of Deserializer must provide a __next__() method')
class DeserializedObject(object):
"""
A deserialized model.
Basically a container for holding the pre-saved deserialized data along
with the many-to-many data saved with the object.
Call ``save()`` to save the object (with the many-to-many data) to the
database; call ``save(save_m2m=False)`` to save just the object fields
(and not touch the many-to-many stuff.)
"""
def __init__(self, obj, m2m_data=None):
self.object = obj
self.m2m_data = m2m_data
def __repr__(self):
return "<DeserializedObject: %s.%s(pk=%s)>" % (
self.object._meta.app_label, self.object._meta.object_name, self.object.pk)
def save(self, save_m2m=True, using=None):
# Call save on the Model baseclass directly. This bypasses any
# model-defined save. The save is also forced to be raw.
# raw=True is passed to any pre/post_save signals.
models.Model.save_base(self.object, using=using, raw=True)
if self.m2m_data and save_m2m:
for accessor_name, object_list in self.m2m_data.items():
setattr(self.object, accessor_name, object_list)
# prevent a second (possibly accidental) call to save() from saving
# the m2m data twice.
self.m2m_data = None
def build_instance(Model, data, db):
"""
Build a model instance.
If the model instance doesn't have a primary key and the model supports
natural keys, try to retrieve it from the database.
"""
obj = Model(**data)
if (obj.pk is None and hasattr(Model, 'natural_key') and
hasattr(Model._default_manager, 'get_by_natural_key')):
natural_key = obj.natural_key()
try:
obj.pk = Model._default_manager.db_manager(db).get_by_natural_key(*natural_key).pk
except Model.DoesNotExist:
pass
return obj
| bsd-3-clause |
SolusOS-discontinued/pisi | scripts/make-changelog.py | 4 | 2280 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import urllib2
import piksemel
first_revision = "27898"
accounts_url = "http://svn.pardus.org.tr/uludag/trunk/common/accounts"
authors = {}
def get_author_name_mail(author):
if not authors:
accounts = urllib2.urlopen(accounts_url)
for line in accounts:
if line.startswith("#"):
continue
elif line.count(":") != 3:
continue
account, name, mail, jabber = line.split(":")
mail = mail.replace(" [at] ", "@")
authors[account] = "%s <%s>" % (name, mail)
return authors[author]
def cleanup_msg_lines(lines):
result = []
for line in lines:
if line.startswith("BUG:FIXED:"):
bug_number = line.split(":")[2]
line = "Fixes the bug reported at http://bugs.pardus.org.tr/%s." % bug_number
elif line.startswith("BUG:COMMENT:"):
bug_number = line.split(":")[2]
line = "See http://bugs.pardus.org.tr/%s." % bug_number
elif line.startswith("Changes since "):
return result[:-1]
result.append(line)
return result
def strip_empty_lines(msg):
result = []
for line in msg.splitlines():
if not line.strip():
line = ""
result.append(line)
return "\n".join(result)
def create_log_entry(author, date, msg):
if author == "transifex":
return None
author = get_author_name_mail(author)
date = date.split("T", 1)[0]
lines = msg.splitlines()
lines = cleanup_msg_lines(lines)
lines[0] = "\t* %s" % lines[0]
msg = "\n\t".join(lines)
msg = strip_empty_lines(msg)
entry = "%s %s\n%s" % (date, author, msg)
return entry
if __name__ == "__main__":
p = os.popen("svn log -r%s:HEAD --xml" % first_revision)
doc = piksemel.parseString(p.read())
entries = []
for log_entry in doc.tags("logentry"):
author = log_entry.getTagData("author")
date = log_entry.getTagData("date")
msg = log_entry.getTagData("msg")
entry = create_log_entry(author, date, msg.strip())
if entry:
entries.append(entry)
entries.reverse()
open("ChangeLog", "w").write("\n\n".join(entries))
| gpl-2.0 |
divergentdave/inspectors-general | inspectors/treasury.py | 2 | 15149 | #!/usr/bin/env python
import datetime
import logging
import os
import re
from urllib.parse import urljoin, unquote
from utils import utils, inspector, admin
# https://www.treasury.gov/about/organizational-structure/ig/Pages/audit_reports_index.aspx
archive = 2005
# options:
# standard since/year options for a year range to fetch from.
#
# Notes for IG's web team:
# - Add an agency for report 'OIG-09-015' listed on
# https://www.treasury.gov/about/organizational-structure/ig/Pages/by-date-2009.aspx
# - There is an extra tr.ms-rteTableEvenRow-default at the end of
# https://www.treasury.gov/about/organizational-structure/ig/Pages/by-date-2014.aspx
# - Add published dates for all reports at
# https://www.treasury.gov/about/organizational-structure/ig/Pages/other-reports.aspx
# - OIG-07-003 is posted twice, once with the wrong date
AUDIT_REPORTS_BASE_URL = "https://www.treasury.gov/about/organizational-structure/ig/Pages/by-date-{}.aspx"
TESTIMONIES_URL = "https://www.treasury.gov/about/organizational-structure/ig/Pages/testimony_index.aspx"
PEER_AUDITS_URL = "https://www.treasury.gov/about/organizational-structure/ig/Pages/peer_audit_reports_index.aspx"
OTHER_REPORTS_URL = "https://www.treasury.gov/about/organizational-structure/ig/Pages/other-reports.aspx"
SEMIANNUAL_REPORTS_URL = "https://www.treasury.gov/about/organizational-structure/ig/Pages/semiannual_reports_index.aspx"
AGENCY_NAMES = {
"bep": "The Bureau of Engraving & Printing",
"bfs": "The Bureau of the Fiscal Service",
"bpd": "The Bureau of the Public",
"cdfi": "The Community Development Financial Institution Fund",
"cfpb": "Consumer Financial Protection Bureau",
"do": "Department of the Treasury",
"esf": "Exchange Stabilization Fund",
"ffb": "Federal Financing Bank",
"fcen": "The Financial Crimes Enforcement Network",
"fincen": "The Financial Crimes Enforcement Network", # Another slug for the above
"fms": "Financial Management Service",
"gcerc": "Gulf Coast Ecosystem Restoration Council",
"ia": "The Office of International Affairs",
"mint": "The U.S. Mint",
"occ": "The Office of the Comptroller of the Currency",
"odcp": "Office of DC Pensions",
"ofac": "The Office of Foreign Assets Control",
"ofr": "Office of Financial Research",
"oig": "Office of the Inspector General",
"ots": "The Office of Thrift",
"restore": "The RESTORE Act",
"sblf": "Small Business Lending Fund",
"ssbci": "State Small Business Credit Initiative",
"tfi": "Office of Terrorism and Financial Intelligence",
"ttb": "The Alcohol and Tobacco Tax and Trade Bureau",
"tff": "Treasury Forfeiture Fund",
}
OTHER_URLS = {
"testimony": TESTIMONIES_URL,
"peer_review": PEER_AUDITS_URL,
"other": OTHER_REPORTS_URL,
}
UNRELEASED_REPORTS = [
# These reports do not say they are unreleased, but there are no links
"IGATI 2006",
"IGATI 2007",
"OIG-CA-07-001",
"OIG-08-039",
"OIG-08-013",
]
REPORT_AGENCY_MAP = {
"OIG-09-015": "mint", # See note to IG web team
}
REPORT_PUBLISHED_MAP = {
"OIG-CA-13-006": datetime.datetime(2013, 3, 29),
"OIG-13-CA-008": datetime.datetime(2013, 6, 10),
"Treasury Freedom of Information Act (FOIA) Request Review": datetime.datetime(2010, 11, 19),
"OIG-CA-14-017": datetime.datetime(2014, 9, 30),
"OIG-CA-14-015": datetime.datetime(2014, 9, 4),
"OIG-CA-15-023": datetime.datetime(2015, 7, 29),
"OIG-CA-15-020": datetime.datetime(2015, 6, 22),
"OIG-15-CA-012": datetime.datetime(2015, 4, 7),
"OIG-CA-15-024": datetime.datetime(2015, 9, 15),
"M-12-12 Reporting": datetime.datetime(2016, 1, 28),
"OIG-CA-16-012": datetime.datetime(2016, 3, 30),
"OIG-CA-16-014": datetime.datetime(2016, 4, 19),
"Role of Non-Career Officials in Treasury FOIA Processing": datetime.datetime(2016, 3, 9),
"OIG-CA-16-028": datetime.datetime(2016, 6, 30),
"OIG-CA-16-033A": datetime.datetime(2016, 7, 29),
"OIG-CA-16-033B": datetime.datetime(2016, 7, 29),
"OIG-CA-17-006": datetime.datetime(2016, 11, 10),
"OIG-CA-17-009": datetime.datetime(2017, 1, 27),
"OIG-CA-17-010": datetime.datetime(2017, 1, 27),
"OIG-CA-17-012": datetime.datetime(2017, 2, 27),
"OIG-CA-17-013": datetime.datetime(2017, 3, 1),
}
def run(options):
year_range = inspector.year_range(options, archive)
if datetime.datetime.now().month >= 10:
# October, November, and December fall into the next fiscal year
# Add next year to year_range to compensate
year_range.append(max(year_range) + 1)
# Pull the audit reports
for year in year_range:
if year < 2006: # This is the oldest year for these reports
continue
url = AUDIT_REPORTS_BASE_URL.format(year)
doc = utils.beautifulsoup_from_url(url)
results = doc.find_all("tr", class_=["ms-rteTableOddRow-default",
"ms-rteTableEvenRow-default"])
if not results:
if year != datetime.datetime.now().year + 1:
raise inspector.NoReportsFoundError("Treasury (%d)" % year)
for result in results:
report = audit_report_from(result, url, year_range)
if report:
inspector.save_report(report)
for report_type, url in OTHER_URLS.items():
doc = utils.beautifulsoup_from_url(url)
results = doc.select("#ctl00_PlaceHolderMain_ctl05_ctl01__ControlWrapper_RichHtmlField > p a")
if not results:
raise inspector.NoReportsFoundError("Treasury (%s)" % report_type)
for result in results:
if len(result.parent.find_all("a")) == 1:
result = result.parent
report = report_from(result, url, report_type, year_range)
if report:
inspector.save_report(report)
doc = utils.beautifulsoup_from_url(SEMIANNUAL_REPORTS_URL)
results = doc.select("#ctl00_PlaceHolderMain_ctl05_ctl01__ControlWrapper_RichHtmlField > p > a")
if not results:
raise inspector.NoReportsFoundError("Treasury (semiannual reports)")
for result in results:
report = semiannual_report_from(result, SEMIANNUAL_REPORTS_URL, year_range)
if report:
inspector.save_report(report)
def clean_text(text):
# A lot of text on this page has extra characters
return text.replace('\u200b', '').replace('\ufffd', ' ').replace('\xa0', ' ').strip()
SUMMARY_RE = re.compile("(OIG|OIG-CA|EVAL) *-? *([0-9]+) *- *([0-9R]+) *[:,]? +([^ ].*)")
SUMMARY_FALLBACK_RE = re.compile("([0-9]+)-(OIG)-([0-9]+) *:? *(.*)")
FILENAME_RE = re.compile("^(OIG-[0-9]+-[0-9]+)\\.pdf")
def audit_report_from(result, page_url, year_range):
if not clean_text(result.text):
# Empty row
return
# Get all direct child nodes
children = list(result.find_all(True, recursive=False))
published_on_text = clean_text(children[1].text)
# this is the header row
if published_on_text.strip() == "Date":
return None
date_formats = ['%m/%d/%Y', '%m/%d%Y']
published_on = None
for date_format in date_formats:
try:
published_on = datetime.datetime.strptime(published_on_text, date_format)
except ValueError:
pass
report_summary = clean_text(children[2].text)
if not report_summary:
# There is an extra row that we want to skip
return
report_summary = report_summary.replace("OIG-15-38Administrative",
"OIG-15-38 Administrative")
summary_match = SUMMARY_RE.match(report_summary)
summary_match_2 = SUMMARY_FALLBACK_RE.match(report_summary)
if summary_match:
report_id = summary_match.expand(r"\1-\2-\3")
title = summary_match.group(4)
elif summary_match_2:
report_id = summary_match_2.expand(r"(\2-\1-\3")
title = summary_match_2.group(4)
elif report_summary.startswith("IGATI") and published_on is not None:
# There are two such annual reports from different years, append the year
report_id = "IGATI %d" % published_on.year
title = report_summary
elif report_summary == "Report on the Bureau of the Fiscal Service Federal " \
"Investments Branch\u2019s Description of its Investment/" \
"Redemption Services and the Suitability of the Design and Operating " \
"Effectiveness of its Controls for the Period August 1, 2013 to " \
"July 31, 2014":
# This one is missing its ID in the index
report_id = "OIG-14-049"
title = report_summary
elif report_summary == "Correspondence related to the resolution of audit recommendation 1 OIG-16-001 OFAC Libyan Sanctions Case Study (Please read this correspondence in conjunction with the report.)":
# Need to make up a report_id for this supplemental document
report_id = "OIG-16-001-resolution"
title = report_summary
else:
try:
filename_match = FILENAME_RE.match(os.path.basename(result.a["href"]))
report_id = filename_match.group(1)
title = report_summary
except (ValueError, IndexError, AttributeError):
raise Exception("Couldn't parse report ID: %s" % repr(report_summary))
if report_id == 'OIG-15-015' and \
'Financial Statements for hte Fiscal Years 2014 and 2013' in title:
# This report is listed twice, once with a typo
return
if report_id == 'OIG-07-003' and published_on_text == '11/23/2006':
# This report is listed twice, once with the wrong date
return
# There are copy-paste errors with several retracted reports
if report_id == 'OIG-14-037':
if published_on.year == 2011 or published_on.year == 2010:
return
if report_id == 'OIG-13-021' and published_on_text == '12/12/2012':
return
if published_on is None:
admin.log_no_date("treasury", report_id, title)
return
agency_slug_text = children[0].text
if report_id in REPORT_AGENCY_MAP:
agency_slug = REPORT_AGENCY_MAP[report_id]
else:
agency_slug = clean_text(agency_slug_text.split("&")[0]).lower()
if (report_id in UNRELEASED_REPORTS or
"If you would like a copy of this report" in report_summary or
"If you would like to see a copy of this report" in report_summary or
"have been removed from the OIG website" in report_summary or
"removed the auditors\u2019 reports from the" in report_summary or
"Classified Report" in report_summary or
"Classified Audit Report" in report_summary or
"Sensitive But Unclassified" in report_summary or
"To obtain further information, please contact the OIG" in report_summary):
unreleased = True
report_url = None
landing_url = page_url
else:
link = result.select("a")[0]
report_url = urljoin(AUDIT_REPORTS_BASE_URL, link['href'])
if report_url == AUDIT_REPORTS_BASE_URL:
raise Exception("Invalid link found: %s" % link)
unreleased = False
landing_url = None
# HTTPS, even if they haven't updated their links yet
if report_url is not None:
report_url = re.sub("^http://www.treasury.gov", "https://www.treasury.gov", report_url)
if report_url == "https://www.treasury.gov/about/organizational-structure/ig/Documents/OIG-11-071.pdf":
report_url = "https://www.treasury.gov/about/organizational-structure/ig/Documents/OIG11071.pdf"
if published_on.year not in year_range:
logging.debug("[%s] Skipping, not in requested range." % report_url)
return
report = {
'inspector': 'treasury',
'inspector_url': 'https://www.treasury.gov/about/organizational-structure/ig/',
'agency': agency_slug,
'agency_name': AGENCY_NAMES[agency_slug],
'type': 'audit',
'report_id': report_id,
'url': report_url,
'title': title,
'published_on': datetime.datetime.strftime(published_on, "%Y-%m-%d"),
}
if unreleased:
report['unreleased'] = unreleased
if landing_url:
report['landing_url'] = landing_url
return report
def report_from(result, page_url, report_type, year_range):
try:
title, date1, date2 = result.text.rsplit(",", 2)
published_on_text = date1 + date2
published_on = datetime.datetime.strptime(published_on_text.strip(), '%B %d %Y')
except ValueError:
try:
title, date1, date2, date3 = result.text.rsplit(maxsplit=3)
published_on_text = date1 + date2 + date3
published_on = datetime.datetime.strptime(published_on_text.strip(), '%B%d,%Y')
except ValueError:
title = result.text
published_on = None
title = clean_text(title)
original_title = title
report_id, title = title.split(maxsplit=1)
report_id = report_id.rstrip(":")
if result.name == "a":
link = result
else:
link = result.a
report_url = urljoin(page_url, link['href'])
# HTTPS, even if they haven't updated their links yet
report_url = re.sub("^http://www.treasury.gov", "https://www.treasury.gov", report_url)
if report_id.find('-') == -1:
# If the first word of the text doesn't contain a hyphen,
# then it's probably part of the title, and not a tracking number.
# In this case, fall back to the URL.
report_filename = report_url.split("/")[-1]
report_id, extension = os.path.splitext(report_filename)
report_id = unquote(report_id)
# Reset the title, since we previously stripped off the first word
# as a candidate report_id.
title = original_title
if report_id in REPORT_PUBLISHED_MAP:
published_on = REPORT_PUBLISHED_MAP[report_id]
if not published_on:
admin.log_no_date("treasury", report_id, title, report_url)
return
# Skip this report, it already shows up under other audit reports
if report_id == "Role of Non-Career Officials in Treasury FOIA Processing":
return
if published_on.year not in year_range:
logging.debug("[%s] Skipping, not in requested range." % report_url)
return
report = {
'inspector': 'treasury',
'inspector_url': 'https://www.treasury.gov/about/organizational-structure/ig/',
'agency': 'treasury',
'agency_name': "Department of the Treasury",
'type': report_type,
'report_id': report_id,
'url': report_url,
'title': title,
'published_on': datetime.datetime.strftime(published_on, "%Y-%m-%d"),
}
return report
def semiannual_report_from(result, page_url, year_range):
published_on_text = clean_text(result.text)
published_on = datetime.datetime.strptime(published_on_text.strip(), '%B %d, %Y')
title = "Semiannual Report - {}".format(published_on_text)
report_url = urljoin(page_url, result['href'])
# HTTPS, even if they haven't updated their links yet
report_url = re.sub("^http://www.treasury.gov", "https://www.treasury.gov", report_url)
report_filename = report_url.split("/")[-1]
report_id, extension = os.path.splitext(report_filename)
report_id = unquote(report_id)
if published_on.year not in year_range:
logging.debug("[%s] Skipping, not in requested range." % report_url)
return
report = {
'inspector': 'treasury',
'inspector_url': 'https://www.treasury.gov/about/organizational-structure/ig/',
'agency': 'treasury',
'agency_name': "Department of the Treasury",
'type': 'semiannual_report',
'report_id': report_id,
'url': report_url,
'title': title,
'published_on': datetime.datetime.strftime(published_on, "%Y-%m-%d"),
}
return report
utils.run(run) if (__name__ == "__main__") else None
| cc0-1.0 |
martinbalsam/timing-rp | timingrp/sanit.py | 1 | 2984 | import re
import argparse
"""
This script sanitize the raw data experted from "Timing.app",
it adds the proper double quotes around the "Path" attribute,
and it removes unwanted double quotes inside the "Path" attribute,
that may yield an unwanted escape of the field.
--- TODO ---
speedup:
as for now I'm iterating twice over the whole list,
Maybe the sanitizing can be done in a single regex, but I spent waay to much time
coming up with these. I'll leave it to somebody else (noone)
cleanup:
delete unused files
"""
parser = argparse.ArgumentParser(description="writes the input data into a sanitized .csv file")
parser.add_argument('path', nargs=1, type = str, help='the path of the input raw .csv file to parse')
args = parser.parse_args()
"""paths of the input and output data
each file has the same name structure:
file.csv
file_tmp_.csv
file_san_.csv (THIS IS THE OUTPUT WE WANT, SANITIZED AND SHIT)
file_err_.log
"""
input_data = args.path[0]
temp_data = args.path[0][:-4]+"_tmp_.csv"
output_data = args.path[0][:-4]+"_san_.csv"
errors_log = args.path[0][:-4]+"_err_.log"
#THIS SHIT WORKS IF THERE ARE NO UNEXPECTED BREAKLINE
errors = open(errors_log,'w')
with open(input_data,'r') as original:
with open(temp_data,'w') as new:
#writes the csv header
new.write(original.readline())
for line in original:
#regex to isolate the 'path' attribute
matches = re.search('(^[^,]+,)(.*)(,\d{2}/\d{2}/\d{2} \d{2}:\d{2},\d{2}/\d{2}/\d{2} \d{2}:\d{2},.*$)', line)
try:
#add quotation around the path attribute and writes it in a new file
new.write(matches.group(1)+'"'+matches.group(2)+'"'+matches.group(3)+'\n')
#catches lines that don't match the regex and writes them in an errors.log file
except AttributeError:
errors.write(line)
continue
#Now I recheck the whole list to catch if there are extra double quotation signs (") in the path attribute,
#if so, we delete them
with open(temp_data,'r') as old:
with open(output_data,'w') as new:
new.write(old.readline())
for line in old:
#regex that catches any path that contains one or more double quotation sign (")
matches = re.search('(^[^,]+,")(.*".*)(",\d{2}/\d{2}/\d{2} \d{2}:\d{2},\d{2}/\d{2}/\d{2} \d{2}:\d{2},.*$)', line)
if matches is not None:
#deletes any double quotation mark (") and writes tha sanitized line in a new file
new.write(matches.group(1)+matches.group(2).replace('"','')+matches.group(3)+'\n')
#if the line is ok, it just writes the line in the new file
else:
new.write(line)
#populate a panda DataFrame object with the data, and the proper datetime objects
"""dateparse = lambda x: pd.datetime.strptime(x, '%d/%m/%y %H:%M')
a = pd.read_csv('bin/fine.csv', parse_dates=[2,3], date_parser=dateparse)
"""
| gpl-2.0 |
kirbyfan64/shedskin | examples/mandelbrot2_main.py | 6 | 3732 | # interactive mandelbrot program
# copyright Tony Veijalainen, tony.veijalainen@gmail.com
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
import os
from PIL import Image, ImageTk
from mandelbrot2 import mandel_file
main_file = 'm-1 0i_3.5_240.bmp'
class MandelbrotTk(tk.Tk):
def __init__(self, width=640, height=480, image_file=main_file):
tk.Tk.__init__(self)
self.canvas = tk.Canvas(width=width, height=height)
self.geometry("%sx%s+100+100" % (width,height+40))
self.canvas.pack()
self.item = None
self.label = tk.Label(self.canvas, font=('courier', 10))
self.parameters_from_fn(image_file)
if not os.path.isfile(image_file):
self.image_file = mandel_file(self.cx, self.cy, self.fsize, self.max_iterations)
print('Mainfile %s generated' % self.image_file)
else:
self.image_file = image_file
self.label.pack(side=tk.BOTTOM)
self.canvas.image = self.load_image()
self.x, self.y, self.size = None, None, (0,)
self.bind("<Button-2>", self.recalculate)
# Linux
self.bind("<Button-1>", self.zoom_in)
self.bind("<Button-3>", self.zoom_out)
# Windows
self.bind("<MouseWheel>", self.mouse_wheel)
def recalculate(self, event):
print('recalculating')
self.image_file = mandel_file(self.cx, self.cy, self.fsize, self.max_iterations)
self.canvas.image = self.load_image()
self.update_label()
def parameters_from_fn(self, fn):
# extract parameters from name
ipos = fn.find('i')
self.cx, self.cy = map(float, fn[1:ipos].split())
self.fsize, rest = fn[ipos+2:].split('_', 1)
self.fsize = float(self.fsize)
self.max_iterations = int(rest.split('.',1)[0])
self.update_label()
def load_image(self):
self.canvas.delete('m')
photo = Image.open(self.image_file)
im = ImageTk.PhotoImage(photo)
self.canvas.create_image(0, 0, image=im, anchor='nw', tag='m')
self.canvas.pack(fill=tk.BOTH, expand=tk.YES)
self.max_iterations = min(max(self.max_iterations, 256), 10000)
self.update_label()
self.step = self.fsize / max(im.width(), im.height())
return im
def update_label(self):
self.label['text'] = ('cx: %g, cy: %g, fsize: %g, max_iterations: %i' %
(self.cx, self.cy, self.fsize, self.max_iterations))
def zoom_in(self, event):
print('ZOOM in')
xshift, yshift = event.x - self.canvas.image.width() // 2, self.canvas.image.height() // 2 - event.y
self.fsize /= 4.0
self.cx, self.cy = xshift * self.step + self.cx, yshift * self.step + self.cy
self.image_file = mandel_file(self.cx, self.cy, self.fsize, self.max_iterations)
self.canvas.image = self.load_image()
def zoom_out(self, event):
print('zoom out')
xshift, yshift = event.x - self.canvas.image.width() // 2, self.canvas.image.height() // 2 - event.y
self.fsize *= 4.0
self.cx, self.cy = xshift * self.step + self.cx, yshift * self.step + self.cy
self.image_file = mandel_file(self.cx, self.cy, self.fsize, self.max_iterations)
self.canvas.image = self.load_image()
def mouse_wheel(self, event):
"""respond to Linux or Windows wheel event"""
if event.num == 5 or event.delta == -120:
self.max_iterations -= 120
if event.num == 4 or event.delta == 120:
self.max_iterations += 120
self.update_label()
if __name__ == '__main__':
mand = MandelbrotTk()
mand.mainloop()
| gpl-3.0 |
curtisstpierre/django | tests/migrations/test_state.py | 96 | 43522 | from django.apps.registry import Apps
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.db.migrations.exceptions import InvalidBasesError
from django.db.migrations.operations import (
AddField, AlterField, DeleteModel, RemoveField,
)
from django.db.migrations.state import (
ModelState, ProjectState, get_related_models_recursive,
)
from django.test import SimpleTestCase, override_settings
from django.utils import six
from .models import (
FoodManager, FoodQuerySet, ModelWithCustomBase, NoMigrationFoodManager,
UnicodeModel,
)
class StateTests(SimpleTestCase):
"""
Tests state construction, rendering and modification by operations.
"""
def test_create(self):
"""
Tests making a ProjectState from an Apps
"""
new_apps = Apps(["migrations"])
class Author(models.Model):
name = models.CharField(max_length=255)
bio = models.TextField()
age = models.IntegerField(blank=True, null=True)
class Meta:
app_label = "migrations"
apps = new_apps
unique_together = ["name", "bio"]
index_together = ["bio", "age"]
class AuthorProxy(Author):
class Meta:
app_label = "migrations"
apps = new_apps
proxy = True
ordering = ["name"]
class SubAuthor(Author):
width = models.FloatField(null=True)
class Meta:
app_label = "migrations"
apps = new_apps
class Book(models.Model):
title = models.CharField(max_length=1000)
author = models.ForeignKey(Author, models.CASCADE)
contributors = models.ManyToManyField(Author)
class Meta:
app_label = "migrations"
apps = new_apps
verbose_name = "tome"
db_table = "test_tome"
class Food(models.Model):
food_mgr = FoodManager('a', 'b')
food_qs = FoodQuerySet.as_manager()
food_no_mgr = NoMigrationFoodManager('x', 'y')
class Meta:
app_label = "migrations"
apps = new_apps
class FoodNoManagers(models.Model):
class Meta:
app_label = "migrations"
apps = new_apps
class FoodNoDefaultManager(models.Model):
food_no_mgr = NoMigrationFoodManager('x', 'y')
food_mgr = FoodManager('a', 'b')
food_qs = FoodQuerySet.as_manager()
class Meta:
app_label = "migrations"
apps = new_apps
mgr1 = FoodManager('a', 'b')
mgr2 = FoodManager('x', 'y', c=3, d=4)
class FoodOrderedManagers(models.Model):
# The managers on this model should be ordered by their creation
# counter and not by the order in model body
food_no_mgr = NoMigrationFoodManager('x', 'y')
food_mgr2 = mgr2
food_mgr1 = mgr1
class Meta:
app_label = "migrations"
apps = new_apps
project_state = ProjectState.from_apps(new_apps)
author_state = project_state.models['migrations', 'author']
author_proxy_state = project_state.models['migrations', 'authorproxy']
sub_author_state = project_state.models['migrations', 'subauthor']
book_state = project_state.models['migrations', 'book']
food_state = project_state.models['migrations', 'food']
food_no_managers_state = project_state.models['migrations', 'foodnomanagers']
food_no_default_manager_state = project_state.models['migrations', 'foodnodefaultmanager']
food_order_manager_state = project_state.models['migrations', 'foodorderedmanagers']
self.assertEqual(author_state.app_label, "migrations")
self.assertEqual(author_state.name, "Author")
self.assertEqual([x for x, y in author_state.fields], ["id", "name", "bio", "age"])
self.assertEqual(author_state.fields[1][1].max_length, 255)
self.assertEqual(author_state.fields[2][1].null, False)
self.assertEqual(author_state.fields[3][1].null, True)
self.assertEqual(author_state.options, {"unique_together": {("name", "bio")}, "index_together": {("bio", "age")}})
self.assertEqual(author_state.bases, (models.Model, ))
self.assertEqual(book_state.app_label, "migrations")
self.assertEqual(book_state.name, "Book")
self.assertEqual([x for x, y in book_state.fields], ["id", "title", "author", "contributors"])
self.assertEqual(book_state.fields[1][1].max_length, 1000)
self.assertEqual(book_state.fields[2][1].null, False)
self.assertEqual(book_state.fields[3][1].__class__.__name__, "ManyToManyField")
self.assertEqual(book_state.options, {"verbose_name": "tome", "db_table": "test_tome"})
self.assertEqual(book_state.bases, (models.Model, ))
self.assertEqual(author_proxy_state.app_label, "migrations")
self.assertEqual(author_proxy_state.name, "AuthorProxy")
self.assertEqual(author_proxy_state.fields, [])
self.assertEqual(author_proxy_state.options, {"proxy": True, "ordering": ["name"]})
self.assertEqual(author_proxy_state.bases, ("migrations.author", ))
self.assertEqual(sub_author_state.app_label, "migrations")
self.assertEqual(sub_author_state.name, "SubAuthor")
self.assertEqual(len(sub_author_state.fields), 2)
self.assertEqual(sub_author_state.bases, ("migrations.author", ))
# The default manager is used in migrations
self.assertEqual([name for name, mgr in food_state.managers], ['food_mgr'])
self.assertTrue(all(isinstance(name, six.text_type) for name, mgr in food_state.managers))
self.assertEqual(food_state.managers[0][1].args, ('a', 'b', 1, 2))
# No explicit managers defined. Migrations will fall back to the default
self.assertEqual(food_no_managers_state.managers, [])
# food_mgr is used in migration but isn't the default mgr, hence add the
# default
self.assertEqual([name for name, mgr in food_no_default_manager_state.managers],
['food_no_mgr', 'food_mgr'])
self.assertTrue(all(isinstance(name, six.text_type) for name, mgr in food_no_default_manager_state.managers))
self.assertEqual(food_no_default_manager_state.managers[0][1].__class__, models.Manager)
self.assertIsInstance(food_no_default_manager_state.managers[1][1], FoodManager)
self.assertEqual([name for name, mgr in food_order_manager_state.managers],
['food_mgr1', 'food_mgr2'])
self.assertTrue(all(isinstance(name, six.text_type) for name, mgr in food_order_manager_state.managers))
self.assertEqual([mgr.args for name, mgr in food_order_manager_state.managers],
[('a', 'b', 1, 2), ('x', 'y', 3, 4)])
def test_custom_default_manager_added_to_the_model_state(self):
"""
When the default manager of the model is a custom manager,
it needs to be added to the model state.
"""
new_apps = Apps(['migrations'])
custom_manager = models.Manager()
class Author(models.Model):
objects = models.TextField()
authors = custom_manager
class Meta:
app_label = 'migrations'
apps = new_apps
project_state = ProjectState.from_apps(new_apps)
author_state = project_state.models['migrations', 'author']
self.assertEqual(author_state.managers, [('authors', custom_manager)])
def test_apps_bulk_update(self):
"""
StateApps.bulk_update() should update apps.ready to False and reset
the value afterwards.
"""
project_state = ProjectState()
apps = project_state.apps
with apps.bulk_update():
self.assertFalse(apps.ready)
self.assertTrue(apps.ready)
with self.assertRaises(ValueError):
with apps.bulk_update():
self.assertFalse(apps.ready)
raise ValueError()
self.assertTrue(apps.ready)
def test_render(self):
"""
Tests rendering a ProjectState into an Apps.
"""
project_state = ProjectState()
project_state.add_model(ModelState(
app_label="migrations",
name="Tag",
fields=[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=100)),
("hidden", models.BooleanField()),
],
))
project_state.add_model(ModelState(
app_label="migrations",
name="SubTag",
fields=[
('tag_ptr', models.OneToOneField(
'migrations.Tag',
models.CASCADE,
auto_created=True,
primary_key=True,
to_field='id',
serialize=False,
)),
("awesome", models.BooleanField()),
],
bases=("migrations.Tag",),
))
base_mgr = models.Manager()
mgr1 = FoodManager('a', 'b')
mgr2 = FoodManager('x', 'y', c=3, d=4)
project_state.add_model(ModelState(
app_label="migrations",
name="Food",
fields=[
("id", models.AutoField(primary_key=True)),
],
managers=[
# The ordering we really want is objects, mgr1, mgr2
('default', base_mgr),
('food_mgr2', mgr2),
(b'food_mgr1', mgr1),
]
))
new_apps = project_state.apps
self.assertEqual(new_apps.get_model("migrations", "Tag")._meta.get_field("name").max_length, 100)
self.assertEqual(new_apps.get_model("migrations", "Tag")._meta.get_field("hidden").null, False)
self.assertEqual(len(new_apps.get_model("migrations", "SubTag")._meta.local_fields), 2)
Food = new_apps.get_model("migrations", "Food")
managers = sorted(Food._meta.managers)
self.assertEqual([mgr.name for _, mgr, _ in managers],
['default', 'food_mgr1', 'food_mgr2'])
self.assertTrue(all(isinstance(mgr.name, six.text_type) for _, mgr, _ in managers))
self.assertEqual([mgr.__class__ for _, mgr, _ in managers],
[models.Manager, FoodManager, FoodManager])
self.assertIs(managers[0][1], Food._default_manager)
def test_render_model_inheritance(self):
class Book(models.Model):
title = models.CharField(max_length=1000)
class Meta:
app_label = "migrations"
apps = Apps()
class Novel(Book):
class Meta:
app_label = "migrations"
apps = Apps()
# First, test rendering individually
apps = Apps(["migrations"])
# We shouldn't be able to render yet
ms = ModelState.from_model(Novel)
with self.assertRaises(InvalidBasesError):
ms.render(apps)
# Once the parent model is in the app registry, it should be fine
ModelState.from_model(Book).render(apps)
ModelState.from_model(Novel).render(apps)
def test_render_model_with_multiple_inheritance(self):
class Foo(models.Model):
class Meta:
app_label = "migrations"
apps = Apps()
class Bar(models.Model):
class Meta:
app_label = "migrations"
apps = Apps()
class FooBar(Foo, Bar):
class Meta:
app_label = "migrations"
apps = Apps()
class AbstractSubFooBar(FooBar):
class Meta:
abstract = True
apps = Apps()
class SubFooBar(AbstractSubFooBar):
class Meta:
app_label = "migrations"
apps = Apps()
apps = Apps(["migrations"])
# We shouldn't be able to render yet
ms = ModelState.from_model(FooBar)
with self.assertRaises(InvalidBasesError):
ms.render(apps)
# Once the parent models are in the app registry, it should be fine
ModelState.from_model(Foo).render(apps)
self.assertSequenceEqual(ModelState.from_model(Foo).bases, [models.Model])
ModelState.from_model(Bar).render(apps)
self.assertSequenceEqual(ModelState.from_model(Bar).bases, [models.Model])
ModelState.from_model(FooBar).render(apps)
self.assertSequenceEqual(ModelState.from_model(FooBar).bases, ['migrations.foo', 'migrations.bar'])
ModelState.from_model(SubFooBar).render(apps)
self.assertSequenceEqual(ModelState.from_model(SubFooBar).bases, ['migrations.foobar'])
def test_render_project_dependencies(self):
"""
Tests that the ProjectState render method correctly renders models
to account for inter-model base dependencies.
"""
new_apps = Apps()
class A(models.Model):
class Meta:
app_label = "migrations"
apps = new_apps
class B(A):
class Meta:
app_label = "migrations"
apps = new_apps
class C(B):
class Meta:
app_label = "migrations"
apps = new_apps
class D(A):
class Meta:
app_label = "migrations"
apps = new_apps
class E(B):
class Meta:
app_label = "migrations"
apps = new_apps
proxy = True
class F(D):
class Meta:
app_label = "migrations"
apps = new_apps
proxy = True
# Make a ProjectState and render it
project_state = ProjectState()
project_state.add_model(ModelState.from_model(A))
project_state.add_model(ModelState.from_model(B))
project_state.add_model(ModelState.from_model(C))
project_state.add_model(ModelState.from_model(D))
project_state.add_model(ModelState.from_model(E))
project_state.add_model(ModelState.from_model(F))
final_apps = project_state.apps
self.assertEqual(len(final_apps.get_models()), 6)
# Now make an invalid ProjectState and make sure it fails
project_state = ProjectState()
project_state.add_model(ModelState.from_model(A))
project_state.add_model(ModelState.from_model(B))
project_state.add_model(ModelState.from_model(C))
project_state.add_model(ModelState.from_model(F))
with self.assertRaises(InvalidBasesError):
project_state.apps
def test_render_unique_app_labels(self):
"""
Tests that the ProjectState render method doesn't raise an
ImproperlyConfigured exception about unique labels if two dotted app
names have the same last part.
"""
class A(models.Model):
class Meta:
app_label = "django.contrib.auth"
class B(models.Model):
class Meta:
app_label = "vendor.auth"
# Make a ProjectState and render it
project_state = ProjectState()
project_state.add_model(ModelState.from_model(A))
project_state.add_model(ModelState.from_model(B))
self.assertEqual(len(project_state.apps.get_models()), 2)
def test_add_relations(self):
"""
#24573 - Adding relations to existing models should reload the
referenced models too.
"""
new_apps = Apps()
class A(models.Model):
class Meta:
app_label = 'something'
apps = new_apps
class B(A):
class Meta:
app_label = 'something'
apps = new_apps
class C(models.Model):
class Meta:
app_label = 'something'
apps = new_apps
project_state = ProjectState()
project_state.add_model(ModelState.from_model(A))
project_state.add_model(ModelState.from_model(B))
project_state.add_model(ModelState.from_model(C))
project_state.apps # We need to work with rendered models
old_state = project_state.clone()
model_a_old = old_state.apps.get_model('something', 'A')
model_b_old = old_state.apps.get_model('something', 'B')
model_c_old = old_state.apps.get_model('something', 'C')
# Check that the relations between the old models are correct
self.assertIs(model_a_old._meta.get_field('b').related_model, model_b_old)
self.assertIs(model_b_old._meta.get_field('a_ptr').related_model, model_a_old)
operation = AddField('c', 'to_a', models.OneToOneField(
'something.A',
models.CASCADE,
related_name='from_c',
))
operation.state_forwards('something', project_state)
model_a_new = project_state.apps.get_model('something', 'A')
model_b_new = project_state.apps.get_model('something', 'B')
model_c_new = project_state.apps.get_model('something', 'C')
# Check that all models have changed
self.assertIsNot(model_a_old, model_a_new)
self.assertIsNot(model_b_old, model_b_new)
self.assertIsNot(model_c_old, model_c_new)
# Check that the relations between the old models still hold
self.assertIs(model_a_old._meta.get_field('b').related_model, model_b_old)
self.assertIs(model_b_old._meta.get_field('a_ptr').related_model, model_a_old)
# Check that the relations between the new models correct
self.assertIs(model_a_new._meta.get_field('b').related_model, model_b_new)
self.assertIs(model_b_new._meta.get_field('a_ptr').related_model, model_a_new)
self.assertIs(model_a_new._meta.get_field('from_c').related_model, model_c_new)
self.assertIs(model_c_new._meta.get_field('to_a').related_model, model_a_new)
def test_remove_relations(self):
"""
#24225 - Tests that relations between models are updated while
remaining the relations and references for models of an old state.
"""
new_apps = Apps()
class A(models.Model):
class Meta:
app_label = "something"
apps = new_apps
class B(models.Model):
to_a = models.ForeignKey(A, models.CASCADE)
class Meta:
app_label = "something"
apps = new_apps
def get_model_a(state):
return [mod for mod in state.apps.get_models() if mod._meta.model_name == 'a'][0]
project_state = ProjectState()
project_state.add_model(ModelState.from_model(A))
project_state.add_model(ModelState.from_model(B))
self.assertEqual(len(get_model_a(project_state)._meta.related_objects), 1)
old_state = project_state.clone()
operation = RemoveField("b", "to_a")
operation.state_forwards("something", project_state)
# Tests that model from old_state still has the relation
model_a_old = get_model_a(old_state)
model_a_new = get_model_a(project_state)
self.assertIsNot(model_a_old, model_a_new)
self.assertEqual(len(model_a_old._meta.related_objects), 1)
self.assertEqual(len(model_a_new._meta.related_objects), 0)
# Same test for deleted model
project_state = ProjectState()
project_state.add_model(ModelState.from_model(A))
project_state.add_model(ModelState.from_model(B))
old_state = project_state.clone()
operation = DeleteModel("b")
operation.state_forwards("something", project_state)
model_a_old = get_model_a(old_state)
model_a_new = get_model_a(project_state)
self.assertIsNot(model_a_old, model_a_new)
self.assertEqual(len(model_a_old._meta.related_objects), 1)
self.assertEqual(len(model_a_new._meta.related_objects), 0)
def test_self_relation(self):
"""
#24513 - Modifying an object pointing to itself would cause it to be
rendered twice and thus breaking its related M2M through objects.
"""
class A(models.Model):
to_a = models.ManyToManyField('something.A', symmetrical=False)
class Meta:
app_label = "something"
def get_model_a(state):
return [mod for mod in state.apps.get_models() if mod._meta.model_name == 'a'][0]
project_state = ProjectState()
project_state.add_model((ModelState.from_model(A)))
self.assertEqual(len(get_model_a(project_state)._meta.related_objects), 1)
old_state = project_state.clone()
operation = AlterField(
model_name="a",
name="to_a",
field=models.ManyToManyField("something.A", symmetrical=False, blank=True)
)
# At this point the model would be rendered twice causing its related
# M2M through objects to point to an old copy and thus breaking their
# attribute lookup.
operation.state_forwards("something", project_state)
model_a_old = get_model_a(old_state)
model_a_new = get_model_a(project_state)
self.assertIsNot(model_a_old, model_a_new)
# Tests that the old model's _meta is still consistent
field_to_a_old = model_a_old._meta.get_field("to_a")
self.assertEqual(field_to_a_old.m2m_field_name(), "from_a")
self.assertEqual(field_to_a_old.m2m_reverse_field_name(), "to_a")
self.assertIs(field_to_a_old.related_model, model_a_old)
self.assertIs(field_to_a_old.remote_field.through._meta.get_field('to_a').related_model, model_a_old)
self.assertIs(field_to_a_old.remote_field.through._meta.get_field('from_a').related_model, model_a_old)
# Tests that the new model's _meta is still consistent
field_to_a_new = model_a_new._meta.get_field("to_a")
self.assertEqual(field_to_a_new.m2m_field_name(), "from_a")
self.assertEqual(field_to_a_new.m2m_reverse_field_name(), "to_a")
self.assertIs(field_to_a_new.related_model, model_a_new)
self.assertIs(field_to_a_new.remote_field.through._meta.get_field('to_a').related_model, model_a_new)
self.assertIs(field_to_a_new.remote_field.through._meta.get_field('from_a').related_model, model_a_new)
def test_equality(self):
"""
Tests that == and != are implemented correctly.
"""
# Test two things that should be equal
project_state = ProjectState()
project_state.add_model(ModelState(
"migrations",
"Tag",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=100)),
("hidden", models.BooleanField()),
],
{},
None,
))
project_state.apps # Fill the apps cached property
other_state = project_state.clone()
self.assertEqual(project_state, project_state)
self.assertEqual(project_state, other_state)
self.assertEqual(project_state != project_state, False)
self.assertEqual(project_state != other_state, False)
self.assertNotEqual(project_state.apps, other_state.apps)
# Make a very small change (max_len 99) and see if that affects it
project_state = ProjectState()
project_state.add_model(ModelState(
"migrations",
"Tag",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=99)),
("hidden", models.BooleanField()),
],
{},
None,
))
self.assertNotEqual(project_state, other_state)
self.assertEqual(project_state == other_state, False)
def test_dangling_references_throw_error(self):
new_apps = Apps()
class Author(models.Model):
name = models.TextField()
class Meta:
app_label = "migrations"
apps = new_apps
class Book(models.Model):
author = models.ForeignKey(Author, models.CASCADE)
class Meta:
app_label = "migrations"
apps = new_apps
class Magazine(models.Model):
authors = models.ManyToManyField(Author)
class Meta:
app_label = "migrations"
apps = new_apps
# Make a valid ProjectState and render it
project_state = ProjectState()
project_state.add_model(ModelState.from_model(Author))
project_state.add_model(ModelState.from_model(Book))
project_state.add_model(ModelState.from_model(Magazine))
self.assertEqual(len(project_state.apps.get_models()), 3)
# now make an invalid one with a ForeignKey
project_state = ProjectState()
project_state.add_model(ModelState.from_model(Book))
with self.assertRaises(ValueError):
project_state.apps
# and another with ManyToManyField
project_state = ProjectState()
project_state.add_model(ModelState.from_model(Magazine))
with self.assertRaises(ValueError):
project_state.apps
def test_real_apps(self):
"""
Tests that including real apps can resolve dangling FK errors.
This test relies on the fact that contenttypes is always loaded.
"""
new_apps = Apps()
class TestModel(models.Model):
ct = models.ForeignKey("contenttypes.ContentType", models.CASCADE)
class Meta:
app_label = "migrations"
apps = new_apps
# If we just stick it into an empty state it should fail
project_state = ProjectState()
project_state.add_model(ModelState.from_model(TestModel))
with self.assertRaises(ValueError):
project_state.apps
# If we include the real app it should succeed
project_state = ProjectState(real_apps=["contenttypes"])
project_state.add_model(ModelState.from_model(TestModel))
rendered_state = project_state.apps
self.assertEqual(
len([x for x in rendered_state.get_models() if x._meta.app_label == "migrations"]),
1,
)
def test_ignore_order_wrt(self):
"""
Makes sure ProjectState doesn't include OrderWrt fields when
making from existing models.
"""
new_apps = Apps()
class Author(models.Model):
name = models.TextField()
class Meta:
app_label = "migrations"
apps = new_apps
class Book(models.Model):
author = models.ForeignKey(Author, models.CASCADE)
class Meta:
app_label = "migrations"
apps = new_apps
order_with_respect_to = "author"
# Make a valid ProjectState and render it
project_state = ProjectState()
project_state.add_model(ModelState.from_model(Author))
project_state.add_model(ModelState.from_model(Book))
self.assertEqual(
[name for name, field in project_state.models["migrations", "book"].fields],
["id", "author"],
)
def test_manager_refer_correct_model_version(self):
"""
#24147 - Tests that managers refer to the correct version of a
historical model
"""
project_state = ProjectState()
project_state.add_model(ModelState(
app_label="migrations",
name="Tag",
fields=[
("id", models.AutoField(primary_key=True)),
("hidden", models.BooleanField()),
],
managers=[
('food_mgr', FoodManager('a', 'b')),
('food_qs', FoodQuerySet.as_manager()),
]
))
old_model = project_state.apps.get_model('migrations', 'tag')
new_state = project_state.clone()
operation = RemoveField("tag", "hidden")
operation.state_forwards("migrations", new_state)
new_model = new_state.apps.get_model('migrations', 'tag')
self.assertIsNot(old_model, new_model)
self.assertIs(old_model, old_model.food_mgr.model)
self.assertIs(old_model, old_model.food_qs.model)
self.assertIs(new_model, new_model.food_mgr.model)
self.assertIs(new_model, new_model.food_qs.model)
self.assertIsNot(old_model.food_mgr, new_model.food_mgr)
self.assertIsNot(old_model.food_qs, new_model.food_qs)
self.assertIsNot(old_model.food_mgr.model, new_model.food_mgr.model)
self.assertIsNot(old_model.food_qs.model, new_model.food_qs.model)
def test_choices_iterator(self):
"""
#24483 - ProjectState.from_apps should not destructively consume
Field.choices iterators.
"""
new_apps = Apps(["migrations"])
choices = [('a', 'A'), ('b', 'B')]
class Author(models.Model):
name = models.CharField(max_length=255)
choice = models.CharField(max_length=255, choices=iter(choices))
class Meta:
app_label = "migrations"
apps = new_apps
ProjectState.from_apps(new_apps)
choices_field = Author._meta.get_field('choice')
self.assertEqual(list(choices_field.choices), choices)
class ModelStateTests(SimpleTestCase):
def test_custom_model_base(self):
state = ModelState.from_model(ModelWithCustomBase)
self.assertEqual(state.bases, (models.Model,))
def test_bound_field_sanity_check(self):
field = models.CharField(max_length=1)
field.model = models.Model
with self.assertRaisesMessage(ValueError,
'ModelState.fields cannot be bound to a model - "field" is.'):
ModelState('app', 'Model', [('field', field)])
def test_sanity_check_to(self):
field = models.ForeignKey(UnicodeModel, models.CASCADE)
with self.assertRaisesMessage(ValueError,
'ModelState.fields cannot refer to a model class - "field.to" does. '
'Use a string reference instead.'):
ModelState('app', 'Model', [('field', field)])
def test_sanity_check_through(self):
field = models.ManyToManyField('UnicodeModel')
field.remote_field.through = UnicodeModel
with self.assertRaisesMessage(ValueError,
'ModelState.fields cannot refer to a model class - "field.through" does. '
'Use a string reference instead.'):
ModelState('app', 'Model', [('field', field)])
def test_fields_immutability(self):
"""
Tests that rendering a model state doesn't alter its internal fields.
"""
apps = Apps()
field = models.CharField(max_length=1)
state = ModelState('app', 'Model', [('name', field)])
Model = state.render(apps)
self.assertNotEqual(Model._meta.get_field('name'), field)
def test_repr(self):
field = models.CharField(max_length=1)
state = ModelState('app', 'Model', [('name', field)], bases=['app.A', 'app.B', 'app.C'])
self.assertEqual(repr(state), "<ModelState: 'app.Model'>")
project_state = ProjectState()
project_state.add_model(state)
with self.assertRaisesMessage(InvalidBasesError, "Cannot resolve bases for [<ModelState: 'app.Model'>]"):
project_state.apps
@override_settings(TEST_SWAPPABLE_MODEL='migrations.SomeFakeModel')
def test_create_swappable(self):
"""
Tests making a ProjectState from an Apps with a swappable model
"""
new_apps = Apps(['migrations'])
class Author(models.Model):
name = models.CharField(max_length=255)
bio = models.TextField()
age = models.IntegerField(blank=True, null=True)
class Meta:
app_label = 'migrations'
apps = new_apps
swappable = 'TEST_SWAPPABLE_MODEL'
author_state = ModelState.from_model(Author)
self.assertEqual(author_state.app_label, 'migrations')
self.assertEqual(author_state.name, 'Author')
self.assertEqual([x for x, y in author_state.fields], ['id', 'name', 'bio', 'age'])
self.assertEqual(author_state.fields[1][1].max_length, 255)
self.assertEqual(author_state.fields[2][1].null, False)
self.assertEqual(author_state.fields[3][1].null, True)
self.assertEqual(author_state.options, {'swappable': 'TEST_SWAPPABLE_MODEL'})
self.assertEqual(author_state.bases, (models.Model, ))
self.assertEqual(author_state.managers, [])
@override_settings(TEST_SWAPPABLE_MODEL='migrations.SomeFakeModel')
def test_custom_manager_swappable(self):
"""
Tests making a ProjectState from unused models with custom managers
"""
new_apps = Apps(['migrations'])
class Food(models.Model):
food_mgr = FoodManager('a', 'b')
food_qs = FoodQuerySet.as_manager()
food_no_mgr = NoMigrationFoodManager('x', 'y')
class Meta:
app_label = "migrations"
apps = new_apps
swappable = 'TEST_SWAPPABLE_MODEL'
food_state = ModelState.from_model(Food)
# The default manager is used in migrations
self.assertEqual([name for name, mgr in food_state.managers], ['food_mgr'])
self.assertEqual(food_state.managers[0][1].args, ('a', 'b', 1, 2))
class RelatedModelsTests(SimpleTestCase):
def setUp(self):
self.apps = Apps(['migrations.related_models_app'])
def create_model(self, name, foreign_keys=[], bases=(), abstract=False, proxy=False):
test_name = 'related_models_app'
assert not (abstract and proxy)
meta_contents = {
'abstract': abstract,
'app_label': test_name,
'apps': self.apps,
'proxy': proxy,
}
meta = type(str("Meta"), tuple(), meta_contents)
if not bases:
bases = (models.Model,)
body = {
'Meta': meta,
'__module__': "__fake__",
}
fname_base = fname = '%s_%%d' % name.lower()
for i, fk in enumerate(foreign_keys, 1):
fname = fname_base % i
body[fname] = fk
return type(name, bases, body)
def assertRelated(self, model, needle):
self.assertEqual(
get_related_models_recursive(model),
{(n._meta.app_label, n._meta.model_name) for n in needle},
)
def test_unrelated(self):
A = self.create_model("A")
B = self.create_model("B")
self.assertRelated(A, [])
self.assertRelated(B, [])
def test_direct_fk(self):
A = self.create_model("A", foreign_keys=[models.ForeignKey('B', models.CASCADE)])
B = self.create_model("B")
self.assertRelated(A, [B])
self.assertRelated(B, [A])
def test_direct_hidden_fk(self):
A = self.create_model("A", foreign_keys=[models.ForeignKey('B', models.CASCADE, related_name='+')])
B = self.create_model("B")
self.assertRelated(A, [B])
self.assertRelated(B, [A])
def test_nested_fk(self):
A = self.create_model("A", foreign_keys=[models.ForeignKey('B', models.CASCADE)])
B = self.create_model("B", foreign_keys=[models.ForeignKey('C', models.CASCADE)])
C = self.create_model("C")
self.assertRelated(A, [B, C])
self.assertRelated(B, [A, C])
self.assertRelated(C, [A, B])
def test_two_sided(self):
A = self.create_model("A", foreign_keys=[models.ForeignKey('B', models.CASCADE)])
B = self.create_model("B", foreign_keys=[models.ForeignKey('A', models.CASCADE)])
self.assertRelated(A, [B])
self.assertRelated(B, [A])
def test_circle(self):
A = self.create_model("A", foreign_keys=[models.ForeignKey('B', models.CASCADE)])
B = self.create_model("B", foreign_keys=[models.ForeignKey('C', models.CASCADE)])
C = self.create_model("C", foreign_keys=[models.ForeignKey('A', models.CASCADE)])
self.assertRelated(A, [B, C])
self.assertRelated(B, [A, C])
self.assertRelated(C, [A, B])
def test_base(self):
A = self.create_model("A")
B = self.create_model("B", bases=(A,))
self.assertRelated(A, [B])
self.assertRelated(B, [A])
def test_nested_base(self):
A = self.create_model("A")
B = self.create_model("B", bases=(A,))
C = self.create_model("C", bases=(B,))
self.assertRelated(A, [B, C])
self.assertRelated(B, [A, C])
self.assertRelated(C, [A, B])
def test_multiple_bases(self):
A = self.create_model("A")
B = self.create_model("B")
C = self.create_model("C", bases=(A, B,))
self.assertRelated(A, [B, C])
self.assertRelated(B, [A, C])
self.assertRelated(C, [A, B])
def test_multiple_nested_bases(self):
A = self.create_model("A")
B = self.create_model("B")
C = self.create_model("C", bases=(A, B,))
D = self.create_model("D")
E = self.create_model("E", bases=(D,))
F = self.create_model("F", bases=(C, E,))
Y = self.create_model("Y")
Z = self.create_model("Z", bases=(Y,))
self.assertRelated(A, [B, C, D, E, F])
self.assertRelated(B, [A, C, D, E, F])
self.assertRelated(C, [A, B, D, E, F])
self.assertRelated(D, [A, B, C, E, F])
self.assertRelated(E, [A, B, C, D, F])
self.assertRelated(F, [A, B, C, D, E])
self.assertRelated(Y, [Z])
self.assertRelated(Z, [Y])
def test_base_to_base_fk(self):
A = self.create_model("A", foreign_keys=[models.ForeignKey('Y', models.CASCADE)])
B = self.create_model("B", bases=(A,))
Y = self.create_model("Y")
Z = self.create_model("Z", bases=(Y,))
self.assertRelated(A, [B, Y, Z])
self.assertRelated(B, [A, Y, Z])
self.assertRelated(Y, [A, B, Z])
self.assertRelated(Z, [A, B, Y])
def test_base_to_subclass_fk(self):
A = self.create_model("A", foreign_keys=[models.ForeignKey('Z', models.CASCADE)])
B = self.create_model("B", bases=(A,))
Y = self.create_model("Y")
Z = self.create_model("Z", bases=(Y,))
self.assertRelated(A, [B, Y, Z])
self.assertRelated(B, [A, Y, Z])
self.assertRelated(Y, [A, B, Z])
self.assertRelated(Z, [A, B, Y])
def test_direct_m2m(self):
A = self.create_model("A", foreign_keys=[models.ManyToManyField('B')])
B = self.create_model("B")
self.assertRelated(A, [A.a_1.rel.through, B])
self.assertRelated(B, [A, A.a_1.rel.through])
def test_direct_m2m_self(self):
A = self.create_model("A", foreign_keys=[models.ManyToManyField('A')])
self.assertRelated(A, [A.a_1.rel.through])
def test_intermediate_m2m_self(self):
A = self.create_model("A", foreign_keys=[models.ManyToManyField('A', through='T')])
T = self.create_model("T", foreign_keys=[
models.ForeignKey('A', models.CASCADE),
models.ForeignKey('A', models.CASCADE),
])
self.assertRelated(A, [T])
self.assertRelated(T, [A])
def test_intermediate_m2m(self):
A = self.create_model("A", foreign_keys=[models.ManyToManyField('B', through='T')])
B = self.create_model("B")
T = self.create_model("T", foreign_keys=[
models.ForeignKey('A', models.CASCADE),
models.ForeignKey('B', models.CASCADE),
])
self.assertRelated(A, [B, T])
self.assertRelated(B, [A, T])
self.assertRelated(T, [A, B])
def test_intermediate_m2m_extern_fk(self):
A = self.create_model("A", foreign_keys=[models.ManyToManyField('B', through='T')])
B = self.create_model("B")
Z = self.create_model("Z")
T = self.create_model("T", foreign_keys=[
models.ForeignKey('A', models.CASCADE),
models.ForeignKey('B', models.CASCADE),
models.ForeignKey('Z', models.CASCADE),
])
self.assertRelated(A, [B, T, Z])
self.assertRelated(B, [A, T, Z])
self.assertRelated(T, [A, B, Z])
self.assertRelated(Z, [A, B, T])
def test_intermediate_m2m_base(self):
A = self.create_model("A", foreign_keys=[models.ManyToManyField('B', through='T')])
B = self.create_model("B")
S = self.create_model("S")
T = self.create_model("T", foreign_keys=[
models.ForeignKey('A', models.CASCADE),
models.ForeignKey('B', models.CASCADE),
], bases=(S,))
self.assertRelated(A, [B, S, T])
self.assertRelated(B, [A, S, T])
self.assertRelated(S, [A, B, T])
self.assertRelated(T, [A, B, S])
def test_generic_fk(self):
A = self.create_model("A", foreign_keys=[
models.ForeignKey('B', models.CASCADE),
GenericForeignKey(),
])
B = self.create_model("B", foreign_keys=[
models.ForeignKey('C', models.CASCADE),
])
self.assertRelated(A, [B])
self.assertRelated(B, [A])
def test_abstract_base(self):
A = self.create_model("A", abstract=True)
B = self.create_model("B", bases=(A,))
self.assertRelated(A, [B])
self.assertRelated(B, [])
def test_nested_abstract_base(self):
A = self.create_model("A", abstract=True)
B = self.create_model("B", bases=(A,), abstract=True)
C = self.create_model("C", bases=(B,))
self.assertRelated(A, [B, C])
self.assertRelated(B, [C])
self.assertRelated(C, [])
def test_proxy_base(self):
A = self.create_model("A")
B = self.create_model("B", bases=(A,), proxy=True)
self.assertRelated(A, [B])
self.assertRelated(B, [])
def test_nested_proxy_base(self):
A = self.create_model("A")
B = self.create_model("B", bases=(A,), proxy=True)
C = self.create_model("C", bases=(B,), proxy=True)
self.assertRelated(A, [B, C])
self.assertRelated(B, [C])
self.assertRelated(C, [])
def test_multiple_mixed_bases(self):
A = self.create_model("A", abstract=True)
M = self.create_model("M")
P = self.create_model("P")
Q = self.create_model("Q", bases=(P,), proxy=True)
Z = self.create_model("Z", bases=(A, M, Q))
# M has a pointer O2O field p_ptr to P
self.assertRelated(A, [M, P, Q, Z])
self.assertRelated(M, [P, Q, Z])
self.assertRelated(P, [M, Q, Z])
self.assertRelated(Q, [M, P, Z])
self.assertRelated(Z, [M, P, Q])
| bsd-3-clause |
TribeMedia/sky_engine | mojo/python/tests/generation_unittest.py | 10 | 1148 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import mojo_unittest
from mojo_bindings import reflection
from mojo_bindings import interface_reflection
class GenerationTest(mojo_unittest.MojoTestCase):
TEST_PACKAGES = [
'math_calculator_mojom',
'no_module_mojom',
'rect_mojom',
'regression_tests_mojom',
'sample_factory_mojom',
'sample_import2_mojom',
'sample_import_mojom',
'sample_interfaces_mojom',
'sample_service_mojom',
'serialization_test_structs_mojom',
'test_structs_mojom',
'validation_test_interfaces_mojom',
]
@staticmethod
def testGeneration():
buildable_types = (reflection.MojoStructType,
interface_reflection.MojoInterfaceType)
for module_name in GenerationTest.TEST_PACKAGES:
module = __import__(module_name)
for element_name in dir(module):
element = getattr(module, element_name)
if isinstance(element, buildable_types):
# Check struct and interface are buildable
element()
| bsd-3-clause |
NunoEdgarGub1/kubernetes | third_party/htpasswd/htpasswd.py | 897 | 5219 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2013 Edgewall Software
# Copyright (C) 2008 Eli Carter
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/.
"""Replacement for htpasswd"""
import os
import sys
import random
from optparse import OptionParser
# We need a crypt module, but Windows doesn't have one by default. Try to find
# one, and tell the user if we can't.
try:
import crypt
except ImportError:
try:
import fcrypt as crypt
except ImportError:
sys.stderr.write("Cannot find a crypt module. "
"Possibly http://carey.geek.nz/code/python-fcrypt/\n")
sys.exit(1)
def wait_for_file_mtime_change(filename):
"""This function is typically called before a file save operation,
waiting if necessary for the file modification time to change. The
purpose is to avoid successive file updates going undetected by the
caching mechanism that depends on a change in the file modification
time to know when the file should be reparsed."""
try:
mtime = os.stat(filename).st_mtime
os.utime(filename, None)
while mtime == os.stat(filename).st_mtime:
time.sleep(1e-3)
os.utime(filename, None)
except OSError:
pass # file doesn't exist (yet)
def salt():
"""Returns a string of 2 randome letters"""
letters = 'abcdefghijklmnopqrstuvwxyz' \
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
'0123456789/.'
return random.choice(letters) + random.choice(letters)
class HtpasswdFile:
"""A class for manipulating htpasswd files."""
def __init__(self, filename, create=False):
self.entries = []
self.filename = filename
if not create:
if os.path.exists(self.filename):
self.load()
else:
raise Exception("%s does not exist" % self.filename)
def load(self):
"""Read the htpasswd file into memory."""
lines = open(self.filename, 'r').readlines()
self.entries = []
for line in lines:
username, pwhash = line.split(':')
entry = [username, pwhash.rstrip()]
self.entries.append(entry)
def save(self):
"""Write the htpasswd file to disk"""
wait_for_file_mtime_change(self.filename)
open(self.filename, 'w').writelines(["%s:%s\n" % (entry[0], entry[1])
for entry in self.entries])
def update(self, username, password):
"""Replace the entry for the given user, or add it if new."""
pwhash = crypt.crypt(password, salt())
matching_entries = [entry for entry in self.entries
if entry[0] == username]
if matching_entries:
matching_entries[0][1] = pwhash
else:
self.entries.append([username, pwhash])
def delete(self, username):
"""Remove the entry for the given user."""
self.entries = [entry for entry in self.entries
if entry[0] != username]
def main():
"""
%prog -b[c] filename username password
%prog -D filename username"""
# For now, we only care about the use cases that affect tests/functional.py
parser = OptionParser(usage=main.__doc__)
parser.add_option('-b', action='store_true', dest='batch', default=False,
help='Batch mode; password is passed on the command line IN THE CLEAR.'
)
parser.add_option('-c', action='store_true', dest='create', default=False,
help='Create a new htpasswd file, overwriting any existing file.')
parser.add_option('-D', action='store_true', dest='delete_user',
default=False, help='Remove the given user from the password file.')
options, args = parser.parse_args()
def syntax_error(msg):
"""Utility function for displaying fatal error messages with usage
help.
"""
sys.stderr.write("Syntax error: " + msg)
sys.stderr.write(parser.get_usage())
sys.exit(1)
if not (options.batch or options.delete_user):
syntax_error("Only batch and delete modes are supported\n")
# Non-option arguments
if len(args) < 2:
syntax_error("Insufficient number of arguments.\n")
filename, username = args[:2]
if options.delete_user:
if len(args) != 2:
syntax_error("Incorrect number of arguments.\n")
password = None
else:
if len(args) != 3:
syntax_error("Incorrect number of arguments.\n")
password = args[2]
passwdfile = HtpasswdFile(filename, create=options.create)
if options.delete_user:
passwdfile.delete(username)
else:
passwdfile.update(username, password)
passwdfile.save()
if __name__ == '__main__':
main()
| apache-2.0 |
endlessm/chromium-browser | third_party/pexpect/FSM.py | 171 | 14248 | #!/usr/bin/env python
"""This module implements a Finite State Machine (FSM). In addition to state
this FSM also maintains a user defined "memory". So this FSM can be used as a
Push-down Automata (PDA) since a PDA is a FSM + memory.
The following describes how the FSM works, but you will probably also need to
see the example function to understand how the FSM is used in practice.
You define an FSM by building tables of transitions. For a given input symbol
the process() method uses these tables to decide what action to call and what
the next state will be. The FSM has a table of transitions that associate:
(input_symbol, current_state) --> (action, next_state)
Where "action" is a function you define. The symbols and states can be any
objects. You use the add_transition() and add_transition_list() methods to add
to the transition table. The FSM also has a table of transitions that
associate:
(current_state) --> (action, next_state)
You use the add_transition_any() method to add to this transition table. The
FSM also has one default transition that is not associated with any specific
input_symbol or state. You use the set_default_transition() method to set the
default transition.
When an action function is called it is passed a reference to the FSM. The
action function may then access attributes of the FSM such as input_symbol,
current_state, or "memory". The "memory" attribute can be any object that you
want to pass along to the action functions. It is not used by the FSM itself.
For parsing you would typically pass a list to be used as a stack.
The processing sequence is as follows. The process() method is given an
input_symbol to process. The FSM will search the table of transitions that
associate:
(input_symbol, current_state) --> (action, next_state)
If the pair (input_symbol, current_state) is found then process() will call the
associated action function and then set the current state to the next_state.
If the FSM cannot find a match for (input_symbol, current_state) it will then
search the table of transitions that associate:
(current_state) --> (action, next_state)
If the current_state is found then the process() method will call the
associated action function and then set the current state to the next_state.
Notice that this table lacks an input_symbol. It lets you define transitions
for a current_state and ANY input_symbol. Hence, it is called the "any" table.
Remember, it is always checked after first searching the table for a specific
(input_symbol, current_state).
For the case where the FSM did not match either of the previous two cases the
FSM will try to use the default transition. If the default transition is
defined then the process() method will call the associated action function and
then set the current state to the next_state. This lets you define a default
transition as a catch-all case. You can think of it as an exception handler.
There can be only one default transition.
Finally, if none of the previous cases are defined for an input_symbol and
current_state then the FSM will raise an exception. This may be desirable, but
you can always prevent this just by defining a default transition.
Noah Spurrier 20020822
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
PERMISSION TO USE, COPY, MODIFY, AND/OR 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.
"""
class ExceptionFSM(Exception):
"""This is the FSM Exception class."""
def __init__(self, value):
self.value = value
def __str__(self):
return `self.value`
class FSM:
"""This is a Finite State Machine (FSM).
"""
def __init__(self, initial_state, memory=None):
"""This creates the FSM. You set the initial state here. The "memory"
attribute is any object that you want to pass along to the action
functions. It is not used by the FSM. For parsing you would typically
pass a list to be used as a stack. """
# Map (input_symbol, current_state) --> (action, next_state).
self.state_transitions = {}
# Map (current_state) --> (action, next_state).
self.state_transitions_any = {}
self.default_transition = None
self.input_symbol = None
self.initial_state = initial_state
self.current_state = self.initial_state
self.next_state = None
self.action = None
self.memory = memory
def reset (self):
"""This sets the current_state to the initial_state and sets
input_symbol to None. The initial state was set by the constructor
__init__(). """
self.current_state = self.initial_state
self.input_symbol = None
def add_transition (self, input_symbol, state, action=None, next_state=None):
"""This adds a transition that associates:
(input_symbol, current_state) --> (action, next_state)
The action may be set to None in which case the process() method will
ignore the action and only set the next_state. The next_state may be
set to None in which case the current state will be unchanged.
You can also set transitions for a list of symbols by using
add_transition_list(). """
if next_state is None:
next_state = state
self.state_transitions[(input_symbol, state)] = (action, next_state)
def add_transition_list (self, list_input_symbols, state, action=None, next_state=None):
"""This adds the same transition for a list of input symbols.
You can pass a list or a string. Note that it is handy to use
string.digits, string.whitespace, string.letters, etc. to add
transitions that match character classes.
The action may be set to None in which case the process() method will
ignore the action and only set the next_state. The next_state may be
set to None in which case the current state will be unchanged. """
if next_state is None:
next_state = state
for input_symbol in list_input_symbols:
self.add_transition (input_symbol, state, action, next_state)
def add_transition_any (self, state, action=None, next_state=None):
"""This adds a transition that associates:
(current_state) --> (action, next_state)
That is, any input symbol will match the current state.
The process() method checks the "any" state associations after it first
checks for an exact match of (input_symbol, current_state).
The action may be set to None in which case the process() method will
ignore the action and only set the next_state. The next_state may be
set to None in which case the current state will be unchanged. """
if next_state is None:
next_state = state
self.state_transitions_any [state] = (action, next_state)
def set_default_transition (self, action, next_state):
"""This sets the default transition. This defines an action and
next_state if the FSM cannot find the input symbol and the current
state in the transition list and if the FSM cannot find the
current_state in the transition_any list. This is useful as a final
fall-through state for catching errors and undefined states.
The default transition can be removed by setting the attribute
default_transition to None. """
self.default_transition = (action, next_state)
def get_transition (self, input_symbol, state):
"""This returns (action, next state) given an input_symbol and state.
This does not modify the FSM state, so calling this method has no side
effects. Normally you do not call this method directly. It is called by
process().
The sequence of steps to check for a defined transition goes from the
most specific to the least specific.
1. Check state_transitions[] that match exactly the tuple,
(input_symbol, state)
2. Check state_transitions_any[] that match (state)
In other words, match a specific state and ANY input_symbol.
3. Check if the default_transition is defined.
This catches any input_symbol and any state.
This is a handler for errors, undefined states, or defaults.
4. No transition was defined. If we get here then raise an exception.
"""
if self.state_transitions.has_key((input_symbol, state)):
return self.state_transitions[(input_symbol, state)]
elif self.state_transitions_any.has_key (state):
return self.state_transitions_any[state]
elif self.default_transition is not None:
return self.default_transition
else:
raise ExceptionFSM ('Transition is undefined: (%s, %s).' %
(str(input_symbol), str(state)) )
def process (self, input_symbol):
"""This is the main method that you call to process input. This may
cause the FSM to change state and call an action. This method calls
get_transition() to find the action and next_state associated with the
input_symbol and current_state. If the action is None then the action
is not called and only the current state is changed. This method
processes one complete input symbol. You can process a list of symbols
(or a string) by calling process_list(). """
self.input_symbol = input_symbol
(self.action, self.next_state) = self.get_transition (self.input_symbol, self.current_state)
if self.action is not None:
self.action (self)
self.current_state = self.next_state
self.next_state = None
def process_list (self, input_symbols):
"""This takes a list and sends each element to process(). The list may
be a string or any iterable object. """
for s in input_symbols:
self.process (s)
##############################################################################
# The following is an example that demonstrates the use of the FSM class to
# process an RPN expression. Run this module from the command line. You will
# get a prompt > for input. Enter an RPN Expression. Numbers may be integers.
# Operators are * / + - Use the = sign to evaluate and print the expression.
# For example:
#
# 167 3 2 2 * * * 1 - =
#
# will print:
#
# 2003
##############################################################################
import sys, os, traceback, optparse, time, string
#
# These define the actions.
# Note that "memory" is a list being used as a stack.
#
def BeginBuildNumber (fsm):
fsm.memory.append (fsm.input_symbol)
def BuildNumber (fsm):
s = fsm.memory.pop ()
s = s + fsm.input_symbol
fsm.memory.append (s)
def EndBuildNumber (fsm):
s = fsm.memory.pop ()
fsm.memory.append (int(s))
def DoOperator (fsm):
ar = fsm.memory.pop()
al = fsm.memory.pop()
if fsm.input_symbol == '+':
fsm.memory.append (al + ar)
elif fsm.input_symbol == '-':
fsm.memory.append (al - ar)
elif fsm.input_symbol == '*':
fsm.memory.append (al * ar)
elif fsm.input_symbol == '/':
fsm.memory.append (al / ar)
def DoEqual (fsm):
print str(fsm.memory.pop())
def Error (fsm):
print 'That does not compute.'
print str(fsm.input_symbol)
def main():
"""This is where the example starts and the FSM state transitions are
defined. Note that states are strings (such as 'INIT'). This is not
necessary, but it makes the example easier to read. """
f = FSM ('INIT', []) # "memory" will be used as a stack.
f.set_default_transition (Error, 'INIT')
f.add_transition_any ('INIT', None, 'INIT')
f.add_transition ('=', 'INIT', DoEqual, 'INIT')
f.add_transition_list (string.digits, 'INIT', BeginBuildNumber, 'BUILDING_NUMBER')
f.add_transition_list (string.digits, 'BUILDING_NUMBER', BuildNumber, 'BUILDING_NUMBER')
f.add_transition_list (string.whitespace, 'BUILDING_NUMBER', EndBuildNumber, 'INIT')
f.add_transition_list ('+-*/', 'INIT', DoOperator, 'INIT')
print
print 'Enter an RPN Expression.'
print 'Numbers may be integers. Operators are * / + -'
print 'Use the = sign to evaluate and print the expression.'
print 'For example: '
print ' 167 3 2 2 * * * 1 - ='
inputstr = raw_input ('> ')
f.process_list(inputstr)
if __name__ == '__main__':
try:
start_time = time.time()
parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id: FSM.py 533 2012-10-20 02:19:33Z noah $')
parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output')
(options, args) = parser.parse_args()
if options.verbose: print time.asctime()
main()
if options.verbose: print time.asctime()
if options.verbose: print 'TOTAL TIME IN MINUTES:',
if options.verbose: print (time.time() - start_time) / 60.0
sys.exit(0)
except KeyboardInterrupt, e: # Ctrl-C
raise e
except SystemExit, e: # sys.exit()
raise e
except Exception, e:
print 'ERROR, UNEXPECTED EXCEPTION'
print str(e)
traceback.print_exc()
os._exit(1)
| bsd-3-clause |
hkariti/mopidy | tests/local/test_library.py | 12 | 23197 | from __future__ import absolute_import, unicode_literals
import os
import shutil
import tempfile
import unittest
import mock
import pykka
from mopidy import core, exceptions
from mopidy.local import actor, json
from mopidy.models import Album, Artist, Image, Track
from tests import path_to_data_dir
# TODO: update tests to only use backend, not core. we need a seperate
# core test that does this integration test.
class LocalLibraryProviderTest(unittest.TestCase):
artists = [
Artist(name='artist1'),
Artist(name='artist2'),
Artist(name='artist3'),
Artist(name='artist4'),
Artist(name='artist5'),
Artist(name='artist6'),
Artist(),
]
albums = [
Album(name='album1', artists=[artists[0]]),
Album(name='album2', artists=[artists[1]]),
Album(name='album3', artists=[artists[2]]),
Album(name='album4'),
Album(artists=[artists[-1]]),
]
tracks = [
Track(
uri='local:track:path1', name='track1',
artists=[artists[0]], album=albums[0],
date='2001-02-03', length=4000, track_no=1),
Track(
uri='local:track:path2', name='track2',
artists=[artists[1]], album=albums[1],
date='2002', length=4000, track_no=2),
Track(
uri='local:track:path3', name='track3',
artists=[artists[3]], album=albums[2],
date='2003', length=4000, track_no=3),
Track(
uri='local:track:path4', name='track4',
artists=[artists[2]], album=albums[3],
date='2004', length=60000, track_no=4,
comment='This is a fantastic track'),
Track(
uri='local:track:path5', name='track5', genre='genre1',
album=albums[3], length=4000, composers=[artists[4]]),
Track(
uri='local:track:path6', name='track6', genre='genre2',
album=albums[3], length=4000, performers=[artists[5]]),
Track(uri='local:track:nameless', album=albums[-1]),
]
config = {
'core': {
'data_dir': path_to_data_dir(''),
},
'local': {
'media_dir': path_to_data_dir(''),
'library': 'json',
},
}
def setUp(self): # noqa: N802
actor.LocalBackend.libraries = [json.JsonLibrary]
self.backend = actor.LocalBackend.start(
config=self.config, audio=None).proxy()
self.core = core.Core(backends=[self.backend])
self.library = self.core.library
def tearDown(self): # noqa: N802
pykka.ActorRegistry.stop_all()
actor.LocalBackend.libraries = []
def find_exact(self, **query):
# TODO: remove this helper?
return self.library.search(query=query, exact=True)
def search(self, **query):
# TODO: remove this helper?
return self.library.search(query=query)
def test_refresh(self):
self.library.refresh()
@unittest.SkipTest
def test_refresh_uri(self):
pass
def test_refresh_missing_uri(self):
# Verifies that https://github.com/mopidy/mopidy/issues/500
# has been fixed.
tmpdir = tempfile.mkdtemp()
try:
tmpdir_local = os.path.join(tmpdir, 'local')
shutil.copytree(path_to_data_dir('local'), tmpdir_local)
config = {
'core': {
'data_dir': tmpdir,
},
'local': self.config['local'],
}
backend = actor.LocalBackend(config=config, audio=None)
# Sanity check that value is in the library
result = backend.library.lookup(self.tracks[0].uri)
self.assertEqual(result, self.tracks[0:1])
# Clear and refresh.
tmplib = os.path.join(tmpdir_local, 'library.json.gz')
open(tmplib, 'w').close()
backend.library.refresh()
# Now it should be gone.
result = backend.library.lookup(self.tracks[0].uri)
self.assertEqual(result, [])
finally:
shutil.rmtree(tmpdir)
@unittest.SkipTest
def test_browse(self):
pass # TODO
def test_lookup(self):
uri = self.tracks[0].uri
result = self.library.lookup(uris=[uri])
self.assertEqual(result[uri], self.tracks[0:1])
def test_lookup_unknown_track(self):
tracks = self.library.lookup(uris=['fake:/uri'])
self.assertEqual(tracks, {'fake:/uri': []})
# test backward compatibility with local libraries returning a
# single Track
@mock.patch.object(json.JsonLibrary, 'lookup')
def test_lookup_return_single_track(self, mock_lookup):
backend = actor.LocalBackend(config=self.config, audio=None)
mock_lookup.return_value = self.tracks[0]
tracks = backend.library.lookup(self.tracks[0].uri)
mock_lookup.assert_called_with(self.tracks[0].uri)
self.assertEqual(tracks, self.tracks[0:1])
mock_lookup.return_value = None
tracks = backend.library.lookup('fake uri')
mock_lookup.assert_called_with('fake uri')
self.assertEqual(tracks, [])
# TODO: move to search_test module
def test_find_exact_no_hits(self):
result = self.find_exact(track_name=['unknown track'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(artist=['unknown artist'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(albumartist=['unknown albumartist'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(composer=['unknown composer'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(performer=['unknown performer'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(album=['unknown album'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(date=['1990'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(genre=['unknown genre'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(track_no=['9'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(track_no=['no_match'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(comment=['fake comment'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(uri=['fake uri'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(any=['unknown any'])
self.assertEqual(list(result[0].tracks), [])
def test_find_exact_uri(self):
track_1_uri = 'local:track:path1'
result = self.find_exact(uri=track_1_uri)
self.assertEqual(list(result[0].tracks), self.tracks[:1])
track_2_uri = 'local:track:path2'
result = self.find_exact(uri=track_2_uri)
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_find_exact_track_name(self):
result = self.find_exact(track_name=['track1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.find_exact(track_name=['track2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_find_exact_artist(self):
result = self.find_exact(artist=['artist1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.find_exact(artist=['artist2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
result = self.find_exact(artist=['artist3'])
self.assertEqual(list(result[0].tracks), self.tracks[3:4])
def test_find_exact_composer(self):
result = self.find_exact(composer=['artist5'])
self.assertEqual(list(result[0].tracks), self.tracks[4:5])
result = self.find_exact(composer=['artist6'])
self.assertEqual(list(result[0].tracks), [])
def test_find_exact_performer(self):
result = self.find_exact(performer=['artist6'])
self.assertEqual(list(result[0].tracks), self.tracks[5:6])
result = self.find_exact(performer=['artist5'])
self.assertEqual(list(result[0].tracks), [])
def test_find_exact_album(self):
result = self.find_exact(album=['album1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.find_exact(album=['album2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_find_exact_albumartist(self):
# Artist is both track artist and album artist
result = self.find_exact(albumartist=['artist1'])
self.assertEqual(list(result[0].tracks), [self.tracks[0]])
# Artist is both track and album artist
result = self.find_exact(albumartist=['artist2'])
self.assertEqual(list(result[0].tracks), [self.tracks[1]])
# Artist is just album artist
result = self.find_exact(albumartist=['artist3'])
self.assertEqual(list(result[0].tracks), [self.tracks[2]])
def test_find_exact_track_no(self):
result = self.find_exact(track_no=['1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.find_exact(track_no=['2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_find_exact_genre(self):
result = self.find_exact(genre=['genre1'])
self.assertEqual(list(result[0].tracks), self.tracks[4:5])
result = self.find_exact(genre=['genre2'])
self.assertEqual(list(result[0].tracks), self.tracks[5:6])
def test_find_exact_date(self):
result = self.find_exact(date=['2001'])
self.assertEqual(list(result[0].tracks), [])
result = self.find_exact(date=['2001-02-03'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.find_exact(date=['2002'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_find_exact_comment(self):
result = self.find_exact(
comment=['This is a fantastic track'])
self.assertEqual(list(result[0].tracks), self.tracks[3:4])
result = self.find_exact(
comment=['This is a fantastic'])
self.assertEqual(list(result[0].tracks), [])
def test_find_exact_any(self):
# Matches on track artist
result = self.find_exact(any=['artist1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.find_exact(any=['artist2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
# Matches on track name
result = self.find_exact(any=['track1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.find_exact(any=['track2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
# Matches on track album
result = self.find_exact(any=['album1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
# Matches on track album artists
result = self.find_exact(any=['artist3'])
self.assertEqual(len(result[0].tracks), 2)
self.assertIn(self.tracks[2], result[0].tracks)
self.assertIn(self.tracks[3], result[0].tracks)
# Matches on track composer
result = self.find_exact(any=['artist5'])
self.assertEqual(list(result[0].tracks), self.tracks[4:5])
# Matches on track performer
result = self.find_exact(any=['artist6'])
self.assertEqual(list(result[0].tracks), self.tracks[5:6])
# Matches on track genre
result = self.find_exact(any=['genre1'])
self.assertEqual(list(result[0].tracks), self.tracks[4:5])
result = self.find_exact(any=['genre2'])
self.assertEqual(list(result[0].tracks), self.tracks[5:6])
# Matches on track date
result = self.find_exact(any=['2002'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
# Matches on track comment
result = self.find_exact(
any=['This is a fantastic track'])
self.assertEqual(list(result[0].tracks), self.tracks[3:4])
# Matches on URI
result = self.find_exact(any=['local:track:path1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
# TODO: This is really just a test of the query validation code now,
# as this code path never even makes it to the local backend.
def test_find_exact_wrong_type(self):
with self.assertRaises(exceptions.ValidationError):
self.find_exact(wrong=['test'])
def test_find_exact_with_empty_query(self):
with self.assertRaises(exceptions.ValidationError):
self.find_exact(artist=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(albumartist=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(track_name=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(composer=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(performer=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(album=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(track_no=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(genre=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(date=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(comment=[''])
with self.assertRaises(exceptions.ValidationError):
self.find_exact(any=[''])
def test_search_no_hits(self):
result = self.search(track_name=['unknown track'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(artist=['unknown artist'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(albumartist=['unknown albumartist'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(composer=['unknown composer'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(performer=['unknown performer'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(album=['unknown album'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(track_no=['9'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(track_no=['no_match'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(genre=['unknown genre'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(date=['unknown date'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(comment=['unknown comment'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(uri=['unknown uri'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(any=['unknown anything'])
self.assertEqual(list(result[0].tracks), [])
def test_search_uri(self):
result = self.search(uri=['TH1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.search(uri=['TH2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_search_track_name(self):
result = self.search(track_name=['Rack1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.search(track_name=['Rack2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_search_artist(self):
result = self.search(artist=['Tist1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.search(artist=['Tist2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_search_albumartist(self):
# Artist is both track artist and album artist
result = self.search(albumartist=['Tist1'])
self.assertEqual(list(result[0].tracks), [self.tracks[0]])
# Artist is both track artist and album artist
result = self.search(albumartist=['Tist2'])
self.assertEqual(list(result[0].tracks), [self.tracks[1]])
# Artist is just album artist
result = self.search(albumartist=['Tist3'])
self.assertEqual(list(result[0].tracks), [self.tracks[2]])
def test_search_composer(self):
result = self.search(composer=['Tist5'])
self.assertEqual(list(result[0].tracks), self.tracks[4:5])
def test_search_performer(self):
result = self.search(performer=['Tist6'])
self.assertEqual(list(result[0].tracks), self.tracks[5:6])
def test_search_album(self):
result = self.search(album=['Bum1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.search(album=['Bum2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_search_genre(self):
result = self.search(genre=['Enre1'])
self.assertEqual(list(result[0].tracks), self.tracks[4:5])
result = self.search(genre=['Enre2'])
self.assertEqual(list(result[0].tracks), self.tracks[5:6])
def test_search_date(self):
result = self.search(date=['2001'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.search(date=['2001-02-03'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.search(date=['2001-02-04'])
self.assertEqual(list(result[0].tracks), [])
result = self.search(date=['2002'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_search_track_no(self):
result = self.search(track_no=['1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.search(track_no=['2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
def test_search_comment(self):
result = self.search(comment=['fantastic'])
self.assertEqual(list(result[0].tracks), self.tracks[3:4])
result = self.search(comment=['antasti'])
self.assertEqual(list(result[0].tracks), self.tracks[3:4])
def test_search_any(self):
# Matches on track artist
result = self.search(any=['Tist1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
# Matches on track composer
result = self.search(any=['Tist5'])
self.assertEqual(list(result[0].tracks), self.tracks[4:5])
# Matches on track performer
result = self.search(any=['Tist6'])
self.assertEqual(list(result[0].tracks), self.tracks[5:6])
# Matches on track
result = self.search(any=['Rack1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
result = self.search(any=['Rack2'])
self.assertEqual(list(result[0].tracks), self.tracks[1:2])
# Matches on track album
result = self.search(any=['Bum1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
# Matches on track album artists
result = self.search(any=['Tist3'])
self.assertEqual(len(result[0].tracks), 2)
self.assertIn(self.tracks[2], result[0].tracks)
self.assertIn(self.tracks[3], result[0].tracks)
# Matches on track genre
result = self.search(any=['Enre1'])
self.assertEqual(list(result[0].tracks), self.tracks[4:5])
result = self.search(any=['Enre2'])
self.assertEqual(list(result[0].tracks), self.tracks[5:6])
# Matches on track comment
result = self.search(any=['fanta'])
self.assertEqual(list(result[0].tracks), self.tracks[3:4])
result = self.search(any=['is a fan'])
self.assertEqual(list(result[0].tracks), self.tracks[3:4])
# Matches on URI
result = self.search(any=['TH1'])
self.assertEqual(list(result[0].tracks), self.tracks[:1])
def test_search_wrong_type(self):
with self.assertRaises(exceptions.ValidationError):
self.search(wrong=['test'])
def test_search_with_empty_query(self):
with self.assertRaises(exceptions.ValidationError):
self.search(artist=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(albumartist=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(composer=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(performer=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(track_name=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(album=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(genre=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(date=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(comment=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(uri=[''])
with self.assertRaises(exceptions.ValidationError):
self.search(any=[''])
def test_default_get_images_impl_no_images(self):
result = self.library.get_images([track.uri for track in self.tracks])
self.assertEqual(result, {track.uri: tuple() for track in self.tracks})
@mock.patch.object(json.JsonLibrary, 'lookup')
def test_default_get_images_impl_album_images(self, mock_lookup):
library = actor.LocalBackend(config=self.config, audio=None).library
image = Image(uri='imageuri')
album = Album(images=[image.uri])
track = Track(uri='trackuri', album=album)
mock_lookup.return_value = [track]
result = library.get_images([track.uri])
self.assertEqual(result, {track.uri: [image]})
@mock.patch.object(json.JsonLibrary, 'lookup')
def test_default_get_images_impl_single_track(self, mock_lookup):
library = actor.LocalBackend(config=self.config, audio=None).library
image = Image(uri='imageuri')
album = Album(images=[image.uri])
track = Track(uri='trackuri', album=album)
mock_lookup.return_value = track
result = library.get_images([track.uri])
self.assertEqual(result, {track.uri: [image]})
@mock.patch.object(json.JsonLibrary, 'get_images')
def test_local_library_get_images(self, mock_get_images):
library = actor.LocalBackend(config=self.config, audio=None).library
image = Image(uri='imageuri')
track = Track(uri='trackuri')
mock_get_images.return_value = {track.uri: [image]}
result = library.get_images([track.uri])
self.assertEqual(result, {track.uri: [image]})
| apache-2.0 |
chromium/chromium | build/android/gyp/native_libraries_template.py | 7 | 1781 | # Copyright 2019 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.
NATIVE_LIBRARIES_TEMPLATE = """\
// This file is autogenerated by
// build/android/gyp/write_native_libraries_java.py
// Please do not change its content.
package org.chromium.build;
public class NativeLibraries {{
public static final int CPU_FAMILY_UNKNOWN = 0;
public static final int CPU_FAMILY_ARM = 1;
public static final int CPU_FAMILY_MIPS = 2;
public static final int CPU_FAMILY_X86 = 3;
// Set to true to enable the use of the Chromium Linker.
public static {MAYBE_FINAL}boolean sUseLinker{USE_LINKER};
public static {MAYBE_FINAL}boolean sUseLibraryInZipFile{USE_LIBRARY_IN_ZIP_FILE};
public static {MAYBE_FINAL}boolean sUseModernLinker{USE_MODERN_LINKER};
// This is the list of native libraries to be loaded (in the correct order)
// by LibraryLoader.java.
// TODO(cjhopman): This is public since it is referenced by NativeTestActivity.java
// directly. The two ways of library loading should be refactored into one.
public static {MAYBE_FINAL}String[] LIBRARIES = {{{LIBRARIES}}};
// This is the expected version of the 'main' native library, which is the one that
// implements the initial set of base JNI functions including
// base::android::nativeGetVersionName()
// TODO(torne): This is public to work around classloader issues in Trichrome
// where NativeLibraries is not in the same dex as LibraryLoader.
// We should instead split up Java code along package boundaries.
public static {MAYBE_FINAL}String sVersionNumber = {VERSION_NUMBER};
public static {MAYBE_FINAL}int sCpuFamily = {CPU_FAMILY};
}}
"""
| bsd-3-clause |
shobhitmishra/CodingProblems | LeetCode/Session3/BinaryTreePaths.py | 1 | 1149 | from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
result = []
if not root:
return result
self.binaryTreePathsHelper(root, [], result)
return result
def binaryTreePathsHelper(self, root, pathSoFar, result):
if root:
pathSoFar.append(str(root.val))
if not root.left and not root.right:
path = "->".join(pathSoFar)
result.append(path)
self.binaryTreePathsHelper(root.left, pathSoFar, result)
self.binaryTreePathsHelper(root.right, pathSoFar, result)
pathSoFar.pop()
root = TreeNode(10)
root.left = TreeNode(3)
root.left.left = TreeNode(2)
root.left.right = TreeNode(8)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(9)
root.right = TreeNode(15)
root.right.left = TreeNode(13)
root.right.right = TreeNode(17)
root.right.right.right = TreeNode(19)
ob = Solution()
print(ob.binaryTreePaths(root))
| mit |
cntnboys/410Lab6 | build/django/django/contrib/admin/helpers.py | 53 | 14115 | from __future__ import unicode_literals
from django import forms
from django.contrib.admin.utils import (flatten_fieldsets, lookup_field,
display_for_field, label_for_field, help_text_for_field)
from django.contrib.admin.templatetags.admin_static import static
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields.related import ManyToManyRel
from django.forms.utils import flatatt
from django.template.defaultfilters import capfirst, linebreaksbr
from django.utils.encoding import force_text, smart_text
from django.utils.html import conditional_escape, format_html
from django.utils.safestring import mark_safe
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
ACTION_CHECKBOX_NAME = '_selected_action'
class ActionForm(forms.Form):
action = forms.ChoiceField(label=_('Action:'))
select_across = forms.BooleanField(label='', required=False, initial=0,
widget=forms.HiddenInput({'class': 'select-across'}))
checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False)
class AdminForm(object):
def __init__(self, form, fieldsets, prepopulated_fields, readonly_fields=None, model_admin=None):
self.form, self.fieldsets = form, fieldsets
self.prepopulated_fields = [{
'field': form[field_name],
'dependencies': [form[f] for f in dependencies]
} for field_name, dependencies in prepopulated_fields.items()]
self.model_admin = model_admin
if readonly_fields is None:
readonly_fields = ()
self.readonly_fields = readonly_fields
def __iter__(self):
for name, options in self.fieldsets:
yield Fieldset(
self.form, name,
readonly_fields=self.readonly_fields,
model_admin=self.model_admin,
**options
)
def _media(self):
media = self.form.media
for fs in self:
media = media + fs.media
return media
media = property(_media)
class Fieldset(object):
def __init__(self, form, name=None, readonly_fields=(), fields=(), classes=(),
description=None, model_admin=None):
self.form = form
self.name, self.fields = name, fields
self.classes = ' '.join(classes)
self.description = description
self.model_admin = model_admin
self.readonly_fields = readonly_fields
def _media(self):
if 'collapse' in self.classes:
extra = '' if settings.DEBUG else '.min'
js = ['jquery%s.js' % extra,
'jquery.init.js',
'collapse%s.js' % extra]
return forms.Media(js=[static('admin/js/%s' % url) for url in js])
return forms.Media()
media = property(_media)
def __iter__(self):
for field in self.fields:
yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin)
class Fieldline(object):
def __init__(self, form, field, readonly_fields=None, model_admin=None):
self.form = form # A django.forms.Form instance
if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
self.fields = [field]
else:
self.fields = field
self.has_visible_field = not all(field in self.form.fields and
self.form.fields[field].widget.is_hidden
for field in self.fields)
self.model_admin = model_admin
if readonly_fields is None:
readonly_fields = ()
self.readonly_fields = readonly_fields
def __iter__(self):
for i, field in enumerate(self.fields):
if field in self.readonly_fields:
yield AdminReadonlyField(self.form, field, is_first=(i == 0),
model_admin=self.model_admin)
else:
yield AdminField(self.form, field, is_first=(i == 0))
def errors(self):
return mark_safe('\n'.join(self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields).strip('\n'))
class AdminField(object):
def __init__(self, form, field, is_first):
self.field = form[field] # A django.forms.BoundField instance
self.is_first = is_first # Whether this field is first on the line
self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput)
def label_tag(self):
classes = []
contents = conditional_escape(force_text(self.field.label))
if self.is_checkbox:
classes.append('vCheckboxLabel')
if self.field.field.required:
classes.append('required')
if not self.is_first:
classes.append('inline')
attrs = {'class': ' '.join(classes)} if classes else {}
# checkboxes should not have a label suffix as the checkbox appears
# to the left of the label.
return self.field.label_tag(contents=mark_safe(contents), attrs=attrs,
label_suffix='' if self.is_checkbox else None)
def errors(self):
return mark_safe(self.field.errors.as_ul())
class AdminReadonlyField(object):
def __init__(self, form, field, is_first, model_admin=None):
# Make self.field look a little bit like a field. This means that
# {{ field.name }} must be a useful class name to identify the field.
# For convenience, store other field-related data here too.
if callable(field):
class_name = field.__name__ if field.__name__ != '<lambda>' else ''
else:
class_name = field
if form._meta.labels and class_name in form._meta.labels:
label = form._meta.labels[class_name]
else:
label = label_for_field(field, form._meta.model, model_admin)
if form._meta.help_texts and class_name in form._meta.help_texts:
help_text = form._meta.help_texts[class_name]
else:
help_text = help_text_for_field(class_name, form._meta.model)
self.field = {
'name': class_name,
'label': label,
'help_text': help_text,
'field': field,
}
self.form = form
self.model_admin = model_admin
self.is_first = is_first
self.is_checkbox = False
self.is_readonly = True
def label_tag(self):
attrs = {}
if not self.is_first:
attrs["class"] = "inline"
label = self.field['label']
return format_html('<label{0}>{1}:</label>',
flatatt(attrs),
capfirst(force_text(label)))
def contents(self):
from django.contrib.admin.templatetags.admin_list import _boolean_icon
from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
try:
f, attr, value = lookup_field(field, obj, model_admin)
except (AttributeError, ValueError, ObjectDoesNotExist):
result_repr = EMPTY_CHANGELIST_VALUE
else:
if f is None:
boolean = getattr(attr, "boolean", False)
if boolean:
result_repr = _boolean_icon(value)
else:
result_repr = smart_text(value)
if getattr(attr, "allow_tags", False):
result_repr = mark_safe(result_repr)
else:
result_repr = linebreaksbr(result_repr)
else:
if isinstance(f.rel, ManyToManyRel) and value is not None:
result_repr = ", ".join(map(six.text_type, value.all()))
else:
result_repr = display_for_field(value, f)
return conditional_escape(result_repr)
class InlineAdminFormSet(object):
"""
A wrapper around an inline formset for use in the admin system.
"""
def __init__(self, inline, formset, fieldsets, prepopulated_fields=None,
readonly_fields=None, model_admin=None):
self.opts = inline
self.formset = formset
self.fieldsets = fieldsets
self.model_admin = model_admin
if readonly_fields is None:
readonly_fields = ()
self.readonly_fields = readonly_fields
if prepopulated_fields is None:
prepopulated_fields = {}
self.prepopulated_fields = prepopulated_fields
def __iter__(self):
for form, original in zip(self.formset.initial_forms, self.formset.get_queryset()):
view_on_site_url = self.opts.get_view_on_site_url(original)
yield InlineAdminForm(self.formset, form, self.fieldsets,
self.prepopulated_fields, original, self.readonly_fields,
model_admin=self.opts, view_on_site_url=view_on_site_url)
for form in self.formset.extra_forms:
yield InlineAdminForm(self.formset, form, self.fieldsets,
self.prepopulated_fields, None, self.readonly_fields,
model_admin=self.opts)
yield InlineAdminForm(self.formset, self.formset.empty_form,
self.fieldsets, self.prepopulated_fields, None,
self.readonly_fields, model_admin=self.opts)
def fields(self):
fk = getattr(self.formset, "fk", None)
for i, field_name in enumerate(flatten_fieldsets(self.fieldsets)):
if fk and fk.name == field_name:
continue
if field_name in self.readonly_fields:
yield {
'label': label_for_field(field_name, self.opts.model, self.opts),
'widget': {
'is_hidden': False
},
'required': False,
'help_text': help_text_for_field(field_name, self.opts.model),
}
else:
yield self.formset.form.base_fields[field_name]
def _media(self):
media = self.opts.media + self.formset.media
for fs in self:
media = media + fs.media
return media
media = property(_media)
class InlineAdminForm(AdminForm):
"""
A wrapper around an inline form for use in the admin system.
"""
def __init__(self, formset, form, fieldsets, prepopulated_fields, original,
readonly_fields=None, model_admin=None, view_on_site_url=None):
self.formset = formset
self.model_admin = model_admin
self.original = original
if original is not None:
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level.
from django.contrib.contenttypes.models import ContentType
self.original_content_type_id = ContentType.objects.get_for_model(original).pk
self.show_url = original and view_on_site_url is not None
self.absolute_url = view_on_site_url
super(InlineAdminForm, self).__init__(form, fieldsets, prepopulated_fields,
readonly_fields, model_admin)
def __iter__(self):
for name, options in self.fieldsets:
yield InlineFieldset(self.formset, self.form, name,
self.readonly_fields, model_admin=self.model_admin, **options)
def needs_explicit_pk_field(self):
# Auto fields are editable (oddly), so need to check for auto or non-editable pk
if self.form._meta.model._meta.has_auto_field or not self.form._meta.model._meta.pk.editable:
return True
# Also search any parents for an auto field. (The pk info is propagated to child
# models so that does not need to be checked in parents.)
for parent in self.form._meta.model._meta.get_parent_list():
if parent._meta.has_auto_field:
return True
return False
def field_count(self):
# tabular.html uses this function for colspan value.
num_of_fields = 0
if self.has_auto_field():
num_of_fields += 1
num_of_fields += len(self.fieldsets[0][1]["fields"])
if self.formset.can_order:
num_of_fields += 1
if self.formset.can_delete:
num_of_fields += 1
return num_of_fields
def pk_field(self):
return AdminField(self.form, self.formset._pk_field.name, False)
def fk_field(self):
fk = getattr(self.formset, "fk", None)
if fk:
return AdminField(self.form, fk.name, False)
else:
return ""
def deletion_field(self):
from django.forms.formsets import DELETION_FIELD_NAME
return AdminField(self.form, DELETION_FIELD_NAME, False)
def ordering_field(self):
from django.forms.formsets import ORDERING_FIELD_NAME
return AdminField(self.form, ORDERING_FIELD_NAME, False)
class InlineFieldset(Fieldset):
def __init__(self, formset, *args, **kwargs):
self.formset = formset
super(InlineFieldset, self).__init__(*args, **kwargs)
def __iter__(self):
fk = getattr(self.formset, "fk", None)
for field in self.fields:
if fk and fk.name == field:
continue
yield Fieldline(self.form, field, self.readonly_fields,
model_admin=self.model_admin)
class AdminErrorList(forms.utils.ErrorList):
"""
Stores all errors for the form/formsets in an add/change stage view.
"""
def __init__(self, form, inline_formsets):
super(AdminErrorList, self).__init__()
if form.is_bound:
self.extend(list(six.itervalues(form.errors)))
for inline_formset in inline_formsets:
self.extend(inline_formset.non_form_errors())
for errors_in_inline_form in inline_formset.errors:
self.extend(list(six.itervalues(errors_in_inline_form)))
| apache-2.0 |
Kobzol/kaira | ptp/gencpp/simrun.py | 12 | 3084 | #
# Copyright (C) 2013 Stanislav Bohm
#
# This file is part of Kaira.
#
# Kaira is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License, or
# (at your option) any later version.
#
# Kaira 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 Kaira. If not, see <http://www.gnu.org/licenses/>.
#
import buildnet
import build
def write_run_configuration(builder):
# Here we do not use block_begin because we want to supress indentation
# User function has to start at the first column to obtain
# correct positions of error messages
builder.line("class RunConfiguration : public casr::RunConfiguration {{")
builder.line("public:")
declaration = \
"ca::IntTime packet_time(casr::Context &ctx, int origin_id, int target_id, size_t size)"
builder.write_function(declaration,
builder.project.communication_model_code,
("*communication-model", 1))
builder.line("}};")
def write_clock(builder, tr):
class_name = "Clock_{0.id}".format(tr)
builder.write_class_head(class_name, "ca::Clock")
builder.write_constructor(class_name,
"ca::ThreadBase *thread",
[ "ctx(thread)" ])
builder.write_method_end()
builder.line("ca::IntTime tock();")
builder.line("protected:")
builder.line("casr::Context ctx;")
builder.write_class_end()
def write_clock_tock(builder, tr):
builder.write_function(
"ca::IntTime Clock_{0.id}::tock()".format(tr),
"ca::IntTime clockTime = Clock::tock();\n"
"return {0};".format(tr.clock_substitution),
("*{0.id}/clock-substitution".format(tr), 1))
def write_clocks_tock(builder):
for net in builder.project.nets:
for tr in net.transitions:
if tr.clock_substitution:
write_clock_tock(builder, tr)
def write_clocks(builder):
for net in builder.project.nets:
for tr in net.transitions:
if tr.clock_substitution:
write_clock(builder, tr)
def write_main(builder):
builder.line("int main(int argc, char **argv)")
builder.block_begin()
buildnet.write_main_setup(builder, start_process=False)
builder.line("RunConfiguration run_configuration;")
builder.line("casr::main(run_configuration);");
builder.line("return 0;")
builder.block_end()
def write_simrun_program(builder):
build.write_header(builder)
write_clocks(builder)
buildnet.write_core(builder)
write_run_configuration(builder)
write_main(builder)
buildnet.write_user_functions(builder)
write_clocks_tock(builder)
| gpl-3.0 |
renaelectronics/linuxcnc | lib/python/gladevcp/hal_meter.py | 39 | 9330 | # vim: sts=4 sw=4 et
# GladeVcp Widgets
#
# Copyright (c) 2010 Pavel Shramov <shramov@mexmat.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
import gtk
import gobject
import cairo
import math
import gtk.glade
from hal_widgets import _HalWidgetBase, hal, hal_pin_changed_signal
MAX_INT = 0x7fffffff
def gdk_color_tuple(c):
if not c:
return 0, 0, 0
return c.red_float, c.green_float, c.blue_float
class HAL_Meter(gtk.DrawingArea, _HalWidgetBase):
__gtype_name__ = 'HAL_Meter'
__gsignals__ = dict([hal_pin_changed_signal])
__gproperties__ = {
'invert' : ( gobject.TYPE_BOOLEAN, 'Inverted', 'Invert min-max direction',
False, gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT),
'min' : ( gobject.TYPE_FLOAT, 'Min', 'Minimum value',
-MAX_INT, MAX_INT, 0, gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT),
'max' : ( gobject.TYPE_FLOAT, 'Max', 'Maximum value',
-MAX_INT, MAX_INT, 100, gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT),
'value' : ( gobject.TYPE_FLOAT, 'Value', 'Current meter value (for glade testing)',
-MAX_INT, MAX_INT, 0, gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT),
'majorscale' : ( gobject.TYPE_FLOAT, 'Major scale', 'Major ticks',
-MAX_INT, MAX_INT, 10, gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT),
'minorscale' : ( gobject.TYPE_FLOAT, 'Minor scale', 'Minor ticks',
-MAX_INT, MAX_INT, 2, gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT),
'z0_color' : ( gtk.gdk.Color.__gtype__, 'Zone 0 color', "Set color for first zone",
gobject.PARAM_READWRITE),
'z1_color' : ( gtk.gdk.Color.__gtype__, 'Zone 1 color', "Set color for second zone",
gobject.PARAM_READWRITE),
'z2_color' : ( gtk.gdk.Color.__gtype__, 'Zone 2 color', "Set color for third zone",
gobject.PARAM_READWRITE),
'z0_border' : ( gobject.TYPE_FLOAT, 'Zone 0 up limit', 'Up limit of zone 0',
-MAX_INT, MAX_INT, MAX_INT, gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT),
'z1_border' : ( gobject.TYPE_FLOAT, 'Zone 1 up limit', 'Up limit of zone 1',
-MAX_INT, MAX_INT, MAX_INT, gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT),
'bg_color' : ( gtk.gdk.Color.__gtype__, 'Background', "Choose background color",
gobject.PARAM_READWRITE),
'force_size' : ( gobject.TYPE_INT, 'Forced size', 'Force meter size not dependent on widget size. -1 to disable',
-1, MAX_INT, -1, gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT),
'text_template' : ( gobject.TYPE_STRING, 'Text template',
'Text template to display. Python formatting may be used for one variable',
"%s", gobject.PARAM_READWRITE|gobject.PARAM_CONSTRUCT),
'label' : ( gobject.TYPE_STRING, 'Meter label', 'Label to display',
"", gobject.PARAM_READWRITE|gobject.PARAM_CONSTRUCT),
'sublabel' : ( gobject.TYPE_STRING, 'Meter sub label', 'Sub text to display',
"", gobject.PARAM_READWRITE|gobject.PARAM_CONSTRUCT),
}
__gproperties = __gproperties__
def __init__(self):
super(HAL_Meter, self).__init__()
self.bg_color = gtk.gdk.Color('white')
self.z0_color = gtk.gdk.Color('green')
self.z1_color = gtk.gdk.Color('yellow')
self.z2_color = gtk.gdk.Color('red')
self.force_radius = None
self.connect("expose-event", self.expose)
def _hal_init(self):
_HalWidgetBase._hal_init(self)
self.hal_pin = self.hal.newpin(self.hal_name, hal.HAL_FLOAT, hal.HAL_IN)
self.hal_pin.connect('value-changed', lambda p: self.set_value(p.value))
self.hal_pin.connect('value-changed', lambda s: self.emit('hal-pin-changed', s))
def expose(self, widget, event):
if self.flags() & gtk.PARENT_SENSITIVE:
alpha = 1
else:
alpha = 0.3
w = self.allocation.width
h = self.allocation.height
r = min(w, h) / 2
fr = self.force_size
if fr > 0: r = min(fr, r)
if r < 20:
r = 40
self.set_size_request(2 * r, 2 * r)
cr = widget.window.cairo_create()
def set_color(c):
return cr.set_source_rgba(c.red_float, c.green_float, c.blue_float, alpha)
cr.set_line_width(2)
set_color(gtk.gdk.Color('black'))
#print w, h, aw, ah, fw, fh
cr.translate(w / 2, h / 2)
cr.arc(0, 0, r, 0, 2*math.pi)
cr.clip_preserve()
cr.stroke()
r -= 1
cr.set_line_width(1)
set_color(self.bg_color)
cr.arc(0, 0, r, 0, 2*math.pi)
cr.stroke_preserve()
cr.fill()
a_delta = math.pi / 6
a_start = 0.5 * math.pi + a_delta
a_size = 2 * math.pi - 2 * a_delta
def angle(v):
size = self.max - self.min
v = max(self.min, v)
v = min(self.max, v)
return a_start + a_size * (v - self.min) / size
set_color(self.z2_color)
self.draw_zone(cr, r, angle(self.z1_border), angle(self.max))
set_color(self.z1_color)
self.draw_zone(cr, r, angle(self.z0_border), angle(self.z1_border))
set_color(self.z0_color)
self.draw_zone(cr, r, angle(self.min), angle(self.z0_border))
set_color(gtk.gdk.Color('black'))
cr.set_font_size(r/10)
v = self.min
while v <= self.max:
if int(v) - v == 0: v = int(v)
self.draw_tick(cr, r, 0.15 * r, angle(v), text=str(v))
v += self.majorscale
v = self.min
while v <= self.max:
self.draw_tick(cr, r, 0.05 * r, angle(v))
v += self.minorscale
self.text_at(cr, self.sublabel, 0, r/5)
cr.set_font_size(r/5)
self.text_at(cr, self.label, 0, -r/5)
set_color(gtk.gdk.Color('red'))
self.draw_arrow(cr, r, angle(self.value))
set_color(gtk.gdk.Color('black'))
self.text_at(cr, self.text_template % self.value, 0, 0.8 * r)
return True
def draw_zone(self, cr, r, start, stop):
cr.arc(0, 0, r, start, stop)
cr.line_to(0.9 * r * math.cos(stop), 0.9 * r * math.sin(stop))
cr.arc_negative(0, 0, 0.9 * r, stop, start)
cr.line_to(r * math.cos(start), r * math.sin(start))
cr.stroke_preserve()
cr.fill()
def draw_tick(self, cr, r, sz, a, text=None):
cr.move_to((r - sz) * math.cos(a), (r - sz) * math.sin(a))
cr.line_to(r * math.cos(a), r * math.sin(a))
cr.stroke()
if not text:
return
self.text_at(cr, text, 0.75 * r * math.cos(a), 0.75 * r * math.sin(a))
def text_at(self, cr, text, x, y, xalign='center', yalign='center'):
xbearing, ybearing, width, height, xadvance, yadvance = cr.text_extents(text)
#print xbearing, ybearing, width, height, xadvance, yadvance
if xalign == 'center':
x = x - width/2
elif xalign == 'right':
x = x - width
if yalign == 'center':
y = y + height/2
elif yalign == 'top':
y = y + height
cr.move_to(x, y)
cr.show_text(text)
def draw_arrow(self, cr, r, a):
cr.rotate(a)
cr.move_to(0, 0)
cr.line_to(-r/10, r/20)
cr.line_to(0.8 * r, 0)
cr.line_to(-r/10, -r/20)
cr.line_to(0, 0)
cr.stroke_preserve()
cr.fill()
cr.rotate(-a)
def set_value(self, v):
self.value = v
self.queue_draw()
def do_get_property(self, property):
name = property.name.replace('-', '_')
if name in self.__gproperties.keys():
return getattr(self, name)
else:
raise AttributeError('unknown property %s' % property.name)
def do_set_property(self, property, value):
name = property.name.replace('-', '_')
if name == 'text_template':
try:
v = value % 0.0
except Exception, e:
print "Invalid format string '%s': %s" % (value, e)
return False
if name in ['bg_color', 'z0_color', 'z1_color', 'z2_color']:
if not value:
return False
if name in self.__gproperties.keys():
setattr(self, name, value)
self.queue_draw()
else:
raise AttributeError('unknown property %s' % property.name)
if name in ['force_size', 'force_size']:
#print "Forcing size request %s" % name
self.set_size_request(self.force_size, self.force_size)
self.queue_draw()
return True
| gpl-2.0 |
ksmit799/Toontown-Source | toontown/building/DistributedKnockKnockDoor.py | 1 | 6420 | from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.distributed.ClockDelta import *
from KnockKnockJokes import *
from toontown.toonbase import ToontownGlobals
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM
import DistributedAnimatedProp
from toontown.distributed import DelayDelete
from toontown.toonbase import TTLocalizer
from toontown.hood import ZoneUtil
class DistributedKnockKnockDoor(DistributedAnimatedProp.DistributedAnimatedProp):
def __init__(self, cr):
DistributedAnimatedProp.DistributedAnimatedProp.__init__(self, cr)
self.fsm.setName('DistributedKnockKnockDoor')
self.rimshot = None
self.knockSfx = None
return
def generate(self):
DistributedAnimatedProp.DistributedAnimatedProp.generate(self)
self.avatarTracks = []
self.avatarId = 0
def announceGenerate(self):
DistributedAnimatedProp.DistributedAnimatedProp.announceGenerate(self)
self.accept('exitKnockKnockDoorSphere_' + str(self.propId), self.exitTrigger)
self.acceptAvatar()
def disable(self):
self.ignore('exitKnockKnockDoorSphere_' + str(self.propId))
self.ignore('enterKnockKnockDoorSphere_' + str(self.propId))
DistributedAnimatedProp.DistributedAnimatedProp.disable(self)
def delete(self):
DistributedAnimatedProp.DistributedAnimatedProp.delete(self)
if self.rimshot:
self.rimshot = None
if self.knockSfx:
self.knockSfx = None
return
def acceptAvatar(self):
self.acceptOnce('enterKnockKnockDoorSphere_' + str(self.propId), self.enterTrigger)
def setAvatarInteract(self, avatarId):
DistributedAnimatedProp.DistributedAnimatedProp.setAvatarInteract(self, avatarId)
def avatarExit(self, avatarId):
if avatarId == self.avatarId:
for track in self.avatarTracks:
track.finish()
DelayDelete.cleanupDelayDeletes(track)
self.avatarTracks = []
def knockKnockTrack(self, avatar, duration):
if avatar == None:
return
self.rimshot = base.loadSfx('phase_5/audio/sfx/AA_heal_telljoke.mp3')
self.knockSfx = base.loadSfx('phase_5/audio/sfx/GUI_knock_3.mp3')
joke = KnockKnockJokes[self.propId % len(KnockKnockJokes)]
place = base.cr.playGame.getPlace()
if place:
zone = place.getZoneId()
branch = ZoneUtil.getBranchZone(zone)
if branch == ToontownGlobals.SillyStreet:
if self.propId == 44:
joke = KnockKnockContestJokes[ToontownGlobals.SillyStreet]
elif branch == ToontownGlobals.LoopyLane:
if self.propId in KnockKnockContestJokes[ToontownGlobals.LoopyLane].keys():
joke = KnockKnockContestJokes[ToontownGlobals.LoopyLane][self.propId]
elif branch == ToontownGlobals.PunchlinePlace:
if self.propId == 1:
joke = KnockKnockContestJokes[ToontownGlobals.PunchlinePlace]
elif branch == ToontownGlobals.PolarPlace:
if self.propId in KnockKnockContestJokes[ToontownGlobals.PolarPlace].keys():
joke = KnockKnockContestJokes[ToontownGlobals.PolarPlace][self.propId]
self.nametag = None
self.nametagNP = None
doorNP = render.find('**/KnockKnockDoorSphere_' + str(self.propId) + ';+s')
if doorNP.isEmpty():
self.notify.warning('Could not find KnockKnockDoorSphere_%s' % self.propId)
return
self.nametag = NametagGroup()
self.nametag.setAvatar(doorNP)
self.nametag.setFont(ToontownGlobals.getToonFont())
self.nametag.setName(TTLocalizer.DoorNametag)
self.nametag.setActive(0)
self.nametag.manage(base.marginManager)
self.nametag.getNametag3d().setBillboardOffset(4)
nametagNode = self.nametag.getNametag3d().upcastToPandaNode()
self.nametagNP = render.attachNewNode(nametagNode)
self.nametagNP.setName('knockKnockDoor_nt_' + str(self.propId))
pos = doorNP.node().getSolid(0).getCenter()
self.nametagNP.setPos(pos + Vec3(0, 0, avatar.getHeight() + 2))
d = duration * 0.125
track = Sequence(Parallel(Sequence(Wait(d * 0.5), SoundInterval(self.knockSfx)), Func(self.nametag.setChat, TTLocalizer.DoorKnockKnock, CFSpeech), Wait(d)), Func(avatar.setChatAbsolute, TTLocalizer.DoorWhosThere, CFSpeech | CFTimeout, openEnded=0), Wait(d), Func(self.nametag.setChat, joke[0], CFSpeech), Wait(d), Func(avatar.setChatAbsolute, joke[0] + TTLocalizer.DoorWhoAppendix, CFSpeech | CFTimeout, openEnded=0), Wait(d), Func(self.nametag.setChat, joke[1], CFSpeech), Parallel(SoundInterval(self.rimshot, startTime=2.0), Wait(d * 4)), Func(self.cleanupTrack))
track.delayDelete = DelayDelete.DelayDelete(avatar, 'knockKnockTrack')
return track
def cleanupTrack(self):
avatar = self.cr.doId2do.get(self.avatarId, None)
if avatar:
avatar.clearChat()
if self.nametag:
self.nametag.unmanage(base.marginManager)
self.nametagNP.removeNode()
self.nametag = None
self.nametagNP = None
return
def enterOff(self):
DistributedAnimatedProp.DistributedAnimatedProp.enterOff(self)
def exitOff(self):
DistributedAnimatedProp.DistributedAnimatedProp.exitOff(self)
def enterAttract(self, ts):
DistributedAnimatedProp.DistributedAnimatedProp.enterAttract(self, ts)
self.acceptAvatar()
def exitAttract(self):
DistributedAnimatedProp.DistributedAnimatedProp.exitAttract(self)
def enterPlaying(self, ts):
DistributedAnimatedProp.DistributedAnimatedProp.enterPlaying(self, ts)
if self.avatarId:
avatar = self.cr.doId2do.get(self.avatarId, None)
track = self.knockKnockTrack(avatar, 8)
if track != None:
track.start(ts)
self.avatarTracks.append(track)
return
def exitPlaying(self):
DistributedAnimatedProp.DistributedAnimatedProp.exitPlaying(self)
for track in self.avatarTracks:
track.finish()
DelayDelete.cleanupDelayDeletes(track)
self.avatarTracks = []
self.avatarId = 0
| mit |
yml/django-filer | filer/migrations/0001_initial.py | 36 | 13407 |
from south.db import db
from django.db import models
from filer.models import *
class Migration:
def forwards(self, orm):
# Adding model 'Image'
db.create_table('filer_image', (
('file_ptr', orm['filer.Image:file_ptr']),
('_height', orm['filer.Image:_height']),
('_width', orm['filer.Image:_width']),
('date_taken', orm['filer.Image:date_taken']),
('default_alt_text', orm['filer.Image:default_alt_text']),
('default_caption', orm['filer.Image:default_caption']),
('author', orm['filer.Image:author']),
('must_always_publish_author_credit', orm['filer.Image:must_always_publish_author_credit']),
('must_always_publish_copyright', orm['filer.Image:must_always_publish_copyright']),
('subject_location', orm['filer.Image:subject_location']),
))
db.send_create_signal('filer', ['Image'])
# Adding model 'ClipboardItem'
db.create_table('filer_clipboarditem', (
('id', orm['filer.ClipboardItem:id']),
('file', orm['filer.ClipboardItem:file']),
('clipboard', orm['filer.ClipboardItem:clipboard']),
))
db.send_create_signal('filer', ['ClipboardItem'])
# Adding model 'File'
db.create_table('filer_file', (
('id', orm['filer.File:id']),
('folder', orm['filer.File:folder']),
('file_field', orm['filer.File:file_field']),
('_file_type_plugin_name', orm['filer.File:_file_type_plugin_name']),
('_file_size', orm['filer.File:_file_size']),
('has_all_mandatory_data', orm['filer.File:has_all_mandatory_data']),
('original_filename', orm['filer.File:original_filename']),
('name', orm['filer.File:name']),
('owner', orm['filer.File:owner']),
('uploaded_at', orm['filer.File:uploaded_at']),
('modified_at', orm['filer.File:modified_at']),
))
db.send_create_signal('filer', ['File'])
# Adding model 'Folder'
db.create_table('filer_folder', (
('id', orm['filer.Folder:id']),
('parent', orm['filer.Folder:parent']),
('name', orm['filer.Folder:name']),
('owner', orm['filer.Folder:owner']),
('uploaded_at', orm['filer.Folder:uploaded_at']),
('created_at', orm['filer.Folder:created_at']),
('modified_at', orm['filer.Folder:modified_at']),
('lft', orm['filer.Folder:lft']),
('rght', orm['filer.Folder:rght']),
('tree_id', orm['filer.Folder:tree_id']),
('level', orm['filer.Folder:level']),
))
db.send_create_signal('filer', ['Folder'])
# Adding model 'Clipboard'
db.create_table('filer_clipboard', (
('id', orm['filer.Clipboard:id']),
('user', orm['filer.Clipboard:user']),
))
db.send_create_signal('filer', ['Clipboard'])
# Adding model 'FolderPermission'
db.create_table('filer_folderpermission', (
('id', orm['filer.FolderPermission:id']),
('folder', orm['filer.FolderPermission:folder']),
('type', orm['filer.FolderPermission:type']),
('user', orm['filer.FolderPermission:user']),
('group', orm['filer.FolderPermission:group']),
('everybody', orm['filer.FolderPermission:everybody']),
('can_edit', orm['filer.FolderPermission:can_edit']),
('can_read', orm['filer.FolderPermission:can_read']),
('can_add_children', orm['filer.FolderPermission:can_add_children']),
))
db.send_create_signal('filer', ['FolderPermission'])
# Creating unique_together for [parent, name] on Folder.
db.create_unique('filer_folder', ['parent_id', 'name'])
def backwards(self, orm):
# Deleting unique_together for [parent, name] on Folder.
db.delete_unique('filer_folder', ['parent_id', 'name'])
# Deleting model 'Image'
db.delete_table('filer_image')
# Deleting model 'ClipboardItem'
db.delete_table('filer_clipboarditem')
# Deleting model 'File'
db.delete_table('filer_file')
# Deleting model 'Folder'
db.delete_table('filer_folder')
# Deleting model 'Clipboard'
db.delete_table('filer_clipboard')
# Deleting model 'FolderPermission'
db.delete_table('filer_folderpermission')
models = {
'auth.group': {
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)"},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'filer.clipboard': {
'files': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['filer.File']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'clipboards'", 'to': "orm['auth.User']"})
},
'filer.clipboarditem': {
'clipboard': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['filer.Clipboard']"}),
'file': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['filer.File']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'filer.file': {
'_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'_file_type_plugin_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'file_field': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'all_files'", 'null': 'True', 'to': "orm['filer.Folder']"}),
'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_files'", 'null': 'True', 'to': "orm['auth.User']"}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
'filer.folder': {
'Meta': {'unique_together': "(('parent', 'name'),)"},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_folders'", 'null': 'True', 'to': "orm['auth.User']"}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['filer.Folder']"}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
'filer.folderpermission': {
'can_add_children': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'can_edit': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'can_read': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'everybody': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'folder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['filer.Folder']", 'null': 'True', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.Group']", 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'type': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
},
'filer.image': {
'_height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'_width': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'author': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'date_taken': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'default_alt_text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'default_caption': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'file_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['filer.File']", 'unique': 'True', 'primary_key': 'True'}),
'must_always_publish_author_credit': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'must_always_publish_copyright': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'subject_location': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '64', 'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['filer']
| mit |
jakobworldpeace/scikit-learn | sklearn/ensemble/forest.py | 8 | 67993 | """Forest of trees-based ensemble methods
Those methods include random forests and extremely randomized trees.
The module structure is the following:
- The ``BaseForest`` base class implements a common ``fit`` method for all
the estimators in the module. The ``fit`` method of the base ``Forest``
class calls the ``fit`` method of each sub-estimator on random samples
(with replacement, a.k.a. bootstrap) of the training set.
The init of the sub-estimator is further delegated to the
``BaseEnsemble`` constructor.
- The ``ForestClassifier`` and ``ForestRegressor`` base classes further
implement the prediction logic by computing an average of the predicted
outcomes of the sub-estimators.
- The ``RandomForestClassifier`` and ``RandomForestRegressor`` derived
classes provide the user with concrete implementations of
the forest ensemble method using classical, deterministic
``DecisionTreeClassifier`` and ``DecisionTreeRegressor`` as
sub-estimator implementations.
- The ``ExtraTreesClassifier`` and ``ExtraTreesRegressor`` derived
classes provide the user with concrete implementations of the
forest ensemble method using the extremely randomized trees
``ExtraTreeClassifier`` and ``ExtraTreeRegressor`` as
sub-estimator implementations.
Single and multi-output problems are both handled.
"""
# Authors: Gilles Louppe <g.louppe@gmail.com>
# Brian Holt <bdholt1@gmail.com>
# Joly Arnaud <arnaud.v.joly@gmail.com>
# Fares Hedayati <fares.hedayati@gmail.com>
#
# License: BSD 3 clause
from __future__ import division
import warnings
from warnings import warn
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.sparse import issparse
from scipy.sparse import hstack as sparse_hstack
from ..base import ClassifierMixin, RegressorMixin
from ..externals.joblib import Parallel, delayed
from ..externals import six
from ..metrics import r2_score
from ..preprocessing import OneHotEncoder
from ..tree import (DecisionTreeClassifier, DecisionTreeRegressor,
ExtraTreeClassifier, ExtraTreeRegressor)
from ..tree._tree import DTYPE, DOUBLE
from ..utils import check_random_state, check_array, compute_sample_weight
from ..exceptions import DataConversionWarning, NotFittedError
from .base import BaseEnsemble, _partition_estimators
from ..utils.fixes import bincount, parallel_helper
from ..utils.multiclass import check_classification_targets
from ..utils.validation import check_is_fitted
__all__ = ["RandomForestClassifier",
"RandomForestRegressor",
"ExtraTreesClassifier",
"ExtraTreesRegressor",
"RandomTreesEmbedding"]
MAX_INT = np.iinfo(np.int32).max
def _generate_sample_indices(random_state, n_samples):
"""Private function used to _parallel_build_trees function."""
random_instance = check_random_state(random_state)
sample_indices = random_instance.randint(0, n_samples, n_samples)
return sample_indices
def _generate_unsampled_indices(random_state, n_samples):
"""Private function used to forest._set_oob_score function."""
sample_indices = _generate_sample_indices(random_state, n_samples)
sample_counts = bincount(sample_indices, minlength=n_samples)
unsampled_mask = sample_counts == 0
indices_range = np.arange(n_samples)
unsampled_indices = indices_range[unsampled_mask]
return unsampled_indices
def _parallel_build_trees(tree, forest, X, y, sample_weight, tree_idx, n_trees,
verbose=0, class_weight=None):
"""Private function used to fit a single tree in parallel."""
if verbose > 1:
print("building tree %d of %d" % (tree_idx + 1, n_trees))
if forest.bootstrap:
n_samples = X.shape[0]
if sample_weight is None:
curr_sample_weight = np.ones((n_samples,), dtype=np.float64)
else:
curr_sample_weight = sample_weight.copy()
indices = _generate_sample_indices(tree.random_state, n_samples)
sample_counts = bincount(indices, minlength=n_samples)
curr_sample_weight *= sample_counts
if class_weight == 'subsample':
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
curr_sample_weight *= compute_sample_weight('auto', y, indices)
elif class_weight == 'balanced_subsample':
curr_sample_weight *= compute_sample_weight('balanced', y, indices)
tree.fit(X, y, sample_weight=curr_sample_weight, check_input=False)
else:
tree.fit(X, y, sample_weight=sample_weight, check_input=False)
return tree
class BaseForest(six.with_metaclass(ABCMeta, BaseEnsemble)):
"""Base class for forests of trees.
Warning: This class should not be used directly. Use derived classes
instead.
"""
@abstractmethod
def __init__(self,
base_estimator,
n_estimators=10,
estimator_params=tuple(),
bootstrap=False,
oob_score=False,
n_jobs=1,
random_state=None,
verbose=0,
warm_start=False,
class_weight=None):
super(BaseForest, self).__init__(
base_estimator=base_estimator,
n_estimators=n_estimators,
estimator_params=estimator_params)
self.bootstrap = bootstrap
self.oob_score = oob_score
self.n_jobs = n_jobs
self.random_state = random_state
self.verbose = verbose
self.warm_start = warm_start
self.class_weight = class_weight
def apply(self, X):
"""Apply trees in the forest to X, return leaf indices.
Parameters
----------
X : array-like or sparse matrix, shape = [n_samples, n_features]
The input samples. Internally, its dtype will be converted to
``dtype=np.float32``. If a sparse matrix is provided, it will be
converted into a sparse ``csr_matrix``.
Returns
-------
X_leaves : array_like, shape = [n_samples, n_estimators]
For each datapoint x in X and for each tree in the forest,
return the index of the leaf x ends up in.
"""
X = self._validate_X_predict(X)
results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose,
backend="threading")(
delayed(parallel_helper)(tree, 'apply', X, check_input=False)
for tree in self.estimators_)
return np.array(results).T
def decision_path(self, X):
"""Return the decision path in the forest
.. versionadded:: 0.18
Parameters
----------
X : array-like or sparse matrix, shape = [n_samples, n_features]
The input samples. Internally, its dtype will be converted to
``dtype=np.float32``. If a sparse matrix is provided, it will be
converted into a sparse ``csr_matrix``.
Returns
-------
indicator : sparse csr array, shape = [n_samples, n_nodes]
Return a node indicator matrix where non zero elements
indicates that the samples goes through the nodes.
n_nodes_ptr : array of size (n_estimators + 1, )
The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]]
gives the indicator value for the i-th estimator.
"""
X = self._validate_X_predict(X)
indicators = Parallel(n_jobs=self.n_jobs, verbose=self.verbose,
backend="threading")(
delayed(parallel_helper)(tree, 'decision_path', X,
check_input=False)
for tree in self.estimators_)
n_nodes = [0]
n_nodes.extend([i.shape[1] for i in indicators])
n_nodes_ptr = np.array(n_nodes).cumsum()
return sparse_hstack(indicators).tocsr(), n_nodes_ptr
def fit(self, X, y, sample_weight=None):
"""Build a forest of trees from the training set (X, y).
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The training input samples. Internally, its dtype will be converted to
``dtype=np.float32``. If a sparse matrix is provided, it will be
converted into a sparse ``csc_matrix``.
y : array-like, shape = [n_samples] or [n_samples, n_outputs]
The target values (class labels in classification, real numbers in
regression).
sample_weight : array-like, shape = [n_samples] or None
Sample weights. If None, then samples are equally weighted. Splits
that would create child nodes with net zero or negative weight are
ignored while searching for a split in each node. In the case of
classification, splits are also ignored if they would result in any
single class carrying a negative weight in either child node.
Returns
-------
self : object
Returns self.
"""
# Validate or convert input data
X = check_array(X, accept_sparse="csc", dtype=DTYPE)
y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)
if sample_weight is not None:
sample_weight = check_array(sample_weight, ensure_2d=False)
if issparse(X):
# Pre-sort indices to avoid that each individual tree of the
# ensemble sorts the indices.
X.sort_indices()
# Remap output
n_samples, self.n_features_ = X.shape
y = np.atleast_1d(y)
if y.ndim == 2 and y.shape[1] == 1:
warn("A column-vector y was passed when a 1d array was"
" expected. Please change the shape of y to "
"(n_samples,), for example using ravel().",
DataConversionWarning, stacklevel=2)
if y.ndim == 1:
# reshape is necessary to preserve the data contiguity against vs
# [:, np.newaxis] that does not.
y = np.reshape(y, (-1, 1))
self.n_outputs_ = y.shape[1]
y, expanded_class_weight = self._validate_y_class_weight(y)
if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:
y = np.ascontiguousarray(y, dtype=DOUBLE)
if expanded_class_weight is not None:
if sample_weight is not None:
sample_weight = sample_weight * expanded_class_weight
else:
sample_weight = expanded_class_weight
# Check parameters
self._validate_estimator()
if not self.bootstrap and self.oob_score:
raise ValueError("Out of bag estimation only available"
" if bootstrap=True")
random_state = check_random_state(self.random_state)
if not self.warm_start or not hasattr(self, "estimators_"):
# Free allocated memory, if any
self.estimators_ = []
n_more_estimators = self.n_estimators - len(self.estimators_)
if n_more_estimators < 0:
raise ValueError('n_estimators=%d must be larger or equal to '
'len(estimators_)=%d when warm_start==True'
% (self.n_estimators, len(self.estimators_)))
elif n_more_estimators == 0:
warn("Warm-start fitting without increasing n_estimators does not "
"fit new trees.")
else:
if self.warm_start and len(self.estimators_) > 0:
# We draw from the random state to get the random state we
# would have got if we hadn't used a warm_start.
random_state.randint(MAX_INT, size=len(self.estimators_))
trees = []
for i in range(n_more_estimators):
tree = self._make_estimator(append=False,
random_state=random_state)
trees.append(tree)
# Parallel loop: we use the threading backend as the Cython code
# for fitting the trees is internally releasing the Python GIL
# making threading always more efficient than multiprocessing in
# that case.
trees = Parallel(n_jobs=self.n_jobs, verbose=self.verbose,
backend="threading")(
delayed(_parallel_build_trees)(
t, self, X, y, sample_weight, i, len(trees),
verbose=self.verbose, class_weight=self.class_weight)
for i, t in enumerate(trees))
# Collect newly grown trees
self.estimators_.extend(trees)
if self.oob_score:
self._set_oob_score(X, y)
# Decapsulate classes_ attributes
if hasattr(self, "classes_") and self.n_outputs_ == 1:
self.n_classes_ = self.n_classes_[0]
self.classes_ = self.classes_[0]
return self
@abstractmethod
def _set_oob_score(self, X, y):
"""Calculate out of bag predictions and score."""
def _validate_y_class_weight(self, y):
# Default implementation
return y, None
def _validate_X_predict(self, X):
"""Validate X whenever one tries to predict, apply, predict_proba"""
if self.estimators_ is None or len(self.estimators_) == 0:
raise NotFittedError("Estimator not fitted, "
"call `fit` before exploiting the model.")
return self.estimators_[0]._validate_X_predict(X, check_input=True)
@property
def feature_importances_(self):
"""Return the feature importances (the higher, the more important the
feature).
Returns
-------
feature_importances_ : array, shape = [n_features]
"""
check_is_fitted(self, 'estimators_')
all_importances = Parallel(n_jobs=self.n_jobs,
backend="threading")(
delayed(getattr)(tree, 'feature_importances_')
for tree in self.estimators_)
return sum(all_importances) / len(self.estimators_)
class ForestClassifier(six.with_metaclass(ABCMeta, BaseForest,
ClassifierMixin)):
"""Base class for forest of trees-based classifiers.
Warning: This class should not be used directly. Use derived classes
instead.
"""
@abstractmethod
def __init__(self,
base_estimator,
n_estimators=10,
estimator_params=tuple(),
bootstrap=False,
oob_score=False,
n_jobs=1,
random_state=None,
verbose=0,
warm_start=False,
class_weight=None):
super(ForestClassifier, self).__init__(
base_estimator,
n_estimators=n_estimators,
estimator_params=estimator_params,
bootstrap=bootstrap,
oob_score=oob_score,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start,
class_weight=class_weight)
def _set_oob_score(self, X, y):
"""Compute out-of-bag score"""
X = check_array(X, dtype=DTYPE, accept_sparse='csr')
n_classes_ = self.n_classes_
n_samples = y.shape[0]
oob_decision_function = []
oob_score = 0.0
predictions = []
for k in range(self.n_outputs_):
predictions.append(np.zeros((n_samples, n_classes_[k])))
for estimator in self.estimators_:
unsampled_indices = _generate_unsampled_indices(
estimator.random_state, n_samples)
p_estimator = estimator.predict_proba(X[unsampled_indices, :],
check_input=False)
if self.n_outputs_ == 1:
p_estimator = [p_estimator]
for k in range(self.n_outputs_):
predictions[k][unsampled_indices, :] += p_estimator[k]
for k in range(self.n_outputs_):
if (predictions[k].sum(axis=1) == 0).any():
warn("Some inputs do not have OOB scores. "
"This probably means too few trees were used "
"to compute any reliable oob estimates.")
decision = (predictions[k] /
predictions[k].sum(axis=1)[:, np.newaxis])
oob_decision_function.append(decision)
oob_score += np.mean(y[:, k] ==
np.argmax(predictions[k], axis=1), axis=0)
if self.n_outputs_ == 1:
self.oob_decision_function_ = oob_decision_function[0]
else:
self.oob_decision_function_ = oob_decision_function
self.oob_score_ = oob_score / self.n_outputs_
def _validate_y_class_weight(self, y):
check_classification_targets(y)
y = np.copy(y)
expanded_class_weight = None
if self.class_weight is not None:
y_original = np.copy(y)
self.classes_ = []
self.n_classes_ = []
y_store_unique_indices = np.zeros(y.shape, dtype=np.int)
for k in range(self.n_outputs_):
classes_k, y_store_unique_indices[:, k] = np.unique(y[:, k], return_inverse=True)
self.classes_.append(classes_k)
self.n_classes_.append(classes_k.shape[0])
y = y_store_unique_indices
if self.class_weight is not None:
valid_presets = ('balanced', 'balanced_subsample')
if isinstance(self.class_weight, six.string_types):
if self.class_weight not in valid_presets:
raise ValueError('Valid presets for class_weight include '
'"balanced" and "balanced_subsample". Given "%s".'
% self.class_weight)
if self.warm_start:
warn('class_weight presets "balanced" or "balanced_subsample" are '
'not recommended for warm_start if the fitted data '
'differs from the full dataset. In order to use '
'"balanced" weights, use compute_class_weight("balanced", '
'classes, y). In place of y you can use a large '
'enough sample of the full training set target to '
'properly estimate the class frequency '
'distributions. Pass the resulting weights as the '
'class_weight parameter.')
if (self.class_weight != 'balanced_subsample' or
not self.bootstrap):
if self.class_weight == "balanced_subsample":
class_weight = "balanced"
else:
class_weight = self.class_weight
expanded_class_weight = compute_sample_weight(class_weight,
y_original)
return y, expanded_class_weight
def predict(self, X):
"""Predict class for X.
The predicted class of an input sample is a vote by the trees in
the forest, weighted by their probability estimates. That is,
the predicted class is the one with highest mean probability
estimate across the trees.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples. Internally, its dtype will be converted to
``dtype=np.float32``. If a sparse matrix is provided, it will be
converted into a sparse ``csr_matrix``.
Returns
-------
y : array of shape = [n_samples] or [n_samples, n_outputs]
The predicted classes.
"""
proba = self.predict_proba(X)
if self.n_outputs_ == 1:
return self.classes_.take(np.argmax(proba, axis=1), axis=0)
else:
n_samples = proba[0].shape[0]
predictions = np.zeros((n_samples, self.n_outputs_))
for k in range(self.n_outputs_):
predictions[:, k] = self.classes_[k].take(np.argmax(proba[k],
axis=1),
axis=0)
return predictions
def predict_proba(self, X):
"""Predict class probabilities for X.
The predicted class probabilities of an input sample are computed as
the mean predicted class probabilities of the trees in the forest. The
class probability of a single tree is the fraction of samples of the same
class in a leaf.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples. Internally, its dtype will be converted to
``dtype=np.float32``. If a sparse matrix is provided, it will be
converted into a sparse ``csr_matrix``.
Returns
-------
p : array of shape = [n_samples, n_classes], or a list of n_outputs
such arrays if n_outputs > 1.
The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute `classes_`.
"""
check_is_fitted(self, 'estimators_')
# Check data
X = self._validate_X_predict(X)
# Assign chunk of trees to jobs
n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs)
# Parallel loop
all_proba = Parallel(n_jobs=n_jobs, verbose=self.verbose,
backend="threading")(
delayed(parallel_helper)(e, 'predict_proba', X,
check_input=False)
for e in self.estimators_)
# Reduce
proba = all_proba[0]
if self.n_outputs_ == 1:
for j in range(1, len(all_proba)):
proba += all_proba[j]
proba /= len(self.estimators_)
else:
for j in range(1, len(all_proba)):
for k in range(self.n_outputs_):
proba[k] += all_proba[j][k]
for k in range(self.n_outputs_):
proba[k] /= self.n_estimators
return proba
def predict_log_proba(self, X):
"""Predict class log-probabilities for X.
The predicted class log-probabilities of an input sample is computed as
the log of the mean predicted class probabilities of the trees in the
forest.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples. Internally, its dtype will be converted to
``dtype=np.float32``. If a sparse matrix is provided, it will be
converted into a sparse ``csr_matrix``.
Returns
-------
p : array of shape = [n_samples, n_classes], or a list of n_outputs
such arrays if n_outputs > 1.
The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute `classes_`.
"""
proba = self.predict_proba(X)
if self.n_outputs_ == 1:
return np.log(proba)
else:
for k in range(self.n_outputs_):
proba[k] = np.log(proba[k])
return proba
class ForestRegressor(six.with_metaclass(ABCMeta, BaseForest, RegressorMixin)):
"""Base class for forest of trees-based regressors.
Warning: This class should not be used directly. Use derived classes
instead.
"""
@abstractmethod
def __init__(self,
base_estimator,
n_estimators=10,
estimator_params=tuple(),
bootstrap=False,
oob_score=False,
n_jobs=1,
random_state=None,
verbose=0,
warm_start=False):
super(ForestRegressor, self).__init__(
base_estimator,
n_estimators=n_estimators,
estimator_params=estimator_params,
bootstrap=bootstrap,
oob_score=oob_score,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start)
def predict(self, X):
"""Predict regression target for X.
The predicted regression target of an input sample is computed as the
mean predicted regression targets of the trees in the forest.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples. Internally, its dtype will be converted to
``dtype=np.float32``. If a sparse matrix is provided, it will be
converted into a sparse ``csr_matrix``.
Returns
-------
y : array of shape = [n_samples] or [n_samples, n_outputs]
The predicted values.
"""
check_is_fitted(self, 'estimators_')
# Check data
X = self._validate_X_predict(X)
# Assign chunk of trees to jobs
n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs)
# Parallel loop
all_y_hat = Parallel(n_jobs=n_jobs, verbose=self.verbose,
backend="threading")(
delayed(parallel_helper)(e, 'predict', X, check_input=False)
for e in self.estimators_)
# Reduce
y_hat = sum(all_y_hat) / len(self.estimators_)
return y_hat
def _set_oob_score(self, X, y):
"""Compute out-of-bag scores"""
X = check_array(X, dtype=DTYPE, accept_sparse='csr')
n_samples = y.shape[0]
predictions = np.zeros((n_samples, self.n_outputs_))
n_predictions = np.zeros((n_samples, self.n_outputs_))
for estimator in self.estimators_:
unsampled_indices = _generate_unsampled_indices(
estimator.random_state, n_samples)
p_estimator = estimator.predict(
X[unsampled_indices, :], check_input=False)
if self.n_outputs_ == 1:
p_estimator = p_estimator[:, np.newaxis]
predictions[unsampled_indices, :] += p_estimator
n_predictions[unsampled_indices, :] += 1
if (n_predictions == 0).any():
warn("Some inputs do not have OOB scores. "
"This probably means too few trees were used "
"to compute any reliable oob estimates.")
n_predictions[n_predictions == 0] = 1
predictions /= n_predictions
self.oob_prediction_ = predictions
if self.n_outputs_ == 1:
self.oob_prediction_ = \
self.oob_prediction_.reshape((n_samples, ))
self.oob_score_ = 0.0
for k in range(self.n_outputs_):
self.oob_score_ += r2_score(y[:, k],
predictions[:, k])
self.oob_score_ /= self.n_outputs_
class RandomForestClassifier(ForestClassifier):
"""A random forest classifier.
A random forest is a meta estimator that fits a number of decision tree
classifiers on various sub-samples of the dataset and use averaging to
improve the predictive accuracy and control over-fitting.
The sub-sample size is always the same as the original
input sample size but the samples are drawn with replacement if
`bootstrap=True` (default).
Read more in the :ref:`User Guide <forest>`.
Parameters
----------
n_estimators : integer, optional (default=10)
The number of trees in the forest.
criterion : string, optional (default="gini")
The function to measure the quality of a split. Supported criteria are
"gini" for the Gini impurity and "entropy" for the information gain.
Note: this parameter is tree-specific.
max_features : int, float, string or None, optional (default="auto")
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a percentage and
`int(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=sqrt(n_features)`.
- If "sqrt", then `max_features=sqrt(n_features)` (same as "auto").
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
max_depth : integer or None, optional (default=None)
The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int, float, optional (default=2)
The minimum number of samples required to split an internal node:
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a percentage and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.
.. versionchanged:: 0.18
Added float values for percentages.
min_samples_leaf : int, float, optional (default=1)
The minimum number of samples required to be at a leaf node:
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a percentage and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
.. versionchanged:: 0.18
Added float values for percentages.
min_weight_fraction_leaf : float, optional (default=0.)
The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
max_leaf_nodes : int or None, optional (default=None)
Grow trees with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
min_impurity_split : float, optional (default=1e-7)
Threshold for early stopping in tree growth. A node will split
if its impurity is above the threshold, otherwise it is a leaf.
.. versionadded:: 0.18
bootstrap : boolean, optional (default=True)
Whether bootstrap samples are used when building trees.
oob_score : bool (default=False)
Whether to use out-of-bag samples to estimate
the generalization accuracy.
n_jobs : integer, optional (default=1)
The number of jobs to run in parallel for both `fit` and `predict`.
If -1, then the number of jobs is set to the number of cores.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
verbose : int, optional (default=0)
Controls the verbosity of the tree building process.
warm_start : bool, optional (default=False)
When set to ``True``, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest.
class_weight : dict, list of dicts, "balanced",
"balanced_subsample" or None, optional (default=None)
Weights associated with classes in the form ``{class_label: weight}``.
If not given, all classes are supposed to have weight one. For
multi-output problems, a list of dicts can be provided in the same
order as the columns of y.
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``
The "balanced_subsample" mode is the same as "balanced" except that
weights are computed based on the bootstrap sample for every tree
grown.
For multi-output, the weights of each column of y will be multiplied.
Note that these weights will be multiplied with sample_weight (passed
through the fit method) if sample_weight is specified.
Attributes
----------
estimators_ : list of DecisionTreeClassifier
The collection of fitted sub-estimators.
classes_ : array of shape = [n_classes] or a list of such arrays
The classes labels (single output problem), or a list of arrays of
class labels (multi-output problem).
n_classes_ : int or list
The number of classes (single output problem), or a list containing the
number of classes for each output (multi-output problem).
n_features_ : int
The number of features when ``fit`` is performed.
n_outputs_ : int
The number of outputs when ``fit`` is performed.
feature_importances_ : array of shape = [n_features]
The feature importances (the higher, the more important the feature).
oob_score_ : float
Score of the training dataset obtained using an out-of-bag estimate.
oob_decision_function_ : array of shape = [n_samples, n_classes]
Decision function computed with out-of-bag estimate on the training
set. If n_estimators is small it might be possible that a data point
was never left out during the bootstrap. In this case,
`oob_decision_function_` might contain NaN.
Notes
-----
The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data,
``max_features=n_features`` and ``bootstrap=False``, if the improvement
of the criterion is identical for several splits enumerated during the
search of the best split. To obtain a deterministic behaviour during
fitting, ``random_state`` has to be fixed.
References
----------
.. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001.
See also
--------
DecisionTreeClassifier, ExtraTreesClassifier
"""
def __init__(self,
n_estimators=10,
criterion="gini",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_features="auto",
max_leaf_nodes=None,
min_impurity_split=1e-7,
bootstrap=True,
oob_score=False,
n_jobs=1,
random_state=None,
verbose=0,
warm_start=False,
class_weight=None):
super(RandomForestClassifier, self).__init__(
base_estimator=DecisionTreeClassifier(),
n_estimators=n_estimators,
estimator_params=("criterion", "max_depth", "min_samples_split",
"min_samples_leaf", "min_weight_fraction_leaf",
"max_features", "max_leaf_nodes", "min_impurity_split",
"random_state"),
bootstrap=bootstrap,
oob_score=oob_score,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start,
class_weight=class_weight)
self.criterion = criterion
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = max_features
self.max_leaf_nodes = max_leaf_nodes
self.min_impurity_split = min_impurity_split
class RandomForestRegressor(ForestRegressor):
"""A random forest regressor.
A random forest is a meta estimator that fits a number of classifying
decision trees on various sub-samples of the dataset and use averaging
to improve the predictive accuracy and control over-fitting.
The sub-sample size is always the same as the original
input sample size but the samples are drawn with replacement if
`bootstrap=True` (default).
Read more in the :ref:`User Guide <forest>`.
Parameters
----------
n_estimators : integer, optional (default=10)
The number of trees in the forest.
criterion : string, optional (default="mse")
The function to measure the quality of a split. Supported criteria
are "mse" for the mean squared error, which is equal to variance
reduction as feature selection criterion, and "mae" for the mean
absolute error.
.. versionadded:: 0.18
Mean Absolute Error (MAE) criterion.
max_features : int, float, string or None, optional (default="auto")
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a percentage and
`int(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=n_features`.
- If "sqrt", then `max_features=sqrt(n_features)`.
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
max_depth : integer or None, optional (default=None)
The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int, float, optional (default=2)
The minimum number of samples required to split an internal node:
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a percentage and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.
.. versionchanged:: 0.18
Added float values for percentages.
min_samples_leaf : int, float, optional (default=1)
The minimum number of samples required to be at a leaf node:
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a percentage and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
.. versionchanged:: 0.18
Added float values for percentages.
min_weight_fraction_leaf : float, optional (default=0.)
The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
max_leaf_nodes : int or None, optional (default=None)
Grow trees with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
min_impurity_split : float, optional (default=1e-7)
Threshold for early stopping in tree growth. A node will split
if its impurity is above the threshold, otherwise it is a leaf.
.. versionadded:: 0.18
bootstrap : boolean, optional (default=True)
Whether bootstrap samples are used when building trees.
oob_score : bool, optional (default=False)
whether to use out-of-bag samples to estimate
the R^2 on unseen data.
n_jobs : integer, optional (default=1)
The number of jobs to run in parallel for both `fit` and `predict`.
If -1, then the number of jobs is set to the number of cores.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
verbose : int, optional (default=0)
Controls the verbosity of the tree building process.
warm_start : bool, optional (default=False)
When set to ``True``, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest.
Attributes
----------
estimators_ : list of DecisionTreeRegressor
The collection of fitted sub-estimators.
feature_importances_ : array of shape = [n_features]
The feature importances (the higher, the more important the feature).
n_features_ : int
The number of features when ``fit`` is performed.
n_outputs_ : int
The number of outputs when ``fit`` is performed.
oob_score_ : float
Score of the training dataset obtained using an out-of-bag estimate.
oob_prediction_ : array of shape = [n_samples]
Prediction computed with out-of-bag estimate on the training set.
Notes
-----
The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data,
``max_features=n_features`` and ``bootstrap=False``, if the improvement
of the criterion is identical for several splits enumerated during the
search of the best split. To obtain a deterministic behaviour during
fitting, ``random_state`` has to be fixed.
References
----------
.. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001.
See also
--------
DecisionTreeRegressor, ExtraTreesRegressor
"""
def __init__(self,
n_estimators=10,
criterion="mse",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_features="auto",
max_leaf_nodes=None,
min_impurity_split=1e-7,
bootstrap=True,
oob_score=False,
n_jobs=1,
random_state=None,
verbose=0,
warm_start=False):
super(RandomForestRegressor, self).__init__(
base_estimator=DecisionTreeRegressor(),
n_estimators=n_estimators,
estimator_params=("criterion", "max_depth", "min_samples_split",
"min_samples_leaf", "min_weight_fraction_leaf",
"max_features", "max_leaf_nodes", "min_impurity_split",
"random_state"),
bootstrap=bootstrap,
oob_score=oob_score,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start)
self.criterion = criterion
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = max_features
self.max_leaf_nodes = max_leaf_nodes
self.min_impurity_split = min_impurity_split
class ExtraTreesClassifier(ForestClassifier):
"""An extra-trees classifier.
This class implements a meta estimator that fits a number of
randomized decision trees (a.k.a. extra-trees) on various sub-samples
of the dataset and use averaging to improve the predictive accuracy
and control over-fitting.
Read more in the :ref:`User Guide <forest>`.
Parameters
----------
n_estimators : integer, optional (default=10)
The number of trees in the forest.
criterion : string, optional (default="gini")
The function to measure the quality of a split. Supported criteria are
"gini" for the Gini impurity and "entropy" for the information gain.
max_features : int, float, string or None, optional (default="auto")
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a percentage and
`int(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=sqrt(n_features)`.
- If "sqrt", then `max_features=sqrt(n_features)`.
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
max_depth : integer or None, optional (default=None)
The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int, float, optional (default=2)
The minimum number of samples required to split an internal node:
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a percentage and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.
.. versionchanged:: 0.18
Added float values for percentages.
min_samples_leaf : int, float, optional (default=1)
The minimum number of samples required to be at a leaf node:
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a percentage and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
.. versionchanged:: 0.18
Added float values for percentages.
min_weight_fraction_leaf : float, optional (default=0.)
The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
max_leaf_nodes : int or None, optional (default=None)
Grow trees with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
min_impurity_split : float, optional (default=1e-7)
Threshold for early stopping in tree growth. A node will split
if its impurity is above the threshold, otherwise it is a leaf.
.. versionadded:: 0.18
bootstrap : boolean, optional (default=False)
Whether bootstrap samples are used when building trees.
oob_score : bool, optional (default=False)
Whether to use out-of-bag samples to estimate
the generalization accuracy.
n_jobs : integer, optional (default=1)
The number of jobs to run in parallel for both `fit` and `predict`.
If -1, then the number of jobs is set to the number of cores.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
verbose : int, optional (default=0)
Controls the verbosity of the tree building process.
warm_start : bool, optional (default=False)
When set to ``True``, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest.
class_weight : dict, list of dicts, "balanced", "balanced_subsample" or None, optional (default=None)
Weights associated with classes in the form ``{class_label: weight}``.
If not given, all classes are supposed to have weight one. For
multi-output problems, a list of dicts can be provided in the same
order as the columns of y.
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``
The "balanced_subsample" mode is the same as "balanced" except that weights are
computed based on the bootstrap sample for every tree grown.
For multi-output, the weights of each column of y will be multiplied.
Note that these weights will be multiplied with sample_weight (passed
through the fit method) if sample_weight is specified.
Attributes
----------
estimators_ : list of DecisionTreeClassifier
The collection of fitted sub-estimators.
classes_ : array of shape = [n_classes] or a list of such arrays
The classes labels (single output problem), or a list of arrays of
class labels (multi-output problem).
n_classes_ : int or list
The number of classes (single output problem), or a list containing the
number of classes for each output (multi-output problem).
feature_importances_ : array of shape = [n_features]
The feature importances (the higher, the more important the feature).
n_features_ : int
The number of features when ``fit`` is performed.
n_outputs_ : int
The number of outputs when ``fit`` is performed.
oob_score_ : float
Score of the training dataset obtained using an out-of-bag estimate.
oob_decision_function_ : array of shape = [n_samples, n_classes]
Decision function computed with out-of-bag estimate on the training
set. If n_estimators is small it might be possible that a data point
was never left out during the bootstrap. In this case,
`oob_decision_function_` might contain NaN.
References
----------
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
Machine Learning, 63(1), 3-42, 2006.
See also
--------
sklearn.tree.ExtraTreeClassifier : Base classifier for this ensemble.
RandomForestClassifier : Ensemble Classifier based on trees with optimal
splits.
"""
def __init__(self,
n_estimators=10,
criterion="gini",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_features="auto",
max_leaf_nodes=None,
min_impurity_split=1e-7,
bootstrap=False,
oob_score=False,
n_jobs=1,
random_state=None,
verbose=0,
warm_start=False,
class_weight=None):
super(ExtraTreesClassifier, self).__init__(
base_estimator=ExtraTreeClassifier(),
n_estimators=n_estimators,
estimator_params=("criterion", "max_depth", "min_samples_split",
"min_samples_leaf", "min_weight_fraction_leaf",
"max_features", "max_leaf_nodes", "min_impurity_split",
"random_state"),
bootstrap=bootstrap,
oob_score=oob_score,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start,
class_weight=class_weight)
self.criterion = criterion
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = max_features
self.max_leaf_nodes = max_leaf_nodes
self.min_impurity_split = min_impurity_split
class ExtraTreesRegressor(ForestRegressor):
"""An extra-trees regressor.
This class implements a meta estimator that fits a number of
randomized decision trees (a.k.a. extra-trees) on various sub-samples
of the dataset and use averaging to improve the predictive accuracy
and control over-fitting.
Read more in the :ref:`User Guide <forest>`.
Parameters
----------
n_estimators : integer, optional (default=10)
The number of trees in the forest.
criterion : string, optional (default="mse")
The function to measure the quality of a split. Supported criteria
are "mse" for the mean squared error, which is equal to variance
reduction as feature selection criterion, and "mae" for the mean
absolute error.
.. versionadded:: 0.18
Mean Absolute Error (MAE) criterion.
max_features : int, float, string or None, optional (default="auto")
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a percentage and
`int(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=n_features`.
- If "sqrt", then `max_features=sqrt(n_features)`.
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
max_depth : integer or None, optional (default=None)
The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int, float, optional (default=2)
The minimum number of samples required to split an internal node:
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a percentage and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.
.. versionchanged:: 0.18
Added float values for percentages.
min_samples_leaf : int, float, optional (default=1)
The minimum number of samples required to be at a leaf node:
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a percentage and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
.. versionchanged:: 0.18
Added float values for percentages.
min_weight_fraction_leaf : float, optional (default=0.)
The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
max_leaf_nodes : int or None, optional (default=None)
Grow trees with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
min_impurity_split : float, optional (default=1e-7)
Threshold for early stopping in tree growth. A node will split
if its impurity is above the threshold, otherwise it is a leaf.
.. versionadded:: 0.18
bootstrap : boolean, optional (default=False)
Whether bootstrap samples are used when building trees.
oob_score : bool, optional (default=False)
Whether to use out-of-bag samples to estimate the R^2 on unseen data.
n_jobs : integer, optional (default=1)
The number of jobs to run in parallel for both `fit` and `predict`.
If -1, then the number of jobs is set to the number of cores.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
verbose : int, optional (default=0)
Controls the verbosity of the tree building process.
warm_start : bool, optional (default=False)
When set to ``True``, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest.
Attributes
----------
estimators_ : list of DecisionTreeRegressor
The collection of fitted sub-estimators.
feature_importances_ : array of shape = [n_features]
The feature importances (the higher, the more important the feature).
n_features_ : int
The number of features.
n_outputs_ : int
The number of outputs.
oob_score_ : float
Score of the training dataset obtained using an out-of-bag estimate.
oob_prediction_ : array of shape = [n_samples]
Prediction computed with out-of-bag estimate on the training set.
References
----------
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
Machine Learning, 63(1), 3-42, 2006.
See also
--------
sklearn.tree.ExtraTreeRegressor: Base estimator for this ensemble.
RandomForestRegressor: Ensemble regressor using trees with optimal splits.
"""
def __init__(self,
n_estimators=10,
criterion="mse",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_features="auto",
max_leaf_nodes=None,
min_impurity_split=1e-7,
bootstrap=False,
oob_score=False,
n_jobs=1,
random_state=None,
verbose=0,
warm_start=False):
super(ExtraTreesRegressor, self).__init__(
base_estimator=ExtraTreeRegressor(),
n_estimators=n_estimators,
estimator_params=("criterion", "max_depth", "min_samples_split",
"min_samples_leaf", "min_weight_fraction_leaf",
"max_features", "max_leaf_nodes", "min_impurity_split",
"random_state"),
bootstrap=bootstrap,
oob_score=oob_score,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start)
self.criterion = criterion
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = max_features
self.max_leaf_nodes = max_leaf_nodes
self.min_impurity_split = min_impurity_split
class RandomTreesEmbedding(BaseForest):
"""An ensemble of totally random trees.
An unsupervised transformation of a dataset to a high-dimensional
sparse representation. A datapoint is coded according to which leaf of
each tree it is sorted into. Using a one-hot encoding of the leaves,
this leads to a binary coding with as many ones as there are trees in
the forest.
The dimensionality of the resulting representation is
``n_out <= n_estimators * max_leaf_nodes``. If ``max_leaf_nodes == None``,
the number of leaf nodes is at most ``n_estimators * 2 ** max_depth``.
Read more in the :ref:`User Guide <random_trees_embedding>`.
Parameters
----------
n_estimators : integer, optional (default=10)
Number of trees in the forest.
max_depth : integer, optional (default=5)
The maximum depth of each tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int, float, optional (default=2)
The minimum number of samples required to split an internal node:
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a percentage and
`ceil(min_samples_split * n_samples)` is the minimum
number of samples for each split.
.. versionchanged:: 0.18
Added float values for percentages.
min_samples_leaf : int, float, optional (default=1)
The minimum number of samples required to be at a leaf node:
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a percentage and
`ceil(min_samples_leaf * n_samples)` is the minimum
number of samples for each node.
.. versionchanged:: 0.18
Added float values for percentages.
min_weight_fraction_leaf : float, optional (default=0.)
The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
max_leaf_nodes : int or None, optional (default=None)
Grow trees with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
min_impurity_split : float, optional (default=1e-7)
Threshold for early stopping in tree growth. A node will split
if its impurity is above the threshold, otherwise it is a leaf.
.. versionadded:: 0.18
sparse_output : bool, optional (default=True)
Whether or not to return a sparse CSR matrix, as default behavior,
or to return a dense array compatible with dense pipeline operators.
n_jobs : integer, optional (default=1)
The number of jobs to run in parallel for both `fit` and `predict`.
If -1, then the number of jobs is set to the number of cores.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
verbose : int, optional (default=0)
Controls the verbosity of the tree building process.
warm_start : bool, optional (default=False)
When set to ``True``, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest.
Attributes
----------
estimators_ : list of DecisionTreeClassifier
The collection of fitted sub-estimators.
References
----------
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
Machine Learning, 63(1), 3-42, 2006.
.. [2] Moosmann, F. and Triggs, B. and Jurie, F. "Fast discriminative
visual codebooks using randomized clustering forests"
NIPS 2007
"""
def __init__(self,
n_estimators=10,
max_depth=5,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_leaf_nodes=None,
min_impurity_split=1e-7,
sparse_output=True,
n_jobs=1,
random_state=None,
verbose=0,
warm_start=False):
super(RandomTreesEmbedding, self).__init__(
base_estimator=ExtraTreeRegressor(),
n_estimators=n_estimators,
estimator_params=("criterion", "max_depth", "min_samples_split",
"min_samples_leaf", "min_weight_fraction_leaf",
"max_features", "max_leaf_nodes", "min_impurity_split",
"random_state"),
bootstrap=False,
oob_score=False,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start)
self.criterion = 'mse'
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = 1
self.max_leaf_nodes = max_leaf_nodes
self.min_impurity_split = min_impurity_split
self.sparse_output = sparse_output
def _set_oob_score(self, X, y):
raise NotImplementedError("OOB score not supported by tree embedding")
def fit(self, X, y=None, sample_weight=None):
"""Fit estimator.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
The input samples. Use ``dtype=np.float32`` for maximum
efficiency. Sparse matrices are also supported, use sparse
``csc_matrix`` for maximum efficiency.
Returns
-------
self : object
Returns self.
"""
self.fit_transform(X, y, sample_weight=sample_weight)
return self
def fit_transform(self, X, y=None, sample_weight=None):
"""Fit estimator and transform dataset.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
Input data used to build forests. Use ``dtype=np.float32`` for
maximum efficiency.
Returns
-------
X_transformed : sparse matrix, shape=(n_samples, n_out)
Transformed dataset.
"""
X = check_array(X, accept_sparse=['csc'])
if issparse(X):
# Pre-sort indices to avoid that each individual tree of the
# ensemble sorts the indices.
X.sort_indices()
rnd = check_random_state(self.random_state)
y = rnd.uniform(size=X.shape[0])
super(RandomTreesEmbedding, self).fit(X, y,
sample_weight=sample_weight)
self.one_hot_encoder_ = OneHotEncoder(sparse=self.sparse_output)
return self.one_hot_encoder_.fit_transform(self.apply(X))
def transform(self, X):
"""Transform dataset.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
Input data to be transformed. Use ``dtype=np.float32`` for maximum
efficiency. Sparse matrices are also supported, use sparse
``csr_matrix`` for maximum efficiency.
Returns
-------
X_transformed : sparse matrix, shape=(n_samples, n_out)
Transformed dataset.
"""
return self.one_hot_encoder_.transform(self.apply(X))
| bsd-3-clause |
brian-yang/mozillians | vendor-local/lib/python/rest_framework/settings.py | 3 | 6369 | """
Settings for REST framework are all namespaced in the REST_FRAMEWORK setting.
For example your project's `settings.py` file might look like this:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.YAMLRenderer',
)
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.YAMLParser',
)
}
This module provides the `api_setting` object, that is used to access
REST framework settings, checking for user settings first, then falling
back to the defaults.
"""
from __future__ import unicode_literals
from django.conf import settings
from django.utils import six
from rest_framework import ISO_8601
from rest_framework.compat import importlib
USER_SETTINGS = getattr(settings, 'REST_FRAMEWORK', None)
DEFAULTS = {
# Base API policies
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_THROTTLE_CLASSES': (),
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'rest_framework.negotiation.DefaultContentNegotiation',
# Genric view behavior
'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.ModelSerializer',
'DEFAULT_PAGINATION_SERIALIZER_CLASS': 'rest_framework.pagination.PaginationSerializer',
'DEFAULT_FILTER_BACKENDS': (),
# Throttling
'DEFAULT_THROTTLE_RATES': {
'user': None,
'anon': None,
},
'NUM_PROXIES': None,
# Pagination
'PAGINATE_BY': None,
'PAGINATE_BY_PARAM': None,
'MAX_PAGINATE_BY': None,
# Filtering
'SEARCH_PARAM': 'search',
'ORDERING_PARAM': 'ordering',
# Authentication
'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser',
'UNAUTHENTICATED_TOKEN': None,
# View configuration
'VIEW_NAME_FUNCTION': 'rest_framework.views.get_view_name',
'VIEW_DESCRIPTION_FUNCTION': 'rest_framework.views.get_view_description',
# Exception handling
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler',
# Testing
'TEST_REQUEST_RENDERER_CLASSES': (
'rest_framework.renderers.MultiPartRenderer',
'rest_framework.renderers.JSONRenderer'
),
'TEST_REQUEST_DEFAULT_FORMAT': 'multipart',
# Browser enhancements
'FORM_METHOD_OVERRIDE': '_method',
'FORM_CONTENT_OVERRIDE': '_content',
'FORM_CONTENTTYPE_OVERRIDE': '_content_type',
'URL_ACCEPT_OVERRIDE': 'accept',
'URL_FORMAT_OVERRIDE': 'format',
'FORMAT_SUFFIX_KWARG': 'format',
'URL_FIELD_NAME': 'url',
# Input and output formats
'DATE_INPUT_FORMATS': (
ISO_8601,
),
'DATE_FORMAT': None,
'DATETIME_INPUT_FORMATS': (
ISO_8601,
),
'DATETIME_FORMAT': None,
'TIME_INPUT_FORMATS': (
ISO_8601,
),
'TIME_FORMAT': None,
# Pending deprecation
'FILTER_BACKEND': None,
}
# List of settings that may be in string import notation.
IMPORT_STRINGS = (
'DEFAULT_RENDERER_CLASSES',
'DEFAULT_PARSER_CLASSES',
'DEFAULT_AUTHENTICATION_CLASSES',
'DEFAULT_PERMISSION_CLASSES',
'DEFAULT_THROTTLE_CLASSES',
'DEFAULT_CONTENT_NEGOTIATION_CLASS',
'DEFAULT_MODEL_SERIALIZER_CLASS',
'DEFAULT_PAGINATION_SERIALIZER_CLASS',
'DEFAULT_FILTER_BACKENDS',
'EXCEPTION_HANDLER',
'FILTER_BACKEND',
'TEST_REQUEST_RENDERER_CLASSES',
'UNAUTHENTICATED_USER',
'UNAUTHENTICATED_TOKEN',
'VIEW_NAME_FUNCTION',
'VIEW_DESCRIPTION_FUNCTION'
)
def perform_import(val, setting_name):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if isinstance(val, six.string_types):
return import_from_string(val, setting_name)
elif isinstance(val, (list, tuple)):
return [import_from_string(item, setting_name) for item in val]
return val
def import_from_string(val, setting_name):
"""
Attempt to import a class from a string representation.
"""
try:
# Nod to tastypie's use of importlib.
parts = val.split('.')
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
module = importlib.import_module(module_path)
return getattr(module, class_name)
except ImportError as e:
msg = "Could not import '%s' for API setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e)
raise ImportError(msg)
class APISettings(object):
"""
A settings object, that allows API settings to be accessed as properties.
For example:
from rest_framework.settings import api_settings
print api_settings.DEFAULT_RENDERER_CLASSES
Any setting with string import paths will be automatically resolved
and return the class, rather than the string literal.
"""
def __init__(self, user_settings=None, defaults=None, import_strings=None):
self.user_settings = user_settings or {}
self.defaults = defaults or {}
self.import_strings = import_strings or ()
def __getattr__(self, attr):
if attr not in self.defaults.keys():
raise AttributeError("Invalid API setting: '%s'" % attr)
try:
# Check if present in user settings
val = self.user_settings[attr]
except KeyError:
# Fall back to defaults
val = self.defaults[attr]
# Coerce import strings into classes
if val and attr in self.import_strings:
val = perform_import(val, attr)
self.validate_setting(attr, val)
# Cache the result
setattr(self, attr, val)
return val
def validate_setting(self, attr, val):
if attr == 'FILTER_BACKEND' and val is not None:
# Make sure we can initialize the class
val()
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
| bsd-3-clause |
karlgrz/karlgrz.com-plugins | github_activity/github_activity.py | 4 | 1827 | # -*- coding: utf-8 -*-
# NEEDS WORK
"""
Copyright (c) Marco Milanesi <kpanic@gnufunk.org>
Github Activity
---------------
A plugin to list your Github Activity
"""
from __future__ import unicode_literals, print_function
import logging
logger = logging.getLogger(__name__)
from pelican import signals
class GitHubActivity():
"""
A class created to fetch github activity with feedparser
"""
def __init__(self, generator):
import feedparser
self.activities = feedparser.parse(
generator.settings['GITHUB_ACTIVITY_FEED'])
def fetch(self):
"""
returns a list of html snippets fetched from github actitivy feed
"""
entries = []
for activity in self.activities['entries']:
entries.append(
[element for element in [activity['title'],
activity['content'][0]['value']]])
return entries
def fetch_github_activity(gen, metadata):
"""
registered handler for the github activity plugin
it puts in generator.context the html needed to be displayed on a
template
"""
if 'GITHUB_ACTIVITY_FEED' in gen.settings.keys():
gen.context['github_activity'] = gen.plugin_instance.fetch()
def feed_parser_initialization(generator):
"""
Initialization of feed parser
"""
generator.plugin_instance = GitHubActivity(generator)
def register():
"""
Plugin registration
"""
try:
signals.article_generator_init.connect(feed_parser_initialization)
signals.article_generator_context.connect(fetch_github_activity)
except ImportError:
logger.warning('`github_activity` failed to load dependency `feedparser`.'
'`github_activity` plugin not loaded.')
| agpl-3.0 |
k-nut/AMPds | the_cloud/web/obvius.log.reading.py | 2 | 2475 | # Copyright (C) 2012 Stephen Makonin. All Right Reserved.
import sys, os, cgi, gzip, traceback
from lib_config_msh import *
from lib_obvius import *
filepath = ""
# exit with unauthorized error
def unauth():
print "Status: 401 Access Denied"
print
sys.exit(0)
# exit with fail
def fail(reason):
print "Status: 406 Not Acceptable"
print "Content-type: text/plain"
print
print "FAILURE: %s" % (reason)
print "NOTES: Rejected logfile upload"
sys.exit(0)
# exit with success
def success():
print "Status: 200 OK"
print "Content-type: text/plain"
print
print "SUCCESS"
sys.exit(0)
# custom exception handler
_old_excepthook = sys.excepthook
def return_except(exctype, excval, exctb):
global filepath
if filepath != "":
os.remove(filepath)
fail("%s (line %d)" % (traceback.format_exception_only(exctype, excval), exctb.tb_lineno))
sys.excepthook = return_except
# load cgi form
form = cgi.FieldStorage()
# authenticate the data collector
home = auth_collector(con, form.getvalue('SERIALNUMBER'), form.getvalue('PASSWORD'))
if home == "":
unauth()
# do a mode value check
if form.getvalue('MODE') == 'LOGFILEUPLOAD':
# do nothing, we want this to happen
happy = "joy"
elif form.getvalue('MODE') == 'STATUS':
success()
elif form.getvalue('MODE') == 'TEST':
success()
elif form.getvalue('MODE') == 'CONFIGFILEMANIFEST':
success()
elif form.getvalue('MODE') == 'CONFIGFILEDOWNLOAD':
success()
elif form.getvalue('MODE') == 'CONFIGFILEUPLOAD':
success()
else:
fail("Mode Type %s not supported." % (form.getvalue('MODE')))
# save file, rund checksum, uncompress
fileitem = form['LOGFILE']
filename = os.path.basename(fileitem.filename)
filepath = "/tmp/obvius/%s" % (filename)
open(filepath, 'wb').write(fileitem.file.read())
checksum = gen_checksum(filepath)
if form.getvalue('MD5CHECKSUM') != checksum:
fail("Checksum mismatch remote[%s] = local[%s]" % (form.getvalue('MD5CHECKSUM'), checksum))
f = gzip.open(filepath, 'rb')
blob = f.read()
f.close()
open(filepath, 'w').write(blob)
# process the file and save in database
if read_csv_file(con, home, int(form.getvalue('MODBUSDEVICECLASS')), int(form.getvalue('MODBUSDEVICE')), filepath) == 0:
fail("Device Class %d not supported." % (int(form.getvalue('MODBUSDEVICECLASS'))))
# clean up and exit
os.remove(filepath)
#os.rename(filepath, "/tmp/obvius/done/%s" % (filename))
close_con()
success()
| mit |
cs564/heron | integration-test/src/python/integration_test/topology/global_grouping/global_grouping.py | 8 | 1102 | # copyright 2016 twitter. 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.
# pylint: disable=missing-docstring
from heron.pyheron.src.python import Grouping
from ...core import TestTopologyBuilder
from ...common.bolt import WordCountBolt
from ...common.spout import ABSpout
def global_grouping_builder(topology_name, http_server_url):
builder = TestTopologyBuilder(topology_name, http_server_url)
ab_spout = builder.add_spout("ab-spout", ABSpout, 1)
builder.add_bolt("count-bolt", WordCountBolt, inputs={ab_spout: Grouping.GLOBAL}, par=3)
return builder.create_topology()
| apache-2.0 |
Peddle/hue | desktop/core/ext-py/python-ldap-2.3.13/Lib/ldapurl.py | 44 | 11503 | """
ldapurl - handling of LDAP URLs as described in RFC 4516
See http://www.python-ldap.org/ for details.
\$Id: ldapurl.py,v 1.45 2010/05/07 08:15:47 stroeder Exp $
Python compability note:
This module only works with Python 2.0+ since
1. string methods are used instead of module string and
2. list comprehensions are used.
"""
__version__ = '2.3.12'
__all__ = [
# constants
'SEARCH_SCOPE','SEARCH_SCOPE_STR',
'LDAP_SCOPE_BASE','LDAP_SCOPE_ONELEVEL','LDAP_SCOPE_SUBTREE',
# functions
'isLDAPUrl',
# classes
'LDAPUrlExtension','LDAPUrlExtensions','LDAPUrl'
]
import UserDict
from urllib import quote,unquote
LDAP_SCOPE_BASE = 0
LDAP_SCOPE_ONELEVEL = 1
LDAP_SCOPE_SUBTREE = 2
SEARCH_SCOPE_STR = {None:'',0:'base',1:'one',2:'sub'}
SEARCH_SCOPE = {
'':None,
# the search scope strings defined in RFC2255
'base':LDAP_SCOPE_BASE,
'one':LDAP_SCOPE_ONELEVEL,
'sub':LDAP_SCOPE_SUBTREE,
}
# Some widely used types
StringType = type('')
TupleType=type(())
def isLDAPUrl(s):
"""
Returns 1 if s is a LDAP URL, 0 else
"""
s_lower = s.lower()
return \
s_lower.startswith('ldap://') or \
s_lower.startswith('ldaps://') or \
s_lower.startswith('ldapi://')
def ldapUrlEscape(s):
"""Returns URL encoding of string s"""
return quote(s).replace(',','%2C').replace('/','%2F')
class LDAPUrlExtension:
"""
Class for parsing and unparsing LDAP URL extensions
as described in RFC 4516.
Usable class attributes:
critical
Boolean integer marking the extension as critical
extype
Type of extension
exvalue
Value of extension
"""
def __init__(self,extensionStr=None,critical=0,extype=None,exvalue=None):
self.critical = critical
self.extype = extype
self.exvalue = exvalue
if extensionStr:
self._parse(extensionStr)
def _parse(self,extension):
extension = extension.strip()
if not extension:
# Don't parse empty strings
self.extype,self.exvalue = None,None
return
self.critical = extension[0]=='!'
if extension[0]=='!':
extension = extension[1:].strip()
try:
self.extype,self.exvalue = extension.split('=',1)
except ValueError:
# No value, just the extype
self.extype,self.exvalue = extension,None
else:
self.exvalue = unquote(self.exvalue.strip())
self.extype = self.extype.strip()
def unparse(self):
if self.exvalue is None:
return '%s%s' % ('!'*(self.critical>0),self.extype)
else:
return '%s%s=%s' % (
'!'*(self.critical>0),
self.extype,quote(self.exvalue or '')
)
def __str__(self):
return self.unparse()
def __repr__(self):
return '<%s.%s instance at %s: %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self)),
self.__dict__
)
def __eq__(self,other):
return \
(self.critical==other.critical) and \
(self.extype==other.extype) and \
(self.exvalue==other.exvalue)
def __ne__(self,other):
return not self.__eq__(other)
class LDAPUrlExtensions(UserDict.UserDict):
"""
Models a collection of LDAP URL extensions as
dictionary type
"""
def __init__(self,default=None):
UserDict.UserDict.__init__(self)
for k,v in (default or {}).items():
self[k]=v
def __setitem__(self,name,value):
"""
value
Either LDAPUrlExtension instance, (critical,exvalue)
or string'ed exvalue
"""
assert isinstance(value,LDAPUrlExtension)
assert name==value.extype
self.data[name] = value
def values(self):
return [
self[k]
for k in self.keys()
]
def __str__(self):
return ','.join(map(str,self.values()))
def __repr__(self):
return '<%s.%s instance at %s: %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self)),
self.data
)
def __eq__(self,other):
assert isinstance(other,self.__class__),TypeError(
"other has to be instance of %s" % (self.__class__)
)
return self.data==other.data
def parse(self,extListStr):
for extension_str in extListStr.strip().split(','):
if extension_str:
e = LDAPUrlExtension(extension_str)
self[e.extype] = e
def unparse(self):
return ','.join([ v.unparse() for v in self.values() ])
class LDAPUrl:
"""
Class for parsing and unparsing LDAP URLs
as described in RFC 4516.
Usable class attributes:
urlscheme
URL scheme (either ldap, ldaps or ldapi)
hostport
LDAP host (default '')
dn
String holding distinguished name (default '')
attrs
list of attribute types (default None)
scope
integer search scope for ldap-module
filterstr
String representation of LDAP Search Filters
(see RFC 2254)
extensions
Dictionary used as extensions store
who
Maps automagically to bindname LDAP URL extension
cred
Maps automagically to X-BINDPW LDAP URL extension
"""
attr2extype = {'who':'bindname','cred':'X-BINDPW'}
def __init__(
self,
ldapUrl=None,
urlscheme='ldap',
hostport='',dn='',attrs=None,scope=None,filterstr=None,
extensions=None,
who=None,cred=None
):
self.urlscheme=urlscheme
self.hostport=hostport
self.dn=dn
self.attrs=attrs
self.scope=scope
self.filterstr=filterstr
self.extensions=(extensions or LDAPUrlExtensions({}))
if ldapUrl!=None:
self._parse(ldapUrl)
if who!=None:
self.who = who
if cred!=None:
self.cred = cred
def __eq__(self,other):
return \
self.urlscheme==other.urlscheme and \
self.hostport==other.hostport and \
self.dn==other.dn and \
self.attrs==other.attrs and \
self.scope==other.scope and \
self.filterstr==other.filterstr and \
self.extensions==other.extensions
def __ne__(self,other):
return not self.__eq__(other)
def _parse(self,ldap_url):
"""
parse a LDAP URL and set the class attributes
urlscheme,host,dn,attrs,scope,filterstr,extensions
"""
if not isLDAPUrl(ldap_url):
raise ValueError,'Parameter ldap_url does not seem to be a LDAP URL.'
scheme,rest = ldap_url.split('://',1)
self.urlscheme = scheme.strip()
if not self.urlscheme in ['ldap','ldaps','ldapi']:
raise ValueError,'LDAP URL contains unsupported URL scheme %s.' % (self.urlscheme)
slash_pos = rest.find('/')
qemark_pos = rest.find('?')
if (slash_pos==-1) and (qemark_pos==-1):
# No / and ? found at all
self.hostport = unquote(rest)
self.dn = ''
return
else:
if slash_pos!=-1 and (qemark_pos==-1 or (slash_pos<qemark_pos)):
# Slash separates DN from hostport
self.hostport = unquote(rest[:slash_pos])
# Eat the slash from rest
rest = rest[slash_pos+1:]
elif qemark_pos!=1 and (slash_pos==-1 or (slash_pos>qemark_pos)):
# Question mark separates hostport from rest, DN is assumed to be empty
self.hostport = unquote(rest[:qemark_pos])
# Do not eat question mark
rest = rest[qemark_pos:]
else:
raise ValueError,'Something completely weird happened!'
paramlist=rest.split('?',4)
paramlist_len = len(paramlist)
if paramlist_len>=1:
self.dn = unquote(paramlist[0]).strip()
if (paramlist_len>=2) and (paramlist[1]):
self.attrs = unquote(paramlist[1].strip()).split(',')
if paramlist_len>=3:
scope = paramlist[2].strip()
try:
self.scope = SEARCH_SCOPE[scope]
except KeyError:
raise ValueError,"Search scope must be either one of base, one or sub. LDAP URL contained %s" % (repr(scope))
if paramlist_len>=4:
filterstr = paramlist[3].strip()
if not filterstr:
self.filterstr = None
else:
self.filterstr = unquote(filterstr)
if paramlist_len>=5:
if paramlist[4]:
self.extensions = LDAPUrlExtensions()
self.extensions.parse(paramlist[4])
else:
self.extensions = None
return
def applyDefaults(self,defaults):
"""
Apply defaults to all class attributes which are None.
defaults
Dictionary containing a mapping from class attributes
to default values
"""
for k in defaults.keys():
if getattr(self,k) is None:
setattr(self,k,defaults[k])
def initializeUrl(self):
"""
Returns LDAP URL suitable to be passed to ldap.initialize()
"""
if self.urlscheme=='ldapi':
# hostport part might contain slashes when ldapi:// is used
hostport = ldapUrlEscape(self.hostport)
else:
hostport = self.hostport
return '%s://%s' % (self.urlscheme,hostport)
def unparse(self):
"""
Returns LDAP URL depending on class attributes set.
"""
if self.attrs is None:
attrs_str = ''
else:
attrs_str = ','.join(self.attrs)
scope_str = SEARCH_SCOPE_STR[self.scope]
if self.filterstr is None:
filterstr = ''
else:
filterstr = ldapUrlEscape(self.filterstr)
dn = ldapUrlEscape(self.dn)
if self.urlscheme=='ldapi':
# hostport part might contain slashes when ldapi:// is used
hostport = ldapUrlEscape(self.hostport)
else:
hostport = self.hostport
ldap_url = '%s://%s/%s?%s?%s?%s' % (
self.urlscheme,
hostport,dn,attrs_str,scope_str,filterstr
)
if self.extensions:
ldap_url = ldap_url+'?'+self.extensions.unparse()
return ldap_url
def htmlHREF(self,urlPrefix='',hrefText=None,hrefTarget=None):
"""Complete """
assert type(urlPrefix)==StringType, "urlPrefix must be StringType"
if hrefText is None:
hrefText = self.unparse()
assert type(hrefText)==StringType, "hrefText must be StringType"
if hrefTarget is None:
target = ''
else:
assert type(hrefTarget)==StringType, "hrefTarget must be StringType"
target = ' target="%s"' % hrefTarget
return '<a%s href="%s%s">%s</a>' % (
target,urlPrefix,self.unparse(),hrefText
)
def __str__(self):
return self.unparse()
def __repr__(self):
return '<%s.%s instance at %s: %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self)),
self.__dict__
)
def __getattr__(self,name):
if self.attr2extype.has_key(name):
extype = self.attr2extype[name]
if self.extensions and \
self.extensions.has_key(extype) and \
not self.extensions[extype].exvalue is None:
result = unquote(self.extensions[extype].exvalue)
else:
return None
else:
raise AttributeError,"%s has no attribute %s" % (
self.__class__.__name__,name
)
return result # __getattr__()
def __setattr__(self,name,value):
if self.attr2extype.has_key(name):
extype = self.attr2extype[name]
if value is None:
# A value of None means that extension is deleted
delattr(self,name)
elif value!=None:
# Add appropriate extension
self.extensions[extype] = LDAPUrlExtension(
extype=extype,exvalue=unquote(value)
)
else:
self.__dict__[name] = value
def __delattr__(self,name):
if self.attr2extype.has_key(name):
extype = self.attr2extype[name]
if self.extensions:
try:
del self.extensions[extype]
except KeyError:
pass
else:
del self.__dict__[name]
| apache-2.0 |
dslomov/intellij-community | plugins/hg4idea/testData/bin/hgext/graphlog.py | 93 | 2081 | # ASCII graph log extension for Mercurial
#
# Copyright 2007 Joel Rosdahl <joel@rosdahl.net>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''command to view revision graphs from a shell
This extension adds a --graph option to the incoming, outgoing and log
commands. When this options is given, an ASCII representation of the
revision graph is also shown.
'''
from mercurial.i18n import _
from mercurial import cmdutil, commands
cmdtable = {}
command = cmdutil.command(cmdtable)
testedwith = 'internal'
@command('glog',
[('f', 'follow', None,
_('follow changeset history, or file history across copies and renames')),
('', 'follow-first', None,
_('only follow the first parent of merge changesets (DEPRECATED)')),
('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
('C', 'copies', None, _('show copied files')),
('k', 'keyword', [],
_('do case-insensitive search for a given text'), _('TEXT')),
('r', 'rev', [], _('show the specified revision or range'), _('REV')),
('', 'removed', None, _('include revisions where files were removed')),
('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
('u', 'user', [], _('revisions committed by user'), _('USER')),
('', 'only-branch', [],
_('show only changesets within the given named branch (DEPRECATED)'),
_('BRANCH')),
('b', 'branch', [],
_('show changesets within the given named branch'), _('BRANCH')),
('P', 'prune', [],
_('do not display revision or any of its ancestors'), _('REV')),
] + commands.logopts + commands.walkopts,
_('[OPTION]... [FILE]'))
def graphlog(ui, repo, *pats, **opts):
"""show revision history alongside an ASCII revision graph
Print a revision history alongside a revision graph drawn with
ASCII characters.
Nodes printed as an @ character are parents of the working
directory.
"""
return cmdutil.graphlog(ui, repo, *pats, **opts)
commands.inferrepo += " glog"
| apache-2.0 |
jsakamoto/selenium | py/test/selenium/webdriver/common/window_tests.py | 7 | 6445 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import pytest
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.support.wait import WebDriverWait
@pytest.mark.xfail_ie
@pytest.mark.xfail_chrome(reason="Fails on Travis")
@pytest.mark.xfail_marionette(reason="Fails on Travis")
@pytest.mark.xfail_firefox(reason="Fails on Travis")
@pytest.mark.xfail_remote(reason="Fails on Travis")
def testShouldMaximizeTheWindow(driver):
resize_timeout = 5
wait = WebDriverWait(driver, resize_timeout)
old_size = driver.get_window_size()
driver.set_window_size(200, 200)
wait.until(
lambda dr: dr.get_window_size() != old_size if old_size["width"] != 200 and old_size["height"] != 200 else True)
size = driver.get_window_size()
driver.maximize_window()
wait.until(lambda dr: dr.get_window_size() != size)
new_size = driver.get_window_size()
assert new_size["width"] > size["width"]
assert new_size["height"] > size["height"]
def test_should_get_the_size_of_the_current_window(driver):
size = driver.get_window_size()
assert size.get('width') > 0
assert size.get('height') > 0
def test_should_set_the_size_of_the_current_window(driver):
size = driver.get_window_size()
target_width = size.get('width') - 20
target_height = size.get('height') - 20
driver.set_window_size(width=target_width, height=target_height)
new_size = driver.get_window_size()
assert new_size.get('width') == target_width
assert new_size.get('height') == target_height
def test_should_get_the_position_of_the_current_window(driver):
position = driver.get_window_position()
assert position.get('x') >= 0
assert position.get('y') >= 0
def test_should_set_the_position_of_the_current_window(driver):
position = driver.get_window_position()
target_x = position.get('x') + 10
target_y = position.get('y') + 10
driver.set_window_position(x=target_x, y=target_y)
WebDriverWait(driver, 2).until(lambda d: d.get_window_position()['x'] != position['x'] and
d.get_window_position()['y'] != position['y'])
new_position = driver.get_window_position()
assert new_position.get('x') == target_x
assert new_position.get('y') == target_y
@pytest.mark.xfail_firefox(raises=WebDriverException,
reason='Get Window Rect command not implemented')
@pytest.mark.xfail_safari(raises=WebDriverException,
reason='Get Window Rect command not implemented')
def test_should_get_the_rect_of_the_current_window(driver):
rect = driver.get_window_rect()
assert rect.get('x') >= 0
assert rect.get('y') >= 0
assert rect.get('width') >= 0
assert rect.get('height') >= 0
@pytest.mark.xfail_firefox(raises=WebDriverException,
reason='Get Window Rect command not implemented')
@pytest.mark.xfail_safari(raises=WebDriverException,
reason='Get Window Rect command not implemented')
def test_should_set_the_rect_of_the_current_window(driver):
rect = driver.get_window_rect()
target_x = rect.get('x') + 10
target_y = rect.get('y') + 10
target_width = rect.get('width') + 10
target_height = rect.get('height') + 10
driver.set_window_rect(x=target_x, y=target_y, width=target_width, height=target_height)
WebDriverWait(driver, 2).until(lambda d: d.get_window_position()['x'] != rect['x'] and
d.get_window_position()['y'] != rect['y'])
new_rect = driver.get_window_rect()
assert new_rect.get('x') == target_x
assert new_rect.get('y') == target_y
assert new_rect.get('width') == target_width
assert new_rect.get('height') == target_height
@pytest.mark.xfail_chrome(raises=WebDriverException,
reason='Fullscreen command not implemented')
@pytest.mark.xfail_firefox(raises=WebDriverException,
reason='Fullscreen command not implemented')
@pytest.mark.xfail_safari(raises=WebDriverException,
reason='Fullscreen command not implemented')
@pytest.mark.skipif(os.environ.get('CI') == 'true',
reason='Fullscreen command causes Travis to hang')
def test_should_fullscreen_the_current_window(driver):
start_width = driver.execute_script('return window.innerWidth;')
start_height = driver.execute_script('return window.innerHeight;')
driver.fullscreen_window()
WebDriverWait(driver, 2).until(lambda d: driver.execute_script('return window.innerWidth;') >
start_width)
end_width = driver.execute_script('return window.innerWidth;')
end_height = driver.execute_script('return window.innerHeight;')
driver.fullscreen_window() # Restore to original size
assert end_width > start_width
assert end_height > start_height
@pytest.mark.xfail_chrome(raises=WebDriverException,
reason='Minimize command not implemented')
@pytest.mark.xfail_firefox(raises=WebDriverException,
reason='Minimize command not implemented')
@pytest.mark.xfail_safari(raises=WebDriverException,
reason='Minimize command not implemented')
@pytest.mark.skipif(os.environ.get('CI') == 'true',
reason='Minimize command causes Travis to hang')
@pytest.mark.no_driver_after_test
def test_should_minimize_the_current_window(driver):
driver.minimize_window()
minimized = driver.execute_script('return document.hidden;')
driver.quit() # Kill driver so we aren't running minimized after
assert minimized is True
| apache-2.0 |
uzgit/ardupilot | mk/VRBRAIN/Tools/genmsg/doc/conf.py | 51 | 8929 | # -*- coding: utf-8 -*-
#
# genmsg documentation build configuration file, created by
# sphinx-quickstart on Wed Dec 14 07:48:35 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import catkin_sphinx
sys.path.insert(0, '../src')
from xml.etree.ElementTree import ElementTree
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
html_logo = 'ros.png'
html_theme_path = [os.path.join(os.path.dirname(catkin_sphinx.__file__),
'theme')]
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.viewcode', 'catkin_sphinx.cmake']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'genmsg'
copyright = u'2011, Willow Garage'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
try:
root = ElementTree(None, os.path.join('..', 'package.xml'))
version = root.findtext('version')
except Exception as e:
raise RuntimeError('Could not extract version from package.xml:\n%s' % e)
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'ros-theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'genmsgdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'genmsg.tex', u'genmsg Documentation',
u'Willow Garage', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'genmsg', u'genmsg Documentation',
[u'Willow Garage'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'genmsg', u'genmsg Documentation',
u'Willow Garage', 'genmsg', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'genmsg': ('http://ros.org/doc/api/genmsg/html', None),
'vcstools': ('http://ros.org/doc/api/vcstools/html', None),
'rosinstall': ('http://ros.org/doc/api/rosinstall/html', None),
'rospkg': ('http://ros.org/doc/api/rosinstall/html', None),
'rosdep2': ('http://ros.org/doc/api/rosdep2/html', None),
}
| gpl-3.0 |
ryanjmccall/nupic | tests/swarming/nupic/swarming/experiments/simple_cla_multistep/permutations.py | 4 | 5228 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# 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.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
Template file used by ExpGenerator to generate the actual
permutations.py file by replacing $XXXXXXXX tokens with desired values.
This permutations.py file was generated by:
'/Users/ronmarianetti/nupic/eng/lib/python2.6/site-packages/nupicengine/frameworks/opf/expGenerator/ExpGenerator.pyc'
"""
import os
from nupic.swarming.permutationhelpers import *
# The name of the field being predicted. Any allowed permutation MUST contain
# the prediction field.
# (generated from PREDICTION_FIELD)
predictedField = 'consumption'
permutations = {
'aggregationInfo': { 'days': 0,
'fields': [ (u'timestamp', 'first'),
(u'gym', 'first'),
(u'consumption', 'sum')],
'hours': 1,
'microseconds': 0,
'milliseconds': 0,
'minutes': 0,
'months': 0,
'seconds': 0,
'weeks': 0,
'years': 0},
'modelParams': {
'inferenceType': PermuteChoices(['NontemporalMultiStep', 'TemporalMultiStep']),
'sensorParams': {
'encoders': {
u'timestamp_timeOfDay': PermuteEncoder(
fieldName='timestamp',
encoderClass='DateEncoder.timeOfDay',
w=21,
radius=PermuteFloat(0.5, 12)),
u'timestamp_dayOfWeek': PermuteEncoder(
fieldName='timestamp',
encoderClass='DateEncoder.dayOfWeek',
w=21,
radius=PermuteFloat(1, 6)),
u'timestamp_weekend': PermuteEncoder(
fieldName='timestamp',
encoderClass='DateEncoder.weekend',
w=21,
radius=PermuteChoices([1])),
u'consumption': PermuteEncoder(
fieldName='consumption',
encoderClass='AdaptiveScalarEncoder',
w=21,
n=PermuteInt(28, 521),
clipInput=True),
u'_classifierInput': dict(
fieldname='consumption',
classifierOnly=True,
type='AdaptiveScalarEncoder',
w=21,
n=PermuteInt(28, 521),
clipInput=True),
},
},
'spParams': {
'synPermInactiveDec': PermuteFloat(0.005, 0.1),
},
'tpParams': {
'activationThreshold': PermuteInt(12, 16),
'minThreshold': PermuteInt(9, 12),
'pamLength': PermuteInt(1, 5),
},
'clParams': {
'alpha': PermuteFloat(0.0001, 0.1),
},
}
}
# Fields selected for final hypersearch report;
# NOTE: These values are used as regular expressions by RunPermutations.py's
# report generator
# (fieldname values generated from PERM_PREDICTED_FIELD_NAME)
report = [
'.*consumption.*',
]
# Permutation optimization setting: either minimize or maximize metric
# used by RunPermutations.
# NOTE: The value is used as a regular expressions by RunPermutations.py's
# report generator
# (generated from minimize = "multiStepBestPredictions:multiStep:errorMetric='altMAPE':steps=\[1\]:window=1000:field=consumption")
minimize = "multiStepBestPredictions:multiStep:errorMetric='altMAPE':steps=\[1\]:window=1000:field=consumption"
minParticlesPerSwarm = None
#############################################################################
def permutationFilter(perm):
""" This function can be used to selectively filter out specific permutation
combinations. It is called by RunPermutations for every possible permutation
of the variables in the permutations dict. It should return True for valid a
combination of permutation values and False for an invalid one.
Parameters:
---------------------------------------------------------
perm: dict of one possible combination of name:value
pairs chosen from permutations.
"""
# An example of how to use this
#if perm['__consumption_encoder']['maxval'] > 300:
# return False;
#
return True
| gpl-3.0 |
albertjan/pypyjs-presentation | assets/js/pypy.js-0.3.1/lib/modules/test/test_py_compile.py | 105 | 1744 | import imp
import os
import py_compile
import shutil
import tempfile
import unittest
from test import test_support
class PyCompileTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.mkdtemp()
self.source_path = os.path.join(self.directory, '_test.py')
self.pyc_path = self.source_path + 'c'
self.cwd_drive = os.path.splitdrive(os.getcwd())[0]
# In these tests we compute relative paths. When using Windows, the
# current working directory path and the 'self.source_path' might be
# on different drives. Therefore we need to switch to the drive where
# the temporary source file lives.
drive = os.path.splitdrive(self.source_path)[0]
if drive:
os.chdir(drive)
with open(self.source_path, 'w') as file:
file.write('x = 123\n')
def tearDown(self):
shutil.rmtree(self.directory)
if self.cwd_drive:
os.chdir(self.cwd_drive)
def test_absolute_path(self):
py_compile.compile(self.source_path, self.pyc_path)
self.assertTrue(os.path.exists(self.pyc_path))
def test_cwd(self):
cwd = os.getcwd()
os.chdir(self.directory)
py_compile.compile(os.path.basename(self.source_path),
os.path.basename(self.pyc_path))
os.chdir(cwd)
self.assertTrue(os.path.exists(self.pyc_path))
def test_relative_path(self):
py_compile.compile(os.path.relpath(self.source_path),
os.path.relpath(self.pyc_path))
self.assertTrue(os.path.exists(self.pyc_path))
def test_main():
test_support.run_unittest(PyCompileTests)
if __name__ == "__main__":
test_main()
| unlicense |
dslomov/bazel-windows | third_party/py/gflags/gflags2man.py | 407 | 18864 | #!/usr/bin/env python
# Copyright (c) 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""gflags2man runs a Google flags base program and generates a man page.
Run the program, parse the output, and then format that into a man
page.
Usage:
gflags2man <program> [program] ...
"""
# TODO(csilvers): work with windows paths (\) as well as unix (/)
# This may seem a bit of an end run, but it: doesn't bloat flags, can
# support python/java/C++, supports older executables, and can be
# extended to other document formats.
# Inspired by help2man.
import os
import re
import sys
import stat
import time
import gflags
_VERSION = '0.1'
def _GetDefaultDestDir():
home = os.environ.get('HOME', '')
homeman = os.path.join(home, 'man', 'man1')
if home and os.path.exists(homeman):
return homeman
else:
return os.environ.get('TMPDIR', '/tmp')
FLAGS = gflags.FLAGS
gflags.DEFINE_string('dest_dir', _GetDefaultDestDir(),
'Directory to write resulting manpage to.'
' Specify \'-\' for stdout')
gflags.DEFINE_string('help_flag', '--help',
'Option to pass to target program in to get help')
gflags.DEFINE_integer('v', 0, 'verbosity level to use for output')
_MIN_VALID_USAGE_MSG = 9 # if fewer lines than this, help is suspect
class Logging:
"""A super-simple logging class"""
def error(self, msg): print >>sys.stderr, "ERROR: ", msg
def warn(self, msg): print >>sys.stderr, "WARNING: ", msg
def info(self, msg): print msg
def debug(self, msg): self.vlog(1, msg)
def vlog(self, level, msg):
if FLAGS.v >= level: print msg
logging = Logging()
class App:
def usage(self, shorthelp=0):
print >>sys.stderr, __doc__
print >>sys.stderr, "flags:"
print >>sys.stderr, str(FLAGS)
def run(self):
main(sys.argv)
app = App()
def GetRealPath(filename):
"""Given an executable filename, find in the PATH or find absolute path.
Args:
filename An executable filename (string)
Returns:
Absolute version of filename.
None if filename could not be found locally, absolutely, or in PATH
"""
if os.path.isabs(filename): # already absolute
return filename
if filename.startswith('./') or filename.startswith('../'): # relative
return os.path.abspath(filename)
path = os.getenv('PATH', '')
for directory in path.split(':'):
tryname = os.path.join(directory, filename)
if os.path.exists(tryname):
if not os.path.isabs(directory): # relative directory
return os.path.abspath(tryname)
return tryname
if os.path.exists(filename):
return os.path.abspath(filename)
return None # could not determine
class Flag(object):
"""The information about a single flag."""
def __init__(self, flag_desc, help):
"""Create the flag object.
Args:
flag_desc The command line forms this could take. (string)
help The help text (string)
"""
self.desc = flag_desc # the command line forms
self.help = help # the help text
self.default = '' # default value
self.tips = '' # parsing/syntax tips
class ProgramInfo(object):
"""All the information gleaned from running a program with --help."""
# Match a module block start, for python scripts --help
# "goopy.logging:"
module_py_re = re.compile(r'(\S.+):$')
# match the start of a flag listing
# " -v,--verbosity: Logging verbosity"
flag_py_re = re.compile(r'\s+(-\S+):\s+(.*)$')
# " (default: '0')"
flag_default_py_re = re.compile(r'\s+\(default:\s+\'(.*)\'\)$')
# " (an integer)"
flag_tips_py_re = re.compile(r'\s+\((.*)\)$')
# Match a module block start, for c++ programs --help
# "google/base/commandlineflags":
module_c_re = re.compile(r'\s+Flags from (\S.+):$')
# match the start of a flag listing
# " -v,--verbosity: Logging verbosity"
flag_c_re = re.compile(r'\s+(-\S+)\s+(.*)$')
# Match a module block start, for java programs --help
# "com.google.common.flags"
module_java_re = re.compile(r'\s+Flags for (\S.+):$')
# match the start of a flag listing
# " -v,--verbosity: Logging verbosity"
flag_java_re = re.compile(r'\s+(-\S+)\s+(.*)$')
def __init__(self, executable):
"""Create object with executable.
Args:
executable Program to execute (string)
"""
self.long_name = executable
self.name = os.path.basename(executable) # name
# Get name without extension (PAR files)
(self.short_name, self.ext) = os.path.splitext(self.name)
self.executable = GetRealPath(executable) # name of the program
self.output = [] # output from the program. List of lines.
self.desc = [] # top level description. List of lines
self.modules = {} # { section_name(string), [ flags ] }
self.module_list = [] # list of module names in their original order
self.date = time.localtime(time.time()) # default date info
def Run(self):
"""Run it and collect output.
Returns:
1 (true) If everything went well.
0 (false) If there were problems.
"""
if not self.executable:
logging.error('Could not locate "%s"' % self.long_name)
return 0
finfo = os.stat(self.executable)
self.date = time.localtime(finfo[stat.ST_MTIME])
logging.info('Running: %s %s </dev/null 2>&1'
% (self.executable, FLAGS.help_flag))
# --help output is often routed to stderr, so we combine with stdout.
# Re-direct stdin to /dev/null to encourage programs that
# don't understand --help to exit.
(child_stdin, child_stdout_and_stderr) = os.popen4(
[self.executable, FLAGS.help_flag])
child_stdin.close() # '</dev/null'
self.output = child_stdout_and_stderr.readlines()
child_stdout_and_stderr.close()
if len(self.output) < _MIN_VALID_USAGE_MSG:
logging.error('Error: "%s %s" returned only %d lines: %s'
% (self.name, FLAGS.help_flag,
len(self.output), self.output))
return 0
return 1
def Parse(self):
"""Parse program output."""
(start_line, lang) = self.ParseDesc()
if start_line < 0:
return
if 'python' == lang:
self.ParsePythonFlags(start_line)
elif 'c' == lang:
self.ParseCFlags(start_line)
elif 'java' == lang:
self.ParseJavaFlags(start_line)
def ParseDesc(self, start_line=0):
"""Parse the initial description.
This could be Python or C++.
Returns:
(start_line, lang_type)
start_line Line to start parsing flags on (int)
lang_type Either 'python' or 'c'
(-1, '') if the flags start could not be found
"""
exec_mod_start = self.executable + ':'
after_blank = 0
start_line = 0 # ignore the passed-in arg for now (?)
for start_line in range(start_line, len(self.output)): # collect top description
line = self.output[start_line].rstrip()
# Python flags start with 'flags:\n'
if ('flags:' == line
and len(self.output) > start_line+1
and '' == self.output[start_line+1].rstrip()):
start_line += 2
logging.debug('Flags start (python): %s' % line)
return (start_line, 'python')
# SWIG flags just have the module name followed by colon.
if exec_mod_start == line:
logging.debug('Flags start (swig): %s' % line)
return (start_line, 'python')
# C++ flags begin after a blank line and with a constant string
if after_blank and line.startswith(' Flags from '):
logging.debug('Flags start (c): %s' % line)
return (start_line, 'c')
# java flags begin with a constant string
if line == 'where flags are':
logging.debug('Flags start (java): %s' % line)
start_line += 2 # skip "Standard flags:"
return (start_line, 'java')
logging.debug('Desc: %s' % line)
self.desc.append(line)
after_blank = (line == '')
else:
logging.warn('Never found the start of the flags section for "%s"!'
% self.long_name)
return (-1, '')
def ParsePythonFlags(self, start_line=0):
"""Parse python/swig style flags."""
modname = None # name of current module
modlist = []
flag = None
for line_num in range(start_line, len(self.output)): # collect flags
line = self.output[line_num].rstrip()
if not line: # blank
continue
mobj = self.module_py_re.match(line)
if mobj: # start of a new module
modname = mobj.group(1)
logging.debug('Module: %s' % line)
if flag:
modlist.append(flag)
self.module_list.append(modname)
self.modules.setdefault(modname, [])
modlist = self.modules[modname]
flag = None
continue
mobj = self.flag_py_re.match(line)
if mobj: # start of a new flag
if flag:
modlist.append(flag)
logging.debug('Flag: %s' % line)
flag = Flag(mobj.group(1), mobj.group(2))
continue
if not flag: # continuation of a flag
logging.error('Flag info, but no current flag "%s"' % line)
mobj = self.flag_default_py_re.match(line)
if mobj: # (default: '...')
flag.default = mobj.group(1)
logging.debug('Fdef: %s' % line)
continue
mobj = self.flag_tips_py_re.match(line)
if mobj: # (tips)
flag.tips = mobj.group(1)
logging.debug('Ftip: %s' % line)
continue
if flag and flag.help:
flag.help += line # multiflags tack on an extra line
else:
logging.info('Extra: %s' % line)
if flag:
modlist.append(flag)
def ParseCFlags(self, start_line=0):
"""Parse C style flags."""
modname = None # name of current module
modlist = []
flag = None
for line_num in range(start_line, len(self.output)): # collect flags
line = self.output[line_num].rstrip()
if not line: # blank lines terminate flags
if flag: # save last flag
modlist.append(flag)
flag = None
continue
mobj = self.module_c_re.match(line)
if mobj: # start of a new module
modname = mobj.group(1)
logging.debug('Module: %s' % line)
if flag:
modlist.append(flag)
self.module_list.append(modname)
self.modules.setdefault(modname, [])
modlist = self.modules[modname]
flag = None
continue
mobj = self.flag_c_re.match(line)
if mobj: # start of a new flag
if flag: # save last flag
modlist.append(flag)
logging.debug('Flag: %s' % line)
flag = Flag(mobj.group(1), mobj.group(2))
continue
# append to flag help. type and default are part of the main text
if flag:
flag.help += ' ' + line.strip()
else:
logging.info('Extra: %s' % line)
if flag:
modlist.append(flag)
def ParseJavaFlags(self, start_line=0):
"""Parse Java style flags (com.google.common.flags)."""
# The java flags prints starts with a "Standard flags" "module"
# that doesn't follow the standard module syntax.
modname = 'Standard flags' # name of current module
self.module_list.append(modname)
self.modules.setdefault(modname, [])
modlist = self.modules[modname]
flag = None
for line_num in range(start_line, len(self.output)): # collect flags
line = self.output[line_num].rstrip()
logging.vlog(2, 'Line: "%s"' % line)
if not line: # blank lines terminate module
if flag: # save last flag
modlist.append(flag)
flag = None
continue
mobj = self.module_java_re.match(line)
if mobj: # start of a new module
modname = mobj.group(1)
logging.debug('Module: %s' % line)
if flag:
modlist.append(flag)
self.module_list.append(modname)
self.modules.setdefault(modname, [])
modlist = self.modules[modname]
flag = None
continue
mobj = self.flag_java_re.match(line)
if mobj: # start of a new flag
if flag: # save last flag
modlist.append(flag)
logging.debug('Flag: %s' % line)
flag = Flag(mobj.group(1), mobj.group(2))
continue
# append to flag help. type and default are part of the main text
if flag:
flag.help += ' ' + line.strip()
else:
logging.info('Extra: %s' % line)
if flag:
modlist.append(flag)
def Filter(self):
"""Filter parsed data to create derived fields."""
if not self.desc:
self.short_desc = ''
return
for i in range(len(self.desc)): # replace full path with name
if self.desc[i].find(self.executable) >= 0:
self.desc[i] = self.desc[i].replace(self.executable, self.name)
self.short_desc = self.desc[0]
word_list = self.short_desc.split(' ')
all_names = [ self.name, self.short_name, ]
# Since the short_desc is always listed right after the name,
# trim it from the short_desc
while word_list and (word_list[0] in all_names
or word_list[0].lower() in all_names):
del word_list[0]
self.short_desc = '' # signal need to reconstruct
if not self.short_desc and word_list:
self.short_desc = ' '.join(word_list)
class GenerateDoc(object):
"""Base class to output flags information."""
def __init__(self, proginfo, directory='.'):
"""Create base object.
Args:
proginfo A ProgramInfo object
directory Directory to write output into
"""
self.info = proginfo
self.dirname = directory
def Output(self):
"""Output all sections of the page."""
self.Open()
self.Header()
self.Body()
self.Footer()
def Open(self): raise NotImplementedError # define in subclass
def Header(self): raise NotImplementedError # define in subclass
def Body(self): raise NotImplementedError # define in subclass
def Footer(self): raise NotImplementedError # define in subclass
class GenerateMan(GenerateDoc):
"""Output a man page."""
def __init__(self, proginfo, directory='.'):
"""Create base object.
Args:
proginfo A ProgramInfo object
directory Directory to write output into
"""
GenerateDoc.__init__(self, proginfo, directory)
def Open(self):
if self.dirname == '-':
logging.info('Writing to stdout')
self.fp = sys.stdout
else:
self.file_path = '%s.1' % os.path.join(self.dirname, self.info.name)
logging.info('Writing: %s' % self.file_path)
self.fp = open(self.file_path, 'w')
def Header(self):
self.fp.write(
'.\\" DO NOT MODIFY THIS FILE! It was generated by gflags2man %s\n'
% _VERSION)
self.fp.write(
'.TH %s "1" "%s" "%s" "User Commands"\n'
% (self.info.name, time.strftime('%x', self.info.date), self.info.name))
self.fp.write(
'.SH NAME\n%s \\- %s\n' % (self.info.name, self.info.short_desc))
self.fp.write(
'.SH SYNOPSIS\n.B %s\n[\\fIFLAGS\\fR]...\n' % self.info.name)
def Body(self):
self.fp.write(
'.SH DESCRIPTION\n.\\" Add any additional description here\n.PP\n')
for ln in self.info.desc:
self.fp.write('%s\n' % ln)
self.fp.write(
'.SH OPTIONS\n')
# This shows flags in the original order
for modname in self.info.module_list:
if modname.find(self.info.executable) >= 0:
mod = modname.replace(self.info.executable, self.info.name)
else:
mod = modname
self.fp.write('\n.P\n.I %s\n' % mod)
for flag in self.info.modules[modname]:
help_string = flag.help
if flag.default or flag.tips:
help_string += '\n.br\n'
if flag.default:
help_string += ' (default: \'%s\')' % flag.default
if flag.tips:
help_string += ' (%s)' % flag.tips
self.fp.write(
'.TP\n%s\n%s\n' % (flag.desc, help_string))
def Footer(self):
self.fp.write(
'.SH COPYRIGHT\nCopyright \(co %s Google.\n'
% time.strftime('%Y', self.info.date))
self.fp.write('Gflags2man created this page from "%s %s" output.\n'
% (self.info.name, FLAGS.help_flag))
self.fp.write('\nGflags2man was written by Dan Christian. '
' Note that the date on this'
' page is the modification date of %s.\n' % self.info.name)
def main(argv):
argv = FLAGS(argv) # handles help as well
if len(argv) <= 1:
app.usage(shorthelp=1)
return 1
for arg in argv[1:]:
prog = ProgramInfo(arg)
if not prog.Run():
continue
prog.Parse()
prog.Filter()
doc = GenerateMan(prog, FLAGS.dest_dir)
doc.Output()
return 0
if __name__ == '__main__':
app.run()
| apache-2.0 |
pinterb/st2 | st2common/st2common/util/jinja.py | 2 | 2074 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import jinja2
import six
def render_values(mapping=None, context=None):
"""
Render an incoming mapping using context provided in context using Jinja2. Returns a dict
containing rendered mapping.
:param mapping: Input as a dictionary of key value pairs.
:type mapping: ``dict``
:param context: Context to be used for dictionary.
:type context: ``dict``
:rtype: ``dict``
"""
if not context or not mapping:
return mapping
env = jinja2.Environment(undefined=jinja2.StrictUndefined)
rendered_mapping = {}
for k, v in six.iteritems(mapping):
# jinja2 works with string so transform list and dict to strings.
reverse_json_dumps = False
if isinstance(v, dict) or isinstance(v, list):
v = json.dumps(v)
reverse_json_dumps = True
else:
v = str(v)
rendered_v = env.from_string(v).render(context)
# no change therefore no templatization so pick params from original to retain
# original type
if rendered_v == v:
rendered_mapping[k] = mapping[k]
continue
if reverse_json_dumps:
rendered_v = json.loads(rendered_v)
rendered_mapping[k] = rendered_v
return rendered_mapping
| apache-2.0 |
MiLk/ansible | test/sanity/validate-modules/test_validate_modules_regex.py | 162 | 2807 | #!/usr/bin/env python
# This is a standalone test for the regex inside validate-modules
# It is not suitable to add to the make tests target because the
# file under test is outside the test's sys.path AND has a hyphen
# in the name making it unimportable.
#
# To execute this by hand:
# 1) cd <checkoutdir>
# 2) source hacking/env-setup
# 3) PYTHONPATH=./lib nosetests -d -w test -v --nocapture sanity/validate-modules
import re
from ansible.compat.tests import unittest
# TYPE_REGEX = re.compile(r'.*\stype\(.*')
# TYPE_REGEX = re.compile(r'.*(if|or)\stype\(.*')
# TYPE_REGEX = re.compile(r'.*(if|or)(\s+.*|\s+)type\(.*')
# TYPE_REGEX = re.compile(r'.*(if|or)(\s+.*|\s+)type\(.*')
# TYPE_REGEX = re.compile(r'.*(if|\sor)(\s+.*|\s+)type\(.*')
# TYPE_REGEX = re.compile(r'.*(if|\sor)(\s+.*|\s+)(?<!_)type\(.*')
TYPE_REGEX = re.compile(r'.*(if|or)(\s+.*|\s+)(?<!_)(?<!str\()type\(.*')
class TestValidateModulesRegex(unittest.TestCase):
def test_type_regex(self):
# each of these examples needs to be matched or not matched
checks = [
['if type(foo) is Bar', True],
['if Bar is type(foo)', True],
['if type(foo) is not Bar', True],
['if Bar is not type(foo)', True],
['if type(foo) == Bar', True],
['if Bar == type(foo)', True],
['if type(foo)==Bar', True],
['if Bar==type(foo)', True],
['if type(foo) != Bar', True],
['if Bar != type(foo)', True],
['if type(foo)!=Bar', True],
['if Bar!=type(foo)', True],
['if foo or type(bar) != Bar', True],
['x = type(foo)', False],
["error = err.message + ' ' + str(err) + ' - ' + str(type(err))", False],
# cloud/amazon/ec2_group.py
["module.fail_json(msg='Invalid rule parameter type [%s].' % type(rule))", False],
# files/patch.py
["p = type('Params', (), module.params)", False], # files/patch.py
# system/osx_defaults.py
["if self.current_value is not None and not isinstance(self.current_value, type(self.value)):", True],
# system/osx_defaults.py
['raise OSXDefaultsException("Type mismatch. Type in defaults: " + type(self.current_value).__name__)', False],
# network/nxos/nxos_interface.py
["if get_interface_type(interface) == 'svi':", False],
]
for idc, check in enumerate(checks):
cstring = check[0]
cexpected = check[1]
match = TYPE_REGEX.match(cstring)
if cexpected and not match:
assert False, "%s should have matched" % cstring
elif not cexpected and match:
assert False, "%s should not have matched" % cstring
| gpl-3.0 |
maxalbert/ansible | contrib/inventory/linode.py | 145 | 11235 | #!/usr/bin/env python
'''
Linode external inventory script
=================================
Generates inventory that Ansible can understand by making API request to
Linode using the Chube library.
NOTE: This script assumes Ansible is being executed where Chube is already
installed and has a valid config at ~/.chube. If not, run:
pip install chube
echo -e "---\napi_key: <YOUR API KEY GOES HERE>" > ~/.chube
For more details, see: https://github.com/exosite/chube
NOTE: This script also assumes that the Linodes in your account all have
labels that correspond to hostnames that are in your resolver search path.
Your resolver search path resides in /etc/hosts.
When run against a specific host, this script returns the following variables:
- api_id
- datacenter_id
- datacenter_city (lowercase city name of data center, e.g. 'tokyo')
- label
- display_group
- create_dt
- total_hd
- total_xfer
- total_ram
- status
- public_ip (The first public IP found)
- private_ip (The first private IP found, or empty string if none)
- alert_cpu_enabled
- alert_cpu_threshold
- alert_diskio_enabled
- alert_diskio_threshold
- alert_bwin_enabled
- alert_bwin_threshold
- alert_bwout_enabled
- alert_bwout_threshold
- alert_bwquota_enabled
- alert_bwquota_threshold
- backup_weekly_daily
- backup_window
- watchdog
Peter Sankauskas did most of the legwork here with his linode plugin; I
just adapted that for Linode.
'''
# (c) 2013, Dan Slimmon
#
# 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/>.
######################################################################
# Standard imports
import os
import re
import sys
import argparse
from time import time
try:
import json
except ImportError:
import simplejson as json
try:
from chube import load_chube_config
from chube import api as chube_api
from chube.datacenter import Datacenter
from chube.linode_obj import Linode
except:
try:
# remove local paths and other stuff that may
# cause an import conflict, as chube is sensitive
# to name collisions on importing
old_path = sys.path
sys.path = [d for d in sys.path if d not in ('', os.getcwd(), os.path.dirname(os.path.realpath(__file__)))]
from chube import load_chube_config
from chube import api as chube_api
from chube.datacenter import Datacenter
from chube.linode_obj import Linode
sys.path = old_path
except Exception, e:
raise Exception("could not import chube")
load_chube_config()
# Imports for ansible
import ConfigParser
class LinodeInventory(object):
def __init__(self):
"""Main execution path."""
# Inventory grouped by display group
self.inventory = {}
# Index of label to Linode ID
self.index = {}
# Local cache of Datacenter objects populated by populate_datacenter_cache()
self._datacenter_cache = None
# Read settings and parse CLI arguments
self.read_settings()
self.parse_cli_args()
# Cache
if self.args.refresh_cache:
self.do_api_calls_update_cache()
elif not self.is_cache_valid():
self.do_api_calls_update_cache()
# Data to print
if self.args.host:
data_to_print = self.get_host_info()
elif self.args.list:
# Display list of nodes for inventory
if len(self.inventory) == 0:
data_to_print = self.get_inventory_from_cache()
else:
data_to_print = self.json_format_dict(self.inventory, True)
print data_to_print
def is_cache_valid(self):
"""Determines if the cache file has expired, or if it is still valid."""
if os.path.isfile(self.cache_path_cache):
mod_time = os.path.getmtime(self.cache_path_cache)
current_time = time()
if (mod_time + self.cache_max_age) > current_time:
if os.path.isfile(self.cache_path_index):
return True
return False
def read_settings(self):
"""Reads the settings from the .ini file."""
config = ConfigParser.SafeConfigParser()
config.read(os.path.dirname(os.path.realpath(__file__)) + '/linode.ini')
# Cache related
cache_path = config.get('linode', 'cache_path')
self.cache_path_cache = cache_path + "/ansible-linode.cache"
self.cache_path_index = cache_path + "/ansible-linode.index"
self.cache_max_age = config.getint('linode', 'cache_max_age')
def parse_cli_args(self):
"""Command line argument processing"""
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on Linode')
parser.add_argument('--list', action='store_true', default=True,
help='List nodes (default: True)')
parser.add_argument('--host', action='store',
help='Get all the variables about a specific node')
parser.add_argument('--refresh-cache', action='store_true', default=False,
help='Force refresh of cache by making API requests to Linode (default: False - use cache files)')
self.args = parser.parse_args()
def do_api_calls_update_cache(self):
"""Do API calls, and save data in cache files."""
self.get_nodes()
self.write_to_cache(self.inventory, self.cache_path_cache)
self.write_to_cache(self.index, self.cache_path_index)
def get_nodes(self):
"""Makes an Linode API call to get the list of nodes."""
try:
for node in Linode.search(status=Linode.STATUS_RUNNING):
self.add_node(node)
except chube_api.linode_api.ApiError, e:
print "Looks like Linode's API is down:"
print
print e
sys.exit(1)
def get_node(self, linode_id):
"""Gets details about a specific node."""
try:
return Linode.find(api_id=linode_id)
except chube_api.linode_api.ApiError, e:
print "Looks like Linode's API is down:"
print
print e
sys.exit(1)
def populate_datacenter_cache(self):
"""Creates self._datacenter_cache, containing all Datacenters indexed by ID."""
self._datacenter_cache = {}
dcs = Datacenter.search()
for dc in dcs:
self._datacenter_cache[dc.api_id] = dc
def get_datacenter_city(self, node):
"""Returns a the lowercase city name of the node's data center."""
if self._datacenter_cache is None:
self.populate_datacenter_cache()
location = self._datacenter_cache[node.datacenter_id].location
location = location.lower()
location = location.split(",")[0]
return location
def add_node(self, node):
"""Adds an node to the inventory and index."""
dest = node.label
# Add to index
self.index[dest] = node.api_id
# Inventory: Group by node ID (always a group of 1)
self.inventory[node.api_id] = [dest]
# Inventory: Group by datacenter city
self.push(self.inventory, self.get_datacenter_city(node), dest)
# Inventory: Group by dipslay group
self.push(self.inventory, node.display_group, dest)
def get_host_info(self):
"""Get variables about a specific host."""
if len(self.index) == 0:
# Need to load index from cache
self.load_index_from_cache()
if not self.args.host in self.index:
# try updating the cache
self.do_api_calls_update_cache()
if not self.args.host in self.index:
# host might not exist anymore
return self.json_format_dict({}, True)
node_id = self.index[self.args.host]
node = self.get_node(node_id)
node_vars = {}
for direct_attr in [
"api_id",
"datacenter_id",
"label",
"display_group",
"create_dt",
"total_hd",
"total_xfer",
"total_ram",
"status",
"alert_cpu_enabled",
"alert_cpu_threshold",
"alert_diskio_enabled",
"alert_diskio_threshold",
"alert_bwin_enabled",
"alert_bwin_threshold",
"alert_bwout_enabled",
"alert_bwout_threshold",
"alert_bwquota_enabled",
"alert_bwquota_threshold",
"backup_weekly_daily",
"backup_window",
"watchdog"
]:
node_vars[direct_attr] = getattr(node, direct_attr)
node_vars["datacenter_city"] = self.get_datacenter_city(node)
node_vars["public_ip"] = [addr.address for addr in node.ipaddresses if addr.is_public][0]
private_ips = [addr.address for addr in node.ipaddresses if not addr.is_public]
if private_ips:
node_vars["private_ip"] = private_ips[0]
return self.json_format_dict(node_vars, True)
def push(self, my_dict, key, element):
"""Pushed an element onto an array that may not have been defined in the dict."""
if key in my_dict:
my_dict[key].append(element);
else:
my_dict[key] = [element]
def get_inventory_from_cache(self):
"""Reads the inventory from the cache file and returns it as a JSON object."""
cache = open(self.cache_path_cache, 'r')
json_inventory = cache.read()
return json_inventory
def load_index_from_cache(self):
"""Reads the index from the cache file and sets self.index."""
cache = open(self.cache_path_index, 'r')
json_index = cache.read()
self.index = json.loads(json_index)
def write_to_cache(self, data, filename):
"""Writes data in JSON format to a file."""
json_data = self.json_format_dict(data, True)
cache = open(filename, 'w')
cache.write(json_data)
cache.close()
def to_safe(self, word):
"""Escapes any characters that would be invalid in an ansible group name."""
return re.sub("[^A-Za-z0-9\-]", "_", word)
def json_format_dict(self, data, pretty=False):
"""Converts a dict to a JSON object and dumps it as a formatted string."""
if pretty:
return json.dumps(data, sort_keys=True, indent=2)
else:
return json.dumps(data)
LinodeInventory()
| gpl-3.0 |
revmischa/boto | tests/integration/support/test_layer1.py | 135 | 3029 | # Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import unittest
import time
from boto.support.layer1 import SupportConnection
from boto.support import exceptions
class TestSupportLayer1Management(unittest.TestCase):
support = True
def setUp(self):
self.api = SupportConnection()
self.wait_time = 5
def test_as_much_as_possible_before_teardown(self):
cases = self.api.describe_cases()
preexisting_count = len(cases.get('cases', []))
services = self.api.describe_services()
self.assertTrue('services' in services)
service_codes = [serv['code'] for serv in services['services']]
self.assertTrue('amazon-cloudsearch' in service_codes)
severity = self.api.describe_severity_levels()
self.assertTrue('severityLevels' in severity)
severity_codes = [sev['code'] for sev in severity['severityLevels']]
self.assertTrue('low' in severity_codes)
case_1 = self.api.create_case(
subject='TEST: I am a test case.',
service_code='amazon-cloudsearch',
category_code='other',
communication_body="This is a test problem",
severity_code='low',
language='en'
)
time.sleep(self.wait_time)
case_id = case_1['caseId']
new_cases = self.api.describe_cases()
self.assertTrue(len(new_cases['cases']) > preexisting_count)
result = self.api.add_communication_to_case(
communication_body="This is a test solution.",
case_id=case_id
)
self.assertTrue(result.get('result', False))
time.sleep(self.wait_time)
final_cases = self.api.describe_cases(case_id_list=[case_id])
comms = final_cases['cases'][0]['recentCommunications']\
['communications']
self.assertEqual(len(comms), 2)
close_result = self.api.resolve_case(case_id=case_id)
| mit |
resba/gnuradio | gnuradio-core/src/python/gnuradio/gr/gr_threading_23.py | 94 | 21922 | """Thread module emulating a subset of Java's threading model."""
# This started life as the threading.py module of Python 2.3
# It's been patched to fix a problem with join, where a KeyboardInterrupt
# caused a lock to be left in the acquired state.
import sys as _sys
try:
import thread
except ImportError:
del _sys.modules[__name__]
raise
from StringIO import StringIO as _StringIO
from time import time as _time, sleep as _sleep
from traceback import print_exc as _print_exc
# Rename some stuff so "from threading import *" is safe
__all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
'Timer', 'setprofile', 'settrace']
_start_new_thread = thread.start_new_thread
_allocate_lock = thread.allocate_lock
_get_ident = thread.get_ident
ThreadError = thread.error
del thread
# Debug support (adapted from ihooks.py).
# All the major classes here derive from _Verbose. We force that to
# be a new-style class so that all the major classes here are new-style.
# This helps debugging (type(instance) is more revealing for instances
# of new-style classes).
_VERBOSE = False
if __debug__:
class _Verbose(object):
def __init__(self, verbose=None):
if verbose is None:
verbose = _VERBOSE
self.__verbose = verbose
def _note(self, format, *args):
if self.__verbose:
format = format % args
format = "%s: %s\n" % (
currentThread().getName(), format)
_sys.stderr.write(format)
else:
# Disable this when using "python -O"
class _Verbose(object):
def __init__(self, verbose=None):
pass
def _note(self, *args):
pass
# Support for profile and trace hooks
_profile_hook = None
_trace_hook = None
def setprofile(func):
global _profile_hook
_profile_hook = func
def settrace(func):
global _trace_hook
_trace_hook = func
# Synchronization classes
Lock = _allocate_lock
def RLock(*args, **kwargs):
return _RLock(*args, **kwargs)
class _RLock(_Verbose):
def __init__(self, verbose=None):
_Verbose.__init__(self, verbose)
self.__block = _allocate_lock()
self.__owner = None
self.__count = 0
def __repr__(self):
return "<%s(%s, %d)>" % (
self.__class__.__name__,
self.__owner and self.__owner.getName(),
self.__count)
def acquire(self, blocking=1):
me = currentThread()
if self.__owner is me:
self.__count = self.__count + 1
if __debug__:
self._note("%s.acquire(%s): recursive success", self, blocking)
return 1
rc = self.__block.acquire(blocking)
if rc:
self.__owner = me
self.__count = 1
if __debug__:
self._note("%s.acquire(%s): initial succes", self, blocking)
else:
if __debug__:
self._note("%s.acquire(%s): failure", self, blocking)
return rc
def release(self):
me = currentThread()
assert self.__owner is me, "release() of un-acquire()d lock"
self.__count = count = self.__count - 1
if not count:
self.__owner = None
self.__block.release()
if __debug__:
self._note("%s.release(): final release", self)
else:
if __debug__:
self._note("%s.release(): non-final release", self)
# Internal methods used by condition variables
def _acquire_restore(self, (count, owner)):
self.__block.acquire()
self.__count = count
self.__owner = owner
if __debug__:
self._note("%s._acquire_restore()", self)
def _release_save(self):
if __debug__:
self._note("%s._release_save()", self)
count = self.__count
self.__count = 0
owner = self.__owner
self.__owner = None
self.__block.release()
return (count, owner)
def _is_owned(self):
return self.__owner is currentThread()
def Condition(*args, **kwargs):
return _Condition(*args, **kwargs)
class _Condition(_Verbose):
def __init__(self, lock=None, verbose=None):
_Verbose.__init__(self, verbose)
if lock is None:
lock = RLock()
self.__lock = lock
# Export the lock's acquire() and release() methods
self.acquire = lock.acquire
self.release = lock.release
# If the lock defines _release_save() and/or _acquire_restore(),
# these override the default implementations (which just call
# release() and acquire() on the lock). Ditto for _is_owned().
try:
self._release_save = lock._release_save
except AttributeError:
pass
try:
self._acquire_restore = lock._acquire_restore
except AttributeError:
pass
try:
self._is_owned = lock._is_owned
except AttributeError:
pass
self.__waiters = []
def __repr__(self):
return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
def _release_save(self):
self.__lock.release() # No state to save
def _acquire_restore(self, x):
self.__lock.acquire() # Ignore saved state
def _is_owned(self):
# Return True if lock is owned by currentThread.
# This method is called only if __lock doesn't have _is_owned().
if self.__lock.acquire(0):
self.__lock.release()
return False
else:
return True
def wait(self, timeout=None):
currentThread() # for side-effect
assert self._is_owned(), "wait() of un-acquire()d lock"
waiter = _allocate_lock()
waiter.acquire()
self.__waiters.append(waiter)
saved_state = self._release_save()
try: # restore state no matter what (e.g., KeyboardInterrupt)
if timeout is None:
waiter.acquire()
if __debug__:
self._note("%s.wait(): got it", self)
else:
# Balancing act: We can't afford a pure busy loop, so we
# have to sleep; but if we sleep the whole timeout time,
# we'll be unresponsive. The scheme here sleeps very
# little at first, longer as time goes on, but never longer
# than 20 times per second (or the timeout time remaining).
endtime = _time() + timeout
delay = 0.0005 # 500 us -> initial delay of 1 ms
while True:
gotit = waiter.acquire(0)
if gotit:
break
remaining = endtime - _time()
if remaining <= 0:
break
delay = min(delay * 2, remaining, .05)
_sleep(delay)
if not gotit:
if __debug__:
self._note("%s.wait(%s): timed out", self, timeout)
try:
self.__waiters.remove(waiter)
except ValueError:
pass
else:
if __debug__:
self._note("%s.wait(%s): got it", self, timeout)
finally:
self._acquire_restore(saved_state)
def notify(self, n=1):
currentThread() # for side-effect
assert self._is_owned(), "notify() of un-acquire()d lock"
__waiters = self.__waiters
waiters = __waiters[:n]
if not waiters:
if __debug__:
self._note("%s.notify(): no waiters", self)
return
self._note("%s.notify(): notifying %d waiter%s", self, n,
n!=1 and "s" or "")
for waiter in waiters:
waiter.release()
try:
__waiters.remove(waiter)
except ValueError:
pass
def notifyAll(self):
self.notify(len(self.__waiters))
def Semaphore(*args, **kwargs):
return _Semaphore(*args, **kwargs)
class _Semaphore(_Verbose):
# After Tim Peters' semaphore class, but not quite the same (no maximum)
def __init__(self, value=1, verbose=None):
assert value >= 0, "Semaphore initial value must be >= 0"
_Verbose.__init__(self, verbose)
self.__cond = Condition(Lock())
self.__value = value
def acquire(self, blocking=1):
rc = False
self.__cond.acquire()
while self.__value == 0:
if not blocking:
break
if __debug__:
self._note("%s.acquire(%s): blocked waiting, value=%s",
self, blocking, self.__value)
self.__cond.wait()
else:
self.__value = self.__value - 1
if __debug__:
self._note("%s.acquire: success, value=%s",
self, self.__value)
rc = True
self.__cond.release()
return rc
def release(self):
self.__cond.acquire()
self.__value = self.__value + 1
if __debug__:
self._note("%s.release: success, value=%s",
self, self.__value)
self.__cond.notify()
self.__cond.release()
def BoundedSemaphore(*args, **kwargs):
return _BoundedSemaphore(*args, **kwargs)
class _BoundedSemaphore(_Semaphore):
"""Semaphore that checks that # releases is <= # acquires"""
def __init__(self, value=1, verbose=None):
_Semaphore.__init__(self, value, verbose)
self._initial_value = value
def release(self):
if self._Semaphore__value >= self._initial_value:
raise ValueError, "Semaphore released too many times"
return _Semaphore.release(self)
def Event(*args, **kwargs):
return _Event(*args, **kwargs)
class _Event(_Verbose):
# After Tim Peters' event class (without is_posted())
def __init__(self, verbose=None):
_Verbose.__init__(self, verbose)
self.__cond = Condition(Lock())
self.__flag = False
def isSet(self):
return self.__flag
def set(self):
self.__cond.acquire()
try:
self.__flag = True
self.__cond.notifyAll()
finally:
self.__cond.release()
def clear(self):
self.__cond.acquire()
try:
self.__flag = False
finally:
self.__cond.release()
def wait(self, timeout=None):
self.__cond.acquire()
try:
if not self.__flag:
self.__cond.wait(timeout)
finally:
self.__cond.release()
# Helper to generate new thread names
_counter = 0
def _newname(template="Thread-%d"):
global _counter
_counter = _counter + 1
return template % _counter
# Active thread administration
_active_limbo_lock = _allocate_lock()
_active = {}
_limbo = {}
# Main class for threads
class Thread(_Verbose):
__initialized = False
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, verbose=None):
assert group is None, "group argument must be None for now"
_Verbose.__init__(self, verbose)
self.__target = target
self.__name = str(name or _newname())
self.__args = args
self.__kwargs = kwargs
self.__daemonic = self._set_daemon()
self.__started = False
self.__stopped = False
self.__block = Condition(Lock())
self.__initialized = True
def _set_daemon(self):
# Overridden in _MainThread and _DummyThread
return currentThread().isDaemon()
def __repr__(self):
assert self.__initialized, "Thread.__init__() was not called"
status = "initial"
if self.__started:
status = "started"
if self.__stopped:
status = "stopped"
if self.__daemonic:
status = status + " daemon"
return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
def start(self):
assert self.__initialized, "Thread.__init__() not called"
assert not self.__started, "thread already started"
if __debug__:
self._note("%s.start(): starting thread", self)
_active_limbo_lock.acquire()
_limbo[self] = self
_active_limbo_lock.release()
_start_new_thread(self.__bootstrap, ())
self.__started = True
_sleep(0.000001) # 1 usec, to let the thread run (Solaris hack)
def run(self):
if self.__target:
self.__target(*self.__args, **self.__kwargs)
def __bootstrap(self):
try:
self.__started = True
_active_limbo_lock.acquire()
_active[_get_ident()] = self
del _limbo[self]
_active_limbo_lock.release()
if __debug__:
self._note("%s.__bootstrap(): thread started", self)
if _trace_hook:
self._note("%s.__bootstrap(): registering trace hook", self)
_sys.settrace(_trace_hook)
if _profile_hook:
self._note("%s.__bootstrap(): registering profile hook", self)
_sys.setprofile(_profile_hook)
try:
self.run()
except SystemExit:
if __debug__:
self._note("%s.__bootstrap(): raised SystemExit", self)
except:
if __debug__:
self._note("%s.__bootstrap(): unhandled exception", self)
s = _StringIO()
_print_exc(file=s)
_sys.stderr.write("Exception in thread %s:\n%s\n" %
(self.getName(), s.getvalue()))
else:
if __debug__:
self._note("%s.__bootstrap(): normal return", self)
finally:
self.__stop()
try:
self.__delete()
except:
pass
def __stop(self):
self.__block.acquire()
self.__stopped = True
self.__block.notifyAll()
self.__block.release()
def __delete(self):
_active_limbo_lock.acquire()
del _active[_get_ident()]
_active_limbo_lock.release()
def join(self, timeout=None):
assert self.__initialized, "Thread.__init__() not called"
assert self.__started, "cannot join thread before it is started"
assert self is not currentThread(), "cannot join current thread"
if __debug__:
if not self.__stopped:
self._note("%s.join(): waiting until thread stops", self)
self.__block.acquire()
try:
if timeout is None:
while not self.__stopped:
self.__block.wait()
if __debug__:
self._note("%s.join(): thread stopped", self)
else:
deadline = _time() + timeout
while not self.__stopped:
delay = deadline - _time()
if delay <= 0:
if __debug__:
self._note("%s.join(): timed out", self)
break
self.__block.wait(delay)
else:
if __debug__:
self._note("%s.join(): thread stopped", self)
finally:
self.__block.release()
def getName(self):
assert self.__initialized, "Thread.__init__() not called"
return self.__name
def setName(self, name):
assert self.__initialized, "Thread.__init__() not called"
self.__name = str(name)
def isAlive(self):
assert self.__initialized, "Thread.__init__() not called"
return self.__started and not self.__stopped
def isDaemon(self):
assert self.__initialized, "Thread.__init__() not called"
return self.__daemonic
def setDaemon(self, daemonic):
assert self.__initialized, "Thread.__init__() not called"
assert not self.__started, "cannot set daemon status of active thread"
self.__daemonic = daemonic
# The timer class was contributed by Itamar Shtull-Trauring
def Timer(*args, **kwargs):
return _Timer(*args, **kwargs)
class _Timer(Thread):
"""Call a function after a specified number of seconds:
t = Timer(30.0, f, args=[], kwargs={})
t.start()
t.cancel() # stop the timer's action if it's still waiting
"""
def __init__(self, interval, function, args=[], kwargs={}):
Thread.__init__(self)
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def cancel(self):
"""Stop the timer if it hasn't finished yet"""
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.isSet():
self.function(*self.args, **self.kwargs)
self.finished.set()
# Special thread class to represent the main thread
# This is garbage collected through an exit handler
class _MainThread(Thread):
def __init__(self):
Thread.__init__(self, name="MainThread")
self._Thread__started = True
_active_limbo_lock.acquire()
_active[_get_ident()] = self
_active_limbo_lock.release()
import atexit
atexit.register(self.__exitfunc)
def _set_daemon(self):
return False
def __exitfunc(self):
self._Thread__stop()
t = _pickSomeNonDaemonThread()
if t:
if __debug__:
self._note("%s: waiting for other threads", self)
while t:
t.join()
t = _pickSomeNonDaemonThread()
if __debug__:
self._note("%s: exiting", self)
self._Thread__delete()
def _pickSomeNonDaemonThread():
for t in enumerate():
if not t.isDaemon() and t.isAlive():
return t
return None
# Dummy thread class to represent threads not started here.
# These aren't garbage collected when they die,
# nor can they be waited for.
# Their purpose is to return *something* from currentThread().
# They are marked as daemon threads so we won't wait for them
# when we exit (conform previous semantics).
class _DummyThread(Thread):
def __init__(self):
Thread.__init__(self, name=_newname("Dummy-%d"))
self._Thread__started = True
_active_limbo_lock.acquire()
_active[_get_ident()] = self
_active_limbo_lock.release()
def _set_daemon(self):
return True
def join(self, timeout=None):
assert False, "cannot join a dummy thread"
# Global API functions
def currentThread():
try:
return _active[_get_ident()]
except KeyError:
##print "currentThread(): no current thread for", _get_ident()
return _DummyThread()
def activeCount():
_active_limbo_lock.acquire()
count = len(_active) + len(_limbo)
_active_limbo_lock.release()
return count
def enumerate():
_active_limbo_lock.acquire()
active = _active.values() + _limbo.values()
_active_limbo_lock.release()
return active
# Create the main thread object
_MainThread()
# Self-test code
def _test():
class BoundedQueue(_Verbose):
def __init__(self, limit):
_Verbose.__init__(self)
self.mon = RLock()
self.rc = Condition(self.mon)
self.wc = Condition(self.mon)
self.limit = limit
self.queue = []
def put(self, item):
self.mon.acquire()
while len(self.queue) >= self.limit:
self._note("put(%s): queue full", item)
self.wc.wait()
self.queue.append(item)
self._note("put(%s): appended, length now %d",
item, len(self.queue))
self.rc.notify()
self.mon.release()
def get(self):
self.mon.acquire()
while not self.queue:
self._note("get(): queue empty")
self.rc.wait()
item = self.queue.pop(0)
self._note("get(): got %s, %d left", item, len(self.queue))
self.wc.notify()
self.mon.release()
return item
class ProducerThread(Thread):
def __init__(self, queue, quota):
Thread.__init__(self, name="Producer")
self.queue = queue
self.quota = quota
def run(self):
from random import random
counter = 0
while counter < self.quota:
counter = counter + 1
self.queue.put("%s.%d" % (self.getName(), counter))
_sleep(random() * 0.00001)
class ConsumerThread(Thread):
def __init__(self, queue, count):
Thread.__init__(self, name="Consumer")
self.queue = queue
self.count = count
def run(self):
while self.count > 0:
item = self.queue.get()
print item
self.count = self.count - 1
NP = 3
QL = 4
NI = 5
Q = BoundedQueue(QL)
P = []
for i in range(NP):
t = ProducerThread(Q, NI)
t.setName("Producer-%d" % (i+1))
P.append(t)
C = ConsumerThread(Q, NI*NP)
for t in P:
t.start()
_sleep(0.000001)
C.start()
for t in P:
t.join()
C.join()
if __name__ == '__main__':
_test()
| gpl-3.0 |
rhinstaller/blivet | blivet/autopart.py | 1 | 20576 | #
# Copyright (C) 2009-2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Dave Lehman <dlehman@redhat.com>
#
"""This module provides functions related to automatic partitioning."""
import parted
from decimal import Decimal
from . import util
from .size import Size
from .devices.partition import PartitionDevice, FALLBACK_DEFAULT_PART_SIZE
from .devices.luks import LUKSDevice
from .devices.lvm import ThPoolReserveSpec
from .errors import NoDisksError, NotEnoughFreeSpaceError
from .formats import get_format
from .partitioning import do_partitioning, get_free_regions, grow_lvm
from .i18n import _
from .static_data import luks_data
from pykickstart.constants import AUTOPART_TYPE_BTRFS, AUTOPART_TYPE_LVM, AUTOPART_TYPE_LVM_THINP, AUTOPART_TYPE_PLAIN
import logging
log = logging.getLogger("anaconda.blivet.autopart")
# maximum ratio of swap size to disk size (10 %)
MAX_SWAP_DISK_RATIO = Decimal('0.1')
AUTOPART_THPOOL_RESERVE = ThPoolReserveSpec(20, Size("1 GiB"), Size("100 GiB"))
def swap_suggestion(quiet=False, hibernation=False, disk_space=None):
"""
Suggest the size of the swap partition that will be created.
:param quiet: whether to log size information or not
:type quiet: bool
:param hibernation: calculate swap size big enough for hibernation
:type hibernation: bool
:param disk_space: how much disk space is available
:type disk_space: :class:`~.size.Size`
:return: calculated swap size
"""
mem = util.total_memory()
mem = ((mem / 16) + 1) * 16
if not quiet:
log.info("Detected %s of memory", mem)
sixtyfour_GiB = Size("64 GiB")
# the succeeding if-statement implements the following formula for
# suggested swap size.
#
# swap(mem) = 2 * mem, if mem < 2 GiB
# = mem, if 2 GiB <= mem < 8 GiB
# = mem / 2, if 8 GIB <= mem < 64 GiB
# = 4 GiB, if mem >= 64 GiB
if mem < Size("2 GiB"):
swap = 2 * mem
elif mem < Size("8 GiB"):
swap = mem
elif mem < sixtyfour_GiB:
swap = mem / 2
else:
swap = Size("4 GiB")
if hibernation:
if mem <= sixtyfour_GiB:
swap = mem + swap
else:
log.info("Ignoring --hibernation option on systems with %s of RAM or more", sixtyfour_GiB)
if disk_space is not None and not hibernation:
max_swap = disk_space * MAX_SWAP_DISK_RATIO
if swap > max_swap:
log.info("Suggested swap size (%(swap)s) exceeds %(percent)d %% of "
"disk space, using %(percent)d %% of disk space (%(size)s) "
"instead.", {"percent": MAX_SWAP_DISK_RATIO * 100,
"swap": swap,
"size": max_swap})
swap = max_swap
if not quiet:
log.info("Swap attempt of %s", swap)
return swap
def _get_candidate_disks(storage):
""" Return a list of disks to be used for autopart/reqpart.
Disks must be partitioned and have a single free region large enough
for a default-sized (500MiB) partition. They must also be in
:attr:`StorageDiscoveryConfig.clear_part_disks` if it is non-empty.
:param storage: a Blivet instance
:type storage: :class:`~.Blivet`
:returns: a list of partitioned disks with at least 500MiB of free space
:rtype: list of :class:`~.devices.StorageDevice`
"""
disks = []
for disk in storage.partitioned:
if not disk.format.supported or disk.protected:
continue
if storage.config.clear_part_disks and \
(disk.name not in storage.config.clear_part_disks):
continue
part = disk.format.first_partition
while part:
if not part.type & parted.PARTITION_FREESPACE:
part = part.nextPartition()
continue
if Size(part.getLength(unit="B")) > PartitionDevice.default_size:
disks.append(disk)
break
part = part.nextPartition()
return disks
def _schedule_implicit_partitions(storage, disks):
""" Schedule creation of a lvm/btrfs member partitions for autopart.
We create one such partition on each disk. They are not allocated until
later (in :func:`doPartitioning`).
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param disks: list of partitioned disks with free space
:type disks: list of :class:`~.devices.StorageDevice`
:returns: list of newly created (unallocated) partitions
:rtype: list of :class:`~.devices.PartitionDevice`
"""
# create a separate pv or btrfs partition for each disk with free space
devs = []
# only schedule the partitions if either lvm or btrfs autopart was chosen
if storage.autopart_type == AUTOPART_TYPE_PLAIN:
return devs
for disk in disks:
if storage.encrypted_autopart:
fmt_type = "luks"
fmt_args = {"passphrase": luks_data.encryption_passphrase,
"cipher": storage.encryption_cipher,
"escrow_cert": storage.autopart_escrow_cert,
"add_backup_passphrase": storage.autopart_add_backup_passphrase,
"min_luks_entropy": luks_data.min_entropy}
else:
if storage.autopart_type in (AUTOPART_TYPE_LVM, AUTOPART_TYPE_LVM_THINP):
fmt_type = "lvmpv"
else:
fmt_type = "btrfs"
fmt_args = {}
part = storage.new_partition(fmt_type=fmt_type,
fmt_args=fmt_args,
grow=True,
parents=[disk])
storage.create_device(part)
devs.append(part)
return devs
def _schedule_partitions(storage, disks, implicit_devices, requests=None):
""" Schedule creation of autopart/reqpart partitions.
This only schedules the requests for actual partitions.
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param disks: list of partitioned disks with free space
:type disks: list of :class:`~.devices.StorageDevice`
:param requests: list of partitioning requests to operate on,
or `~.storage.autopart_requests` by default
:type requests: list of :class:`~.partspec.PartSpec` instances
:returns: None
:rtype: None
"""
if not requests:
requests = storage.autopart_requests
# basis for requests with required_space is the sum of the sizes of the
# two largest free regions
all_free = (Size(reg.getLength(unit="B")) for reg in get_free_regions(disks))
all_free = sorted(all_free, reverse=True)
if not all_free:
# this should never happen since we've already filtered the disks
# to those with at least 500MiB free
log.error("no free space on disks %s", [d.name for d in disks])
return
free = all_free[0]
if len(all_free) > 1:
free += all_free[1]
# The boot disk must be set at this point. See if any platform-specific
# stage1 device we might allocate already exists on the boot disk.
stage1_device = None
for device in storage.devices:
if storage.bootloader.stage1_disk not in device.disks:
continue
if storage.bootloader.is_valid_stage1_device(device, early=True):
stage1_device = device
break
#
# First pass is for partitions only. We'll do LVs later.
#
for request in requests:
if ((request.lv and storage.do_autopart and
storage.autopart_type in (AUTOPART_TYPE_LVM,
AUTOPART_TYPE_LVM_THINP)) or
(request.btr and storage.autopart_type == AUTOPART_TYPE_BTRFS)):
continue
if request.required_space and request.required_space > free:
continue
elif request.fstype in ("prepboot", "efi", "macefi", "hfs+") and \
(storage.bootloader.skip_bootloader or stage1_device):
# there should never be a need for more than one of these
# partitions, so skip them.
log.info("skipping unneeded stage1 %s request", request.fstype)
log.debug("%s", request)
if request.fstype in ["efi", "macefi"] and stage1_device:
# Set the mountpoint for the existing EFI boot partition
stage1_device.format.mountpoint = "/boot/efi"
log.debug("%s", stage1_device)
continue
elif request.fstype == "biosboot":
is_gpt = (stage1_device and
getattr(stage1_device.format, "label_type", None) == "gpt")
has_bios_boot = (stage1_device and
any([p.format.type == "biosboot"
for p in storage.partitions
if p.disk == stage1_device]))
if (storage.bootloader.skip_bootloader or
not (stage1_device and stage1_device.is_disk and
is_gpt and not has_bios_boot)):
# there should never be a need for more than one of these
# partitions, so skip them.
log.info("skipping unneeded stage1 %s request", request.fstype)
log.debug("%s", request)
log.debug("%s", stage1_device)
continue
if request.size > all_free[0]:
# no big enough free space for the requested partition
raise NotEnoughFreeSpaceError(_("No big enough free space on disks for "
"automatic partitioning"))
if request.encrypted and storage.encrypted_autopart:
fmt_type = "luks"
fmt_args = {"passphrase": luks_data.encryption_passphrase,
"cipher": storage.encryption_cipher,
"escrow_cert": storage.autopart_escrow_cert,
"add_backup_passphrase": storage.autopart_add_backup_passphrase,
"min_luks_entropy": luks_data.min_entropy}
else:
fmt_type = request.fstype
fmt_args = {}
dev = storage.new_partition(fmt_type=fmt_type,
fmt_args=fmt_args,
size=request.size,
grow=request.grow,
maxsize=request.max_size,
mountpoint=request.mountpoint,
parents=disks,
weight=request.weight)
# schedule the device for creation
storage.create_device(dev)
if request.encrypted and storage.encrypted_autopart:
luks_fmt = get_format(request.fstype,
device=dev.path,
mountpoint=request.mountpoint)
luks_dev = LUKSDevice("luks-%s" % dev.name,
fmt=luks_fmt,
size=dev.size,
parents=dev)
storage.create_device(luks_dev)
if storage.do_autopart and \
storage.autopart_type in (AUTOPART_TYPE_LVM, AUTOPART_TYPE_LVM_THINP,
AUTOPART_TYPE_BTRFS):
# doing LVM/BTRFS -- make sure the newly created partition fits in some
# free space together with one of the implicitly requested partitions
smallest_implicit = sorted(implicit_devices, key=lambda d: d.size)[0]
if (request.size + smallest_implicit.size) > all_free[0]:
# not enough space to allocate the smallest implicit partition
# and the request, make the implicit partitions smaller in
# attempt to make space for the request
for implicit_req in implicit_devices:
implicit_req.size = FALLBACK_DEFAULT_PART_SIZE
return implicit_devices
def _schedule_volumes(storage, devs):
""" Schedule creation of autopart lvm/btrfs volumes.
Schedules encryption of member devices if requested, schedules creation
of the container (:class:`~.devices.LVMVolumeGroupDevice` or
:class:`~.devices.BTRFSVolumeDevice`) then schedules creation of the
autopart volume requests.
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param devs: list of member partitions
:type devs: list of :class:`~.devices.PartitionDevice`
:returns: None
:rtype: None
If an appropriate bootloader stage1 device exists on the boot drive, any
autopart request to create another one will be skipped/discarded.
"""
if not devs:
return
if storage.autopart_type in (AUTOPART_TYPE_LVM, AUTOPART_TYPE_LVM_THINP):
new_container = storage.new_vg
new_volume = storage.new_lv
format_name = "lvmpv"
else:
new_container = storage.new_btrfs
new_volume = storage.new_btrfs
format_name = "btrfs"
if storage.encrypted_autopart:
pvs = []
for dev in devs:
pv = LUKSDevice("luks-%s" % dev.name,
fmt=get_format(format_name, device=dev.path),
size=dev.size,
parents=dev)
pvs.append(pv)
storage.create_device(pv)
else:
pvs = devs
# create a vg containing all of the autopart pvs
container = new_container(parents=pvs)
storage.create_device(container)
#
# Convert storage.autopart_requests into Device instances and
# schedule them for creation.
#
# Second pass, for LVs only.
pool = None
for request in storage.autopart_requests:
btr = storage.autopart_type == AUTOPART_TYPE_BTRFS and request.btr
lv = (storage.autopart_type in (AUTOPART_TYPE_LVM,
AUTOPART_TYPE_LVM_THINP) and request.lv)
thinlv = (storage.autopart_type == AUTOPART_TYPE_LVM_THINP and
request.lv and request.thin)
if thinlv and pool is None:
# create a single thin pool in the vg
pool = storage.new_lv(parents=[container], thin_pool=True, grow=True)
storage.create_device(pool)
# make sure VG reserves space for the pool to grow if needed
container.thpool_reserve = AUTOPART_THPOOL_RESERVE
if not btr and not lv and not thinlv:
continue
# required space isn't relevant on btrfs
if (lv or thinlv) and \
request.required_space and request.required_space > container.size:
continue
if request.fstype is None:
if btr:
# btrfs volumes can only contain btrfs filesystems
request.fstype = "btrfs"
else:
request.fstype = storage.default_fstype
kwargs = {"mountpoint": request.mountpoint,
"fmt_type": request.fstype}
if lv or thinlv:
if thinlv:
parents = [pool]
else:
parents = [container]
kwargs.update({"parents": parents,
"grow": request.grow,
"maxsize": request.max_size,
"size": request.size,
"thin_volume": thinlv})
else:
kwargs.update({"parents": [container],
"size": request.size,
"subvol": True})
dev = new_volume(**kwargs)
# schedule the device for creation
storage.create_device(dev)
def do_reqpart(storage, requests):
"""Perform automatic partitioning of just required platform-specific
partitions. This is incompatible with do_autopart.
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param requests: list of partitioning requests to operate on,
or `~.storage.autopart_requests` by default
:type requests: list of :class:`~.partspec.PartSpec` instances
"""
if not any(d.format.supported for d in storage.partitioned):
raise NoDisksError(_("No usable disks selected"))
disks = _get_candidate_disks(storage)
if disks == []:
raise NotEnoughFreeSpaceError(_("Not enough free space on disks for "
"automatic partitioning"))
_schedule_partitions(storage, disks, [], requests=requests)
def do_autopart(storage, data, min_luks_entropy=None):
""" Perform automatic partitioning.
:param storage: a :class:`~.Blivet` instance
:type storage: :class:`~.Blivet`
:param data: kickstart data
:type data: :class:`pykickstart.BaseHandler`
:param min_luks_entropy: minimum entropy in bits required for
luks format creation; uses default when None
:type min_luks_entropy: int
:attr:`Blivet.do_autopart` controls whether this method creates the
automatic partitioning layout. :attr:`Blivet.autopart_type` controls
which variant of autopart used. It uses one of the pykickstart
AUTOPART_TYPE_* constants. The set of eligible disks is defined in
:attr:`StorageDiscoveryConfig.clear_part_disks`.
.. note::
Clearing of partitions is handled separately, in
:meth:`~.Blivet.clear_partitions`.
"""
# pylint: disable=unused-argument
log.debug("do_autopart: %s", storage.do_autopart)
log.debug("encrypted_autopart: %s", storage.encrypted_autopart)
log.debug("autopart_type: %s", storage.autopart_type)
log.debug("clear_part_type: %s", storage.config.clear_part_type)
log.debug("clear_part_disks: %s", storage.config.clear_part_disks)
log.debug("autopart_requests:\n%s", "".join([str(p) for p in storage.autopart_requests]))
log.debug("storage.disks: %s", [d.name for d in storage.disks])
log.debug("storage.partitioned: %s", [d.name for d in storage.partitioned if d.format.supported])
log.debug("all names: %s", [d.name for d in storage.devices])
log.debug("boot disk: %s", getattr(storage.boot_disk, "name", None))
disks = []
devs = []
if not storage.do_autopart:
return
if not any(d.format.supported for d in storage.partitioned):
raise NoDisksError(_("No usable disks selected"))
if min_luks_entropy is not None:
luks_data.min_entropy = min_luks_entropy
disks = _get_candidate_disks(storage)
devs = _schedule_implicit_partitions(storage, disks)
log.debug("candidate disks: %s", disks)
log.debug("devs: %s", devs)
if disks == []:
raise NotEnoughFreeSpaceError(_("Not enough free space on disks for "
"automatic partitioning"))
devs = _schedule_partitions(storage, disks, devs)
# run the autopart function to allocate and grow partitions
do_partitioning(storage)
_schedule_volumes(storage, devs)
# grow LVs
grow_lvm(storage)
storage.set_up_bootloader()
# only newly added swaps should appear in the fstab
new_swaps = (dev for dev in storage.swaps if not dev.format.exists)
storage.set_fstab_swaps(new_swaps)
| lgpl-2.1 |
5n1p/appengine-overheard-python | gaeunit.py | 5 | 18637 | #!/usr/bin/env python
'''
GAEUnit: Google App Engine Unit Test Framework
Usage:
1. Put gaeunit.py into your application directory. Modify 'app.yaml' by
adding the following mapping below the 'handlers:' section:
- url: /test.*
script: gaeunit.py
2. Write your own test cases by extending unittest.TestCase.
3. Launch the development web server. To run all tests, point your browser to:
http://localhost:8080/test (Modify the port if necessary.)
For plain text output add '?format=plain' to the above URL.
See README.TXT for information on how to run specific tests.
4. The results are displayed as the tests are run.
Visit http://code.google.com/p/gaeunit for more information and updates.
------------------------------------------------------------------------------
Copyright (c) 2008, George Lei and Steven R. Farley. All rights reserved.
Distributed under the following BSD license:
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 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.
------------------------------------------------------------------------------
'''
__author__ = "George Lei and Steven R. Farley"
__email__ = "George.Z.Lei@Gmail.com"
__version__ = "#Revision: 1.2.2 $"[11:-2]
__copyright__= "Copyright (c) 2008, George Lei and Steven R. Farley"
__license__ = "BSD"
__url__ = "http://code.google.com/p/gaeunit"
import sys
import os
import unittest
import StringIO
import time
import re
import logging
from google.appengine.ext import webapp
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import datastore_file_stub
from google.appengine.ext.webapp.util import run_wsgi_app
_DEFAULT_TEST_DIR = 'test'
##############################################################################
# Main request handler
##############################################################################
class MainTestPageHandler(webapp.RequestHandler):
def get(self):
unknown_args = [arg for arg in self.request.arguments()
if arg not in ("format", "package", "name")]
if len(unknown_args) > 0:
errors = []
for arg in unknown_args:
errors.append(_log_error("The request parameter '%s' is not valid." % arg))
self.error(404)
self.response.out.write(" ".join(errors))
return
format = self.request.get("format", "html")
if format == "html":
self._render_html()
elif format == "plain":
self._render_plain()
else:
error = _log_error("The format '%s' is not valid." % format)
self.error(404)
self.response.out.write(error)
def _render_html(self):
suite, error = _create_suite(self.request)
if not error:
self.response.out.write(_MAIN_PAGE_CONTENT % _test_suite_to_json(suite))
else:
self.error(404)
self.response.out.write(error)
def _render_plain(self):
self.response.headers["Content-Type"] = "text/plain"
runner = unittest.TextTestRunner(self.response.out)
suite, error = _create_suite(self.request)
if not error:
self.response.out.write("====================\n" \
"GAEUnit Test Results\n" \
"====================\n\n")
_run_test_suite(runner, suite)
else:
self.error(404)
self.response.out.write(error)
##############################################################################
# JSON test classes
##############################################################################
class JsonTestResult(unittest.TestResult):
def __init__(self):
unittest.TestResult.__init__(self)
self.testNumber = 0
def render_to(self, stream):
stream.write('{')
stream.write('"runs":"%d", "total":"%d", "errors":"%d", "failures":"%d",' % \
(self.testsRun, self.testNumber,
len(self.errors), len(self.failures)))
stream.write('"details":')
self._render_errors(stream)
stream.write('}')
def _render_errors(self, stream):
stream.write('{')
self._render_error_list('errors', self.errors, stream)
stream.write(',')
self._render_error_list('failures', self.failures, stream)
stream.write('}')
def _render_error_list(self, flavour, errors, stream):
stream.write('"%s":[' % flavour)
for test, err in errors:
stream.write('{"desc":"%s", "detail":"%s"},' %
(self._description(test), self._escape(err)))
if len(errors):
stream.seek(-1, 2)
stream.write("]")
def _description(self, test):
return test.shortDescription() or str(test)
def _escape(self, s):
newstr = re.sub('"', '"', s)
newstr = re.sub('\n', '<br/>', newstr)
return newstr
class JsonTestRunner:
def run(self, test):
self.result = JsonTestResult()
self.result.testNumber = test.countTestCases()
startTime = time.time()
test(self.result)
stopTime = time.time()
timeTaken = stopTime - startTime
return self.result
class JsonTestRunHandler(webapp.RequestHandler):
def get(self):
test_name = self.request.get("name")
_load_default_test_modules()
suite = unittest.defaultTestLoader.loadTestsFromName(test_name)
runner = JsonTestRunner()
_run_test_suite(runner, suite)
runner.result.render_to(self.response.out)
# This is not used by the HTML page, but it may be useful for other client test runners.
class JsonTestListHandler(webapp.RequestHandler):
def get(self):
suite, error = _create_suite(self.request)
if not error:
self.response.out.write(_test_suite_to_json(suite))
else:
self.error(404)
self.response.out.write(error)
##############################################################################
# Module helper functions
##############################################################################
def _create_suite(request):
package_name = request.get("package")
test_name = request.get("name")
loader = unittest.defaultTestLoader
suite = unittest.TestSuite()
if not package_name and not test_name:
modules = _load_default_test_modules()
for module in modules:
suite.addTest(loader.loadTestsFromModule(module))
elif test_name:
try:
_load_default_test_modules()
suite.addTest(loader.loadTestsFromName(test_name))
except:
pass
elif package_name:
try:
package = reload(__import__(package_name))
module_names = package.__all__
for module_name in module_names:
suite.addTest(loader.loadTestsFromName('%s.%s' % (package_name, module_name)))
except:
pass
if suite.countTestCases() == 0:
error = _log_error("'%s' is not found or does not contain any tests." % \
(test_name or package_name))
else:
error = None
return (suite, error)
def _load_default_test_modules():
if not _DEFAULT_TEST_DIR in sys.path:
sys.path.append(_DEFAULT_TEST_DIR)
module_names = [mf[0:-3] for mf in os.listdir(_DEFAULT_TEST_DIR) if mf.endswith(".py")]
return [reload(__import__(name)) for name in module_names]
def _get_tests_from_suite(suite, tests):
for test in suite:
if isinstance(test, unittest.TestSuite):
_get_tests_from_suite(test, tests)
else:
tests.append(test)
def _test_suite_to_json(suite):
tests = []
_get_tests_from_suite(suite, tests)
test_tuples = [(type(test).__module__, type(test).__name__, test._testMethodName) \
for test in tests]
test_dict = {}
for test_tuple in test_tuples:
module_name, class_name, method_name = test_tuple
if module_name not in test_dict:
mod_dict = {}
method_list = []
method_list.append(method_name)
mod_dict[class_name] = method_list
test_dict[module_name] = mod_dict
else:
mod_dict = test_dict[module_name]
if class_name not in mod_dict:
method_list = []
method_list.append(method_name)
mod_dict[class_name] = method_list
else:
method_list = mod_dict[class_name]
method_list.append(method_name)
# Python's dictionary and list string representations happen to match JSON formatting.
return str(test_dict)
def _run_test_suite(runner, suite):
"""Run the test suite.
Preserve the current development apiproxy, create a new apiproxy and
replace the datastore with a temporary one that will be used for this
test suite, run the test suite, and restore the development apiproxy.
This isolates the test datastore from the development datastore.
"""
original_apiproxy = apiproxy_stub_map.apiproxy
try:
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
temp_stub = datastore_file_stub.DatastoreFileStub('GAEUnitDataStore', None, None)
apiproxy_stub_map.apiproxy.RegisterStub('datastore', temp_stub)
# Allow the other services to be used as-is for tests.
for name in ['user', 'urlfetch', 'mail', 'memcache', 'images']:
apiproxy_stub_map.apiproxy.RegisterStub(name, original_apiproxy.GetStub(name))
runner.run(suite)
finally:
apiproxy_stub_map.apiproxy = original_apiproxy
def _log_error(s):
logging.warn(s)
return s
################################################
# Browser HTML, CSS, and Javascript
################################################
# This string uses Python string formatting, so be sure to escape percents as %%.
_MAIN_PAGE_CONTENT = """
<html>
<head>
<style>
body {font-family:arial,sans-serif; text-align:center}
#title {font-family:"Times New Roman","Times Roman",TimesNR,times,serif; font-size:28px; font-weight:bold; text-align:center}
#version {font-size:87%%; text-align:center;}
#weblink {font-style:italic; text-align:center; padding-top:7px; padding-bottom:7px}
#results {padding-top:20px; margin:0pt auto; text-align:center; font-weight:bold}
#testindicator {width:750px; height:16px; border-style:solid; border-width:2px 1px 1px 2px; background-color:#f8f8f8;}
#footerarea {text-align:center; font-size:83%%; padding-top:25px}
#errorarea {padding-top:25px}
.error {border-color: #c3d9ff; border-style: solid; border-width: 2px 1px 2px 1px; width:750px; padding:1px; margin:0pt auto; text-align:left}
.errtitle {background-color:#c3d9ff; font-weight:bold}
</style>
<script language="javascript" type="text/javascript">
var testsToRun = eval("(" + "%s" + ")"); // JSON-formatted (see _test_suite_to_json)
var totalRuns = 0;
var totalErrors = 0;
var totalFailures = 0;
function newXmlHttp() {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}
function requestTestRun(moduleName, className, methodName) {
var methodSuffix = "";
if (methodName) {
methodSuffix = "." + methodName;
}
var xmlHttp = newXmlHttp();
xmlHttp.open("GET", "/testrun?name=" + moduleName + "." + className + methodSuffix, true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState != 4) {
return;
}
if (xmlHttp.status == 200) {
var result = eval("(" + xmlHttp.responseText + ")");
totalRuns += parseInt(result.runs);
totalErrors += parseInt(result.errors);
totalFailures += parseInt(result.failures);
document.getElementById("testran").innerHTML = totalRuns;
document.getElementById("testerror").innerHTML = totalErrors;
document.getElementById("testfailure").innerHTML = totalFailures;
if (totalErrors == 0 && totalFailures == 0) {
testSucceed();
} else {
testFailed();
}
var errors = result.details.errors;
var failures = result.details.failures;
var details = "";
for(var i=0; i<errors.length; i++) {
details += '<p><div class="error"><div class="errtitle">ERROR ' +
errors[i].desc +
'</div><div class="errdetail"><pre>'+errors[i].detail +
'</pre></div></div></p>';
}
for(var i=0; i<failures.length; i++) {
details += '<p><div class="error"><div class="errtitle">FAILURE ' +
failures[i].desc +
'</div><div class="errdetail"><pre>' +
failures[i].detail +
'</pre></div></div></p>';
}
var errorArea = document.getElementById("errorarea");
errorArea.innerHTML += details;
} else {
document.getElementById("errorarea").innerHTML = xmlHttp.responseText;
testFailed();
}
};
xmlHttp.send(null);
}
function testFailed() {
document.getElementById("testindicator").style.backgroundColor="red";
}
function testSucceed() {
document.getElementById("testindicator").style.backgroundColor="green";
}
function runTests() {
// Run each test asynchronously (concurrently).
var totalTests = 0;
for (var moduleName in testsToRun) {
var classes = testsToRun[moduleName];
for (var className in classes) {
// TODO: Optimize for the case where tests are run by class so we don't
// have to always execute each method separately. This should be
// possible when we have a UI that allows the user to select tests
// by module, class, and method.
//requestTestRun(moduleName, className);
methods = classes[className];
for (var i = 0; i < methods.length; i++) {
totalTests += 1;
var methodName = methods[i];
requestTestRun(moduleName, className, methodName);
}
}
}
document.getElementById("testtotal").innerHTML = totalTests;
}
</script>
<title>GAEUnit: Google App Engine Unit Test Framework</title>
</head>
<body onload="runTests()">
<div id="headerarea">
<div id="title">GAEUnit: Google App Engine Unit Test Framework</div>
<div id="version">Version 1.2.4</div>
</div>
<div id="resultarea">
<table id="results"><tbody>
<tr><td colspan="3"><div id="testindicator"> </div></td</tr>
<tr>
<td>Runs: <span id="testran">0</span>/<span id="testtotal">0</span></td>
<td>Errors: <span id="testerror">0</span></td>
<td>Failures: <span id="testfailure">0</span></td>
</tr>
</tbody></table>
</div>
<div id="errorarea"></div>
<div id="footerarea">
<div id="weblink">
<p>
Please visit the <a href="http://code.google.com/p/gaeunit">project home page</a>
for the latest version or to report problems.
</p>
<p>
Copyright 2008 <a href="mailto:George.Z.Lei@Gmail.com">George Lei</a>
and <a href="mailto:srfarley@gmail.com>Steven R. Farley</a>
</p>
</div>
</div>
</body>
</html>
"""
##############################################################################
# Script setup and execution
##############################################################################
application = webapp.WSGIApplication([('/test', MainTestPageHandler),
('/testrun', JsonTestRunHandler),
('/testlist', JsonTestListHandler)],
debug=True)
def main():
if os.environ['SERVER_SOFTWARE'].startswith('Development'):
run_wsgi_app(application)
else:
print 'Status: 404 Not Found'
print 'Content-Type: text/plain'
print ''
print 'Not Found'
return
if __name__ == '__main__':
main()
| apache-2.0 |
zeehio/META-SHARE | metashare/sync/management/commands/synchronize.py | 6 | 11826 | """
Management utility to trigger synchronization.
"""
import logging
import socket
from metashare import settings
from metashare.sync.sync_utils import login, get_inventory, get_full_metadata, \
remove_resource
from django.core.management.base import BaseCommand
from optparse import make_option
from metashare.storage.models import StorageObject, PROXY, REMOTE, add_or_update_resource
from django.core.exceptions import ObjectDoesNotExist
from metashare.utils import Lock
# Setup logging support.
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(settings.LOG_HANDLER)
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('-i', '--id-file', action='store', dest='id_filename',
default=None, help='file for IDs of new/modified resource'),
make_option('-n', '--node', action='store', dest='node',
default=None, help='sync only with specified node'),
)
help = 'Synchronizes with a predefined list of META-SHARE nodes'
def handle(self, *args, **options):
"""
Synchronizes this META-SHARE node with the locally configured other
META-SHARE nodes.
"""
# Check for --id-file option
id_filename = options.get('id_filename', None)
id_file = None
if not id_filename is None:
if len(id_filename) > 0:
try:
id_file = open(id_filename, 'w')
except:
print "Impossible to open file {0}".format(id_filename)
print " IDs will not be printed"
# set a graceful default socket timeout of 30 seconds so that none of
# our connections blocks forever
socket.setdefaulttimeout(30.0)
node_name = options.get('node', None)
if node_name is None:
Command.sync_with_nodes(getattr(settings, 'CORE_NODES', {}), False, id_file)
Command.sync_with_nodes(getattr(settings, 'PROXIED_NODES', {}), True, id_file)
else:
# Synchronize only with the given node
core_nodes = getattr(settings, 'CORE_NODES', {})
for key, value in core_nodes.items():
if value['NAME'] == node_name:
Command.sync_with_nodes({key: value}, False, id_file)
break
proxied_nodes = getattr(settings, 'PROXIED_NODES', {})
for key, value in proxied_nodes.items():
if value['NAME'] == node_name:
Command.sync_with_nodes({key: value}, True, id_file)
break
# Close id file if used
if not id_file is None:
id_file.close()
@staticmethod
def sync_with_nodes(nodes, is_proxy, id_file=None):
"""
Synchronizes this META-SHARE node with the given other META-SHARE nodes.
`nodes` is a dict of dicts with synchronization settings for the nodes
to synchronize with
`is_proxy` must be True if this node is a proxy for the given nodes;
it must be False if the given nodes are not proxied by this node
"""
for node_id, node in nodes.items():
LOGGER.info("syncing with node {} at {} ...".format(
node_id, node['URL']))
try:
# before starting the actual synchronization, make sure to lock
# the storage so that any other processes with heavy/frequent
# operations on the storage don't get in our way
lock = Lock('storage')
lock.acquire()
Command.sync_with_single_node(
node_id, node, is_proxy, id_file=id_file)
except:
LOGGER.error('There was an error while trying to sync with '
'node "%s":', node_id, exc_info=True)
finally:
lock.release()
@staticmethod
def sync_with_single_node(node_id, node, is_proxy, id_file=None):
"""
Synchronizes this META-SHARE node with another META-SHARE node using
the given node description.
`node_id` is the unique key under which the node settings are stored in
the dict
`node` is a dict with synchronization settings for the node to
synchronize with
`is_proxy` must be True if this node is a proxy for the given nodes;
it must be False if the given nodes are not proxied by this node
"""
# login
url = node['URL']
user_name = node['USERNAME']
password = node['PASSWORD']
opener = login("{0}/login/".format(url), user_name, password)
# create inventory url
inv_url = "{0}/sync/?".format(url)
# add sync protocols to url
for index, _prot in enumerate(settings.SYNC_PROTOCOLS):
inv_url = inv_url + "sync_protocol={}".format(_prot)
if (index < len(settings.SYNC_PROTOCOLS) - 1):
inv_url = inv_url + "&"
# get the inventory list
remote_inventory = get_inventory(opener, inv_url)
remote_inventory_count = len(remote_inventory)
LOGGER.info("Remote node {} contains {} resources".format(
node_id, remote_inventory_count))
# create a dictionary of uuid's and digests of resource from the local
# inventory that stem from the remote node
local_inventory = {}
remote_storage_objects = StorageObject.objects.filter(source_node=node_id)
for item in remote_storage_objects:
local_inventory[item.identifier] = item.digest_checksum
local_inventory_count = len(local_inventory)
LOGGER.info("Local node contains {} resources stemming from remote node {}".format(
local_inventory_count, node_id))
# create three lists:
# 1. list of resources to be added - resources that exist in the remote
# inventory but not in the local
# 2. list of resources to be updated - resources that exist in both
# inventories but the remote is different from the local
# 3. list of resources to be removed - resources that exist in the local
# inventory but not in the remote
resources_to_add = []
resources_to_update = []
for remote_res_id, remote_digest in remote_inventory.iteritems():
if remote_res_id in local_inventory:
# compare checksums; if they differ, the resource has to be updated
if remote_digest != local_inventory[remote_res_id]:
resources_to_update.append(remote_res_id)
else:
# resources have the same checksum, nothing to do
pass
# remove the resource from the local inventory; what is left
# in the local inventory after this loop are the resources
# to delete
del local_inventory[remote_res_id]
else:
# resource exists in the remote inventory but not in the local;
# make sure that the remote node does not try to add a resource
# for which we now that it stems from ANOTHER node or OUR node
try:
local_so = StorageObject.objects.get(identifier=remote_res_id)
source_node = local_so.source_node
if not source_node:
source_node = 'LOCAL NODE'
LOGGER.warn(
"Node {} wants to add resource {} that we already know from node {}".format(
node_id, remote_res_id, source_node))
except ObjectDoesNotExist:
resources_to_add.append(remote_res_id)
# remaining local inventory resources are to delete
resources_to_delete = local_inventory.keys()
# print informative messages to the user
resources_to_add_count = len(resources_to_add)
resources_to_update_count = len(resources_to_update)
resources_to_delete_count = len(resources_to_delete)
LOGGER.info("{} resources will be added".format(resources_to_add_count))
LOGGER.info("{} resources will be updated".format(resources_to_update_count))
LOGGER.info("{} resources will be deleted".format(resources_to_delete_count))
if is_proxy:
_copy_status = PROXY
else:
_copy_status = REMOTE
# add resources from remote inventory
num_added = 0
for res_id in resources_to_add:
try:
LOGGER.info("adding resource {0} from node {1}".format(res_id, node_id))
res_obj = Command._get_remote_resource(
res_id, remote_inventory[res_id], node_id, node, opener, _copy_status)
if not id_file is None:
id_file.write("--->RESOURCE_ID:{0};STORAGE_IDENTIFIER:{1}\n"\
.format(res_obj.id, res_obj.storage_object.identifier))
num_added += 1
except:
LOGGER.error("Error while adding resource {}".format(res_id),
exc_info=True)
# update resources from remote inventory
num_updated = 0
for res_id in resources_to_update:
try:
LOGGER.info("updating resource {0} from node {1}".format(res_id, node_id))
res_obj = Command._get_remote_resource(
res_id, remote_inventory[res_id], node_id, node, opener, _copy_status)
if not id_file is None:
id_file.write("--->RESOURCE_ID:{0};STORAGE_IDENTIFIER:{1}\n"\
.format(res_obj.id, res_obj.storage_object.identifier))
if remote_inventory[res_id] != res_obj.storage_object.digest_checksum:
id_file.write("Different digests!\n")
num_updated += 1
except:
LOGGER.error("Error while updating resource {}".format(res_id),
exc_info=True)
# delete resources from remote inventory
num_deleted = 0
for res_id in resources_to_delete:
try:
LOGGER.info("removing resource {0} from node {1}".format(res_id, node_id))
_so_to_remove = StorageObject.objects.get(identifier=res_id)
remove_resource(_so_to_remove)
num_deleted += 1
except:
LOGGER.error("Error while removing resource {}".format(res_id),
exc_info=True)
LOGGER.info("{} of {} resources successfully added." \
.format(num_added, resources_to_add_count))
LOGGER.info("{} of {} resources successfully updated." \
.format(num_updated, resources_to_update_count))
LOGGER.info("{} of {} resources successfully removed." \
.format(num_deleted, resources_to_delete_count))
@staticmethod
def _get_remote_resource(resource_id, resource_digest, node_id, node, opener, copy_status):
"""
Retrieves from the given node the resource for the given id and
adds/updates it at the current node with the given copy status using the
given opener
"""
# Get the json storage object and the actual metadata xml
storage_json, resource_xml_string = \
get_full_metadata(opener, "{0}/sync/{1}/metadata/" \
.format(node['URL'], resource_id), resource_digest)
res_obj = add_or_update_resource(storage_json, resource_xml_string,
resource_digest, copy_status, source_node=node_id)
return res_obj
| bsd-3-clause |
gvb/odoo | addons/account/res_config.py | 200 | 25453 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (C) 2004-2012 OpenERP S.A. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
import datetime
from dateutil.relativedelta import relativedelta
import openerp
from openerp import SUPERUSER_ID
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DF
from openerp.tools.translate import _
from openerp.osv import fields, osv
class account_config_settings(osv.osv_memory):
_name = 'account.config.settings'
_inherit = 'res.config.settings'
_columns = {
'company_id': fields.many2one('res.company', 'Company', required=True),
'has_default_company': fields.boolean('Has default company', readonly=True),
'expects_chart_of_accounts': fields.related('company_id', 'expects_chart_of_accounts', type='boolean',
string='This company has its own chart of accounts',
help="""Check this box if this company is a legal entity."""),
'currency_id': fields.related('company_id', 'currency_id', type='many2one', relation='res.currency', required=True,
string='Default company currency', help="Main currency of the company."),
'paypal_account': fields.related('company_id', 'paypal_account', type='char', size=128,
string='Paypal account', help="Paypal account (email) for receiving online payments (credit card, etc.) If you set a paypal account, the customer will be able to pay your invoices or quotations with a button \"Pay with Paypal\" in automated emails or through the Odoo portal."),
'company_footer': fields.related('company_id', 'rml_footer', type='text', readonly=True,
string='Bank accounts footer preview', help="Bank accounts as printed in the footer of each printed document"),
'has_chart_of_accounts': fields.boolean('Company has a chart of accounts'),
'chart_template_id': fields.many2one('account.chart.template', 'Template', domain="[('visible','=', True)]"),
'code_digits': fields.integer('# of Digits', help="No. of digits to use for account code"),
'tax_calculation_rounding_method': fields.related('company_id',
'tax_calculation_rounding_method', type='selection', selection=[
('round_per_line', 'Round per line'),
('round_globally', 'Round globally'),
], string='Tax calculation rounding method',
help="If you select 'Round per line' : for each tax, the tax amount will first be computed and rounded for each PO/SO/invoice line and then these rounded amounts will be summed, leading to the total amount for that tax. If you select 'Round globally': for each tax, the tax amount will be computed for each PO/SO/invoice line, then these amounts will be summed and eventually this total tax amount will be rounded. If you sell with tax included, you should choose 'Round per line' because you certainly want the sum of your tax-included line subtotals to be equal to the total amount with taxes."),
'sale_tax': fields.many2one("account.tax.template", "Default sale tax"),
'purchase_tax': fields.many2one("account.tax.template", "Default purchase tax"),
'sale_tax_rate': fields.float('Sales tax (%)'),
'purchase_tax_rate': fields.float('Purchase tax (%)'),
'complete_tax_set': fields.boolean('Complete set of taxes', help='This boolean helps you to choose if you want to propose to the user to encode the sales and purchase rates or use the usual m2o fields. This last choice assumes that the set of tax defined for the chosen template is complete'),
'has_fiscal_year': fields.boolean('Company has a fiscal year'),
'date_start': fields.date('Start date', required=True),
'date_stop': fields.date('End date', required=True),
'period': fields.selection([('month', 'Monthly'), ('3months','3 Monthly')], 'Periods', required=True),
'sale_journal_id': fields.many2one('account.journal', 'Sale journal'),
'sale_sequence_prefix': fields.related('sale_journal_id', 'sequence_id', 'prefix', type='char', string='Invoice sequence'),
'sale_sequence_next': fields.related('sale_journal_id', 'sequence_id', 'number_next', type='integer', string='Next invoice number'),
'sale_refund_journal_id': fields.many2one('account.journal', 'Sale refund journal'),
'sale_refund_sequence_prefix': fields.related('sale_refund_journal_id', 'sequence_id', 'prefix', type='char', string='Credit note sequence'),
'sale_refund_sequence_next': fields.related('sale_refund_journal_id', 'sequence_id', 'number_next', type='integer', string='Next credit note number'),
'purchase_journal_id': fields.many2one('account.journal', 'Purchase journal'),
'purchase_sequence_prefix': fields.related('purchase_journal_id', 'sequence_id', 'prefix', type='char', string='Supplier invoice sequence'),
'purchase_sequence_next': fields.related('purchase_journal_id', 'sequence_id', 'number_next', type='integer', string='Next supplier invoice number'),
'purchase_refund_journal_id': fields.many2one('account.journal', 'Purchase refund journal'),
'purchase_refund_sequence_prefix': fields.related('purchase_refund_journal_id', 'sequence_id', 'prefix', type='char', string='Supplier credit note sequence'),
'purchase_refund_sequence_next': fields.related('purchase_refund_journal_id', 'sequence_id', 'number_next', type='integer', string='Next supplier credit note number'),
'module_account_check_writing': fields.boolean('Pay your suppliers by check',
help='This allows you to check writing and printing.\n'
'-This installs the module account_check_writing.'),
'module_account_accountant': fields.boolean('Full accounting features: journals, legal statements, chart of accounts, etc.',
help="""If you do not check this box, you will be able to do invoicing & payments, but not accounting (Journal Items, Chart of Accounts, ...)"""),
'module_account_asset': fields.boolean('Assets management',
help='This allows you to manage the assets owned by a company or a person.\n'
'It keeps track of the depreciation occurred on those assets, and creates account move for those depreciation lines.\n'
'-This installs the module account_asset. If you do not check this box, you will be able to do invoicing & payments, '
'but not accounting (Journal Items, Chart of Accounts, ...)'),
'module_account_budget': fields.boolean('Budget management',
help='This allows accountants to manage analytic and crossovered budgets. '
'Once the master budgets and the budgets are defined, '
'the project managers can set the planned amount on each analytic account.\n'
'-This installs the module account_budget.'),
'module_account_payment': fields.boolean('Manage payment orders',
help='This allows you to create and manage your payment orders, with purposes to \n'
'* serve as base for an easy plug-in of various automated payment mechanisms, and \n'
'* provide a more efficient way to manage invoice payments.\n'
'-This installs the module account_payment.' ),
'module_account_voucher': fields.boolean('Manage customer payments',
help='This includes all the basic requirements of voucher entries for bank, cash, sales, purchase, expense, contra, etc.\n'
'-This installs the module account_voucher.'),
'module_account_followup': fields.boolean('Manage customer payment follow-ups',
help='This allows to automate letters for unpaid invoices, with multi-level recalls.\n'
'-This installs the module account_followup.'),
'module_product_email_template': fields.boolean('Send products tools and information at the invoice confirmation',
help='With this module, link your products to a template to send complete information and tools to your customer.\n'
'For instance when invoicing a training, the training agenda and materials will automatically be send to your customers.'),
'group_proforma_invoices': fields.boolean('Allow pro-forma invoices',
implied_group='account.group_proforma_invoices',
help="Allows you to put invoices in pro-forma state."),
'default_sale_tax': fields.many2one('account.tax', 'Default sale tax',
help="This sale tax will be assigned by default on new products."),
'default_purchase_tax': fields.many2one('account.tax', 'Default purchase tax',
help="This purchase tax will be assigned by default on new products."),
'decimal_precision': fields.integer('Decimal precision on journal entries',
help="""As an example, a decimal precision of 2 will allow journal entries like: 9.99 EUR, whereas a decimal precision of 4 will allow journal entries like: 0.0231 EUR."""),
'group_multi_currency': fields.boolean('Allow multi currencies',
implied_group='base.group_multi_currency',
help="Allows you multi currency environment"),
'group_analytic_accounting': fields.boolean('Analytic accounting',
implied_group='analytic.group_analytic_accounting',
help="Allows you to use the analytic accounting."),
'group_check_supplier_invoice_total': fields.boolean('Check the total of supplier invoices',
implied_group="account.group_supplier_inv_check_total"),
'income_currency_exchange_account_id': fields.related(
'company_id', 'income_currency_exchange_account_id',
type='many2one',
relation='account.account',
string="Gain Exchange Rate Account",
domain="[('type', '=', 'other'), ('company_id', '=', company_id)]]"),
'expense_currency_exchange_account_id': fields.related(
'company_id', 'expense_currency_exchange_account_id',
type="many2one",
relation='account.account',
string="Loss Exchange Rate Account",
domain="[('type', '=', 'other'), ('company_id', '=', company_id)]]"),
}
def _check_account_gain(self, cr, uid, ids, context=None):
for obj in self.browse(cr, uid, ids, context=context):
if obj.income_currency_exchange_account_id.company_id and obj.company_id != obj.income_currency_exchange_account_id.company_id:
return False
return True
def _check_account_loss(self, cr, uid, ids, context=None):
for obj in self.browse(cr, uid, ids, context=context):
if obj.expense_currency_exchange_account_id.company_id and obj.company_id != obj.expense_currency_exchange_account_id.company_id:
return False
return True
_constraints = [
(_check_account_gain, 'The company of the gain exchange rate account must be the same than the company selected.', ['income_currency_exchange_account_id']),
(_check_account_loss, 'The company of the loss exchange rate account must be the same than the company selected.', ['expense_currency_exchange_account_id']),
]
def _default_company(self, cr, uid, context=None):
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
return user.company_id.id
def _default_has_default_company(self, cr, uid, context=None):
count = self.pool.get('res.company').search_count(cr, uid, [], context=context)
return bool(count == 1)
def _get_default_fiscalyear_data(self, cr, uid, company_id, context=None):
"""Compute default period, starting and ending date for fiscalyear
- if in a fiscal year, use its period, starting and ending date
- if past fiscal year, use its period, and new dates [ending date of the latest +1 day ; ending date of the latest +1 year]
- if no fiscal year, use monthly, 1st jan, 31th dec of this year
:return: (date_start, date_stop, period) at format DEFAULT_SERVER_DATETIME_FORMAT
"""
fiscalyear_ids = self.pool.get('account.fiscalyear').search(cr, uid,
[('date_start', '<=', time.strftime(DF)), ('date_stop', '>=', time.strftime(DF)),
('company_id', '=', company_id)])
if fiscalyear_ids:
# is in a current fiscal year, use this one
fiscalyear = self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_ids[0], context=context)
if len(fiscalyear.period_ids) == 5: # 4 periods of 3 months + opening period
period = '3months'
else:
period = 'month'
return (fiscalyear.date_start, fiscalyear.date_stop, period)
else:
past_fiscalyear_ids = self.pool.get('account.fiscalyear').search(cr, uid,
[('date_stop', '<=', time.strftime(DF)), ('company_id', '=', company_id)])
if past_fiscalyear_ids:
# use the latest fiscal, sorted by (start_date, id)
latest_year = self.pool.get('account.fiscalyear').browse(cr, uid, past_fiscalyear_ids[-1], context=context)
latest_stop = datetime.datetime.strptime(latest_year.date_stop, DF)
if len(latest_year.period_ids) == 5:
period = '3months'
else:
period = 'month'
return ((latest_stop+datetime.timedelta(days=1)).strftime(DF), latest_stop.replace(year=latest_stop.year+1).strftime(DF), period)
else:
return (time.strftime('%Y-01-01'), time.strftime('%Y-12-31'), 'month')
_defaults = {
'company_id': _default_company,
'has_default_company': _default_has_default_company,
}
def create(self, cr, uid, values, context=None):
id = super(account_config_settings, self).create(cr, uid, values, context)
# Hack: to avoid some nasty bug, related fields are not written upon record creation.
# Hence we write on those fields here.
vals = {}
for fname, field in self._columns.iteritems():
if isinstance(field, fields.related) and fname in values:
vals[fname] = values[fname]
self.write(cr, uid, [id], vals, context)
return id
def onchange_company_id(self, cr, uid, ids, company_id, context=None):
# update related fields
values = {}
values['currency_id'] = False
if company_id:
company = self.pool.get('res.company').browse(cr, uid, company_id, context=context)
has_chart_of_accounts = company_id not in self.pool.get('account.installer').get_unconfigured_cmp(cr, uid)
fiscalyear_count = self.pool.get('account.fiscalyear').search_count(cr, uid,
[('date_start', '<=', time.strftime('%Y-%m-%d')), ('date_stop', '>=', time.strftime('%Y-%m-%d')),
('company_id', '=', company_id)])
date_start, date_stop, period = self._get_default_fiscalyear_data(cr, uid, company_id, context=context)
values = {
'expects_chart_of_accounts': company.expects_chart_of_accounts,
'currency_id': company.currency_id.id,
'paypal_account': company.paypal_account,
'company_footer': company.rml_footer,
'has_chart_of_accounts': has_chart_of_accounts,
'has_fiscal_year': bool(fiscalyear_count),
'chart_template_id': False,
'tax_calculation_rounding_method': company.tax_calculation_rounding_method,
'date_start': date_start,
'date_stop': date_stop,
'period': period,
}
# update journals and sequences
for journal_type in ('sale', 'sale_refund', 'purchase', 'purchase_refund'):
for suffix in ('_journal_id', '_sequence_prefix', '_sequence_next'):
values[journal_type + suffix] = False
journal_obj = self.pool.get('account.journal')
journal_ids = journal_obj.search(cr, uid, [('company_id', '=', company_id)])
for journal in journal_obj.browse(cr, uid, journal_ids):
if journal.type in ('sale', 'sale_refund', 'purchase', 'purchase_refund'):
values.update({
journal.type + '_journal_id': journal.id,
journal.type + '_sequence_prefix': journal.sequence_id.prefix,
journal.type + '_sequence_next': journal.sequence_id.number_next,
})
# update taxes
ir_values = self.pool.get('ir.values')
taxes_id = ir_values.get_default(cr, uid, 'product.template', 'taxes_id', company_id=company_id)
supplier_taxes_id = ir_values.get_default(cr, uid, 'product.template', 'supplier_taxes_id', company_id=company_id)
values.update({
'default_sale_tax': isinstance(taxes_id, list) and taxes_id[0] or taxes_id,
'default_purchase_tax': isinstance(supplier_taxes_id, list) and supplier_taxes_id[0] or supplier_taxes_id,
})
# update gain/loss exchange rate accounts
values.update({
'income_currency_exchange_account_id': company.income_currency_exchange_account_id and company.income_currency_exchange_account_id.id or False,
'expense_currency_exchange_account_id': company.expense_currency_exchange_account_id and company.expense_currency_exchange_account_id.id or False
})
return {'value': values}
def onchange_chart_template_id(self, cr, uid, ids, chart_template_id, context=None):
tax_templ_obj = self.pool.get('account.tax.template')
res = {'value': {
'complete_tax_set': False, 'sale_tax': False, 'purchase_tax': False,
'sale_tax_rate': 15, 'purchase_tax_rate': 15,
}}
if chart_template_id:
# update complete_tax_set, sale_tax and purchase_tax
chart_template = self.pool.get('account.chart.template').browse(cr, uid, chart_template_id, context=context)
res['value'].update({'complete_tax_set': chart_template.complete_tax_set})
if chart_template.complete_tax_set:
# default tax is given by the lowest sequence. For same sequence we will take the latest created as it will be the case for tax created while isntalling the generic chart of account
sale_tax_ids = tax_templ_obj.search(cr, uid,
[("chart_template_id", "=", chart_template_id), ('type_tax_use', 'in', ('sale','all'))],
order="sequence, id desc")
purchase_tax_ids = tax_templ_obj.search(cr, uid,
[("chart_template_id", "=", chart_template_id), ('type_tax_use', 'in', ('purchase','all'))],
order="sequence, id desc")
res['value']['sale_tax'] = sale_tax_ids and sale_tax_ids[0] or False
res['value']['purchase_tax'] = purchase_tax_ids and purchase_tax_ids[0] or False
if chart_template.code_digits:
res['value']['code_digits'] = chart_template.code_digits
return res
def onchange_tax_rate(self, cr, uid, ids, rate, context=None):
return {'value': {'purchase_tax_rate': rate or False}}
def onchange_multi_currency(self, cr, uid, ids, group_multi_currency, context=None):
res = {}
if not group_multi_currency:
res['value'] = {'income_currency_exchange_account_id': False, 'expense_currency_exchange_account_id': False}
return res
def onchange_start_date(self, cr, uid, id, start_date):
if start_date:
start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
end_date = (start_date + relativedelta(months=12)) - relativedelta(days=1)
return {'value': {'date_stop': end_date.strftime('%Y-%m-%d')}}
return {}
def open_company_form(self, cr, uid, ids, context=None):
config = self.browse(cr, uid, ids[0], context)
return {
'type': 'ir.actions.act_window',
'name': 'Configure your Company',
'res_model': 'res.company',
'res_id': config.company_id.id,
'view_mode': 'form',
}
def set_default_taxes(self, cr, uid, ids, context=None):
""" set default sale and purchase taxes for products """
if uid != SUPERUSER_ID and not self.pool['res.users'].has_group(cr, uid, 'base.group_erp_manager'):
raise openerp.exceptions.AccessError(_("Only administrators can change the settings"))
ir_values = self.pool.get('ir.values')
config = self.browse(cr, uid, ids[0], context)
ir_values.set_default(cr, SUPERUSER_ID, 'product.template', 'taxes_id',
config.default_sale_tax and [config.default_sale_tax.id] or False, company_id=config.company_id.id)
ir_values.set_default(cr, SUPERUSER_ID, 'product.template', 'supplier_taxes_id',
config.default_purchase_tax and [config.default_purchase_tax.id] or False, company_id=config.company_id.id)
def set_chart_of_accounts(self, cr, uid, ids, context=None):
""" install a chart of accounts for the given company (if required) """
config = self.browse(cr, uid, ids[0], context)
if config.chart_template_id:
assert config.expects_chart_of_accounts and not config.has_chart_of_accounts
wizard = self.pool.get('wizard.multi.charts.accounts')
wizard_id = wizard.create(cr, uid, {
'company_id': config.company_id.id,
'chart_template_id': config.chart_template_id.id,
'code_digits': config.code_digits or 6,
'sale_tax': config.sale_tax.id,
'purchase_tax': config.purchase_tax.id,
'sale_tax_rate': config.sale_tax_rate,
'purchase_tax_rate': config.purchase_tax_rate,
'complete_tax_set': config.complete_tax_set,
'currency_id': config.currency_id.id,
}, context)
wizard.execute(cr, uid, [wizard_id], context)
def set_fiscalyear(self, cr, uid, ids, context=None):
""" create a fiscal year for the given company (if necessary) """
config = self.browse(cr, uid, ids[0], context)
if config.has_chart_of_accounts or config.chart_template_id:
fiscalyear = self.pool.get('account.fiscalyear')
fiscalyear_count = fiscalyear.search_count(cr, uid,
[('date_start', '<=', config.date_start), ('date_stop', '>=', config.date_stop),
('company_id', '=', config.company_id.id)],
context=context)
if not fiscalyear_count:
name = code = config.date_start[:4]
if int(name) != int(config.date_stop[:4]):
name = config.date_start[:4] +'-'+ config.date_stop[:4]
code = config.date_start[2:4] +'-'+ config.date_stop[2:4]
vals = {
'name': name,
'code': code,
'date_start': config.date_start,
'date_stop': config.date_stop,
'company_id': config.company_id.id,
}
fiscalyear_id = fiscalyear.create(cr, uid, vals, context=context)
if config.period == 'month':
fiscalyear.create_period(cr, uid, [fiscalyear_id])
elif config.period == '3months':
fiscalyear.create_period3(cr, uid, [fiscalyear_id])
def get_default_dp(self, cr, uid, fields, context=None):
dp = self.pool.get('ir.model.data').get_object(cr, uid, 'product','decimal_account')
return {'decimal_precision': dp.digits}
def set_default_dp(self, cr, uid, ids, context=None):
config = self.browse(cr, uid, ids[0], context)
dp = self.pool.get('ir.model.data').get_object(cr, uid, 'product','decimal_account')
dp.write({'digits': config.decimal_precision})
def onchange_analytic_accounting(self, cr, uid, ids, analytic_accounting, context=None):
if analytic_accounting:
return {'value': {
'module_account_accountant': True,
}}
return {}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
inclement/vispy | examples/basics/gloo/animate_images_slice.py | 18 | 4149 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Irwin Zaid
# vispy: gallery 2
"""
Example demonstrating a 3D Texture. The volume contains noise that
is smoothed in the z-direction. Shown is one slice throught that volume
to give the effect of "morphing" noise.
"""
import numpy as np
from vispy.util.transforms import ortho
from vispy import gloo
from vispy import app
from vispy.visuals.shaders import ModularProgram
# Shape of image to be displayed
D, H, W = 30, 60, 90
# Modulated image
I = np.random.uniform(0, 0.1, (D, H, W, 3)).astype(np.float32)
# Depth slices are dark->light
I[...] += np.linspace(0, 0.9, D)[:, np.newaxis, np.newaxis, np.newaxis]
# Make vertical direction more green moving upward
I[..., 1] *= np.linspace(0, 1, H)[np.newaxis, :, np.newaxis]
# Make horizontal direction more red moving rightward
I[..., 0] *= np.linspace(0, 1, W)[np.newaxis, np.newaxis, :]
# A simple texture quad
data = np.zeros(4, dtype=[('a_position', np.float32, 2),
('a_texcoord', np.float32, 2)])
data['a_position'] = np.array([[0, 0], [W, 0], [0, H], [W, H]])
data['a_texcoord'] = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
VERT_SHADER = """
// Uniforms
uniform mat4 u_model;
uniform mat4 u_view;
uniform mat4 u_projection;
// Attributes
attribute vec2 a_position;
attribute vec2 a_texcoord;
// Varyings
varying vec2 v_texcoord;
// Main
void main (void)
{
v_texcoord = a_texcoord;
gl_Position = u_projection * u_view * u_model * vec4(a_position,0.0,1.0);
}
"""
FRAG_SHADER = """
uniform $sampler_type u_texture;
uniform float i;
varying vec2 v_texcoord;
void main()
{
// step through gradient with i, note that slice (depth) comes last here!
gl_FragColor = $sample(u_texture, vec3(v_texcoord, i));
gl_FragColor.a = 1.0;
}
"""
class Canvas(app.Canvas):
def __init__(self, emulate3d=True):
app.Canvas.__init__(self, keys='interactive', size=((W*5), (H*5)))
if emulate3d:
tex_cls = gloo.TextureEmulated3D
else:
tex_cls = gloo.Texture3D
self.texture = tex_cls(I, interpolation='nearest',
wrapping='clamp_to_edge')
self.program = ModularProgram(VERT_SHADER, FRAG_SHADER)
self.program.frag['sampler_type'] = self.texture.glsl_sampler_type
self.program.frag['sample'] = self.texture.glsl_sample
self.program['u_texture'] = self.texture
self.program['i'] = 0.0
self.program.bind(gloo.VertexBuffer(data))
self.view = np.eye(4, dtype=np.float32)
self.model = np.eye(4, dtype=np.float32)
self.projection = np.eye(4, dtype=np.float32)
self.program['u_model'] = self.model
self.program['u_view'] = self.view
self.projection = ortho(0, W, 0, H, -1, 1)
self.program['u_projection'] = self.projection
self.i = 0
gloo.set_clear_color('white')
self._timer = app.Timer('auto', connect=self.on_timer, start=True)
self.show()
def on_resize(self, event):
width, height = event.physical_size
gloo.set_viewport(0, 0, width, height)
self.projection = ortho(0, width, 0, height, -100, 100)
self.program['u_projection'] = self.projection
# Compute the new size of the quad
r = width / float(height)
R = W / float(H)
if r < R:
w, h = width, width / R
x, y = 0, int((height - h) / 2)
else:
w, h = height * R, height
x, y = int((width - w) / 2), 0
data['a_position'] = np.array(
[[x, y], [x + w, y], [x, y + h], [x + w, y + h]])
self.program.bind(gloo.VertexBuffer(data))
def on_timer(self, event):
# cycle every 2 sec
self.i = (self.i + 1./120.) % 1.0
self.update()
def on_draw(self, event):
gloo.clear(color=True, depth=True)
self.program['i'] = 1.9 * np.abs(0.5 - self.i)
self.program.draw('triangle_strip')
if __name__ == '__main__':
# Use emulated3d to switch from an emulated 3D texture to an actual one
c = Canvas(emulate3d=True)
app.run()
| bsd-3-clause |
mdjurfeldt/nest-simulator | pynest/nest/tests/test_sp/test_get_sp_status.py | 5 | 3009 | # -*- coding: utf-8 -*-
#
# test_get_sp_status.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# NEST is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
"""
Structural Plasticity GetStatus Test
-----------------------
This tests the functionality of the GetStructuralPlasticityStatus
function
"""
import nest
import unittest
__author__ = 'sdiaz'
class TestGetStructuralPlasticityStatus(unittest.TestCase):
neuron_model = 'iaf_psc_alpha'
nest.CopyModel('static_synapse', 'synapse_ex')
nest.SetDefaults('synapse_ex', {'weight': 1.0, 'delay': 1.0})
nest.SetStructuralPlasticityStatus({
'structural_plasticity_synapses': {
'synapse_ex': {
'model': 'synapse_ex',
'post_synaptic_element': 'Den_ex',
'pre_synaptic_element': 'Axon_ex',
},
}
})
growth_curve = {
'growth_curve': "gaussian",
'growth_rate': 0.0001, # (elements/ms)
'continuous': False,
'eta': 0.0, # Ca2+
'eps': 0.05
}
'''
Now we assign the growth curves to the corresponding synaptic
elements
'''
synaptic_elements = {
'Den_ex': growth_curve,
'Den_in': growth_curve,
'Axon_ex': growth_curve,
}
nodes = nest.Create(neuron_model,
2,
{'synaptic_elements': synaptic_elements}
)
all = nest.GetStructuralPlasticityStatus()
print (all)
assert ('structural_plasticity_synapses' in all)
assert ('syn1' in all['structural_plasticity_synapses'])
assert ('structural_plasticity_update_interval' in all)
assert (all['structural_plasticity_update_interval'] == 1000)
sp_synapses = nest.GetStructuralPlasticityStatus(
'structural_plasticity_synapses'
)
print (sp_synapses)
syn = sp_synapses['syn1']
assert ('pre_synaptic_element' in syn)
assert ('post_synaptic_element' in syn)
assert (syn['pre_synaptic_element'] == 'Axon_ex')
assert (syn['post_synaptic_element'] == 'Den_ex')
sp_interval = nest.GetStructuralPlasticityStatus(
'structural_plasticity_update_interval'
)
print (sp_interval)
assert (sp_interval == 1000)
def suite():
test_suite = unittest.makeSuite(
TestGetStructuralPlasticityStatus,
'test'
)
return test_suite
if __name__ == '__main__':
unittest.main()
| gpl-2.0 |
wavelets/ThinkStats2 | code/moments.py | 1 | 1149 | """This file contains code for use with "Think Bayes",
by Allen B. Downey, available from greenteapress.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import math
import thinkstats2
def RawMoment(xs, k):
return sum(x**k for x in xs) / float(len(xs))
def CentralMoment(xs, k):
xbar = RawMoment(xs, 1)
return sum((x - xbar)**k for x in xs) / len(xs)
def StandardizedMoment(xs, k):
var = CentralMoment(xs, 2)
sigma = math.sqrt(var)
return CentralMoment(xs, k) / sigma**k
def Skewness(xs):
return StandardizedMoment(xs, 3)
def Median(xs):
cdf = thinkstats2.MakeCdfFromList(xs)
return cdf.Value(0.5)
def PearsonMedianSkewness(xs):
median = Median(xs)
mean = RawMoment(xs, 1)
var = CentralMoment(xs, 2)
std = math.sqrt(var)
gp = 3 * (mean - median) / std
return gp
def main():
xs = range(10)
print 'mean', RawMoment(xs, 1)
print 'median', Median(xs)
print 'var', CentralMoment(xs, 2)
print 'skewness', Skewness(xs)
print 'Pearson skewness', PearsonMedianSkewness(xs)
if __name__ == '__main__':
main()
| gpl-3.0 |
flavour/Turkey | modules/s3db/delphi.py | 12 | 22626 | # -*- coding: utf-8 -*-
""" Sahana Eden Delphi Decision Maker Model
@copyright: 2009-2015 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
__all__ = ("S3DelphiModel",
"S3DelphiUser",
)
from gluon import *
from gluon.storage import Storage
from ..s3 import *
# =============================================================================
class S3DelphiModel(S3Model):
"""
Delphi Decision Maker
"""
names = ("delphi_group",
"delphi_membership",
"delphi_problem",
"delphi_solution",
"delphi_vote",
"delphi_comment",
"delphi_solution_represent",
"delphi_DelphiUser",
)
def model(self):
T = current.T
db = current.db
messages = current.messages
NONE = messages["NONE"]
UNKNOWN_OPT = messages.UNKNOWN_OPT
add_components = self.add_components
configure = self.configure
crud_strings = current.response.s3.crud_strings
define_table = self.define_table
# ---------------------------------------------------------------------
# Groups
# ---------------------------------------------------------------------
tablename = "delphi_group"
define_table(tablename,
Field("name", length=255, notnull=True, unique=True,
label = T("Group Title"),
),
Field("description", "text",
label = T("Description"),
),
Field("active", "boolean", default=True,
label = T("Active"),
represent = s3_yes_no_represent,
),
*s3_meta_fields()
)
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Create Group"),
title_display = T("Group Details"),
title_list = T("Groups"),
title_update = T("Edit Group"),
label_list_button = T("List Groups"),
label_delete_button = T("Delete Group"),
msg_record_created = T("Group added"),
msg_record_modified = T("Group updated"),
msg_record_deleted = T("Group deleted"),
msg_list_empty = T("No Groups currently defined"))
configure(tablename,
deduplicate = self.group_duplicate,
list_fields = ["id",
"name",
"description",
],
)
# Components
add_components(tablename,
delphi_membership = "group_id",
delphi_problem = "group_id",
)
group_id = S3ReusableField("group_id", "reference %s" % tablename,
notnull=True,
label = T("Problem Group"),
represent = self.delphi_group_represent,
requires = IS_ONE_OF(db, "delphi_group.id",
self.delphi_group_represent
),
)
user_id = S3ReusableField("user_id", current.auth.settings.table_user,
notnull=True,
label = T("User"),
represent = s3_auth_user_represent,
requires = IS_ONE_OF(db, "auth_user.id",
s3_auth_user_represent),
)
# ---------------------------------------------------------------------
# Group Membership
# ---------------------------------------------------------------------
delphi_role_opts = {
1:T("Guest"),
2:T("Contributor"),
3:T("Participant"),
4:T("Moderator")
}
tablename = "delphi_membership"
define_table(tablename,
group_id(),
user_id(),
Field("description",
label = T("Description"),
),
# @ToDo: Change how Membership Requests work
Field("req", "boolean",
default = False,
label = T("Request"), # Membership Request
represent = s3_yes_no_represent,
),
Field("status", "integer",
default = 3,
label = T("Status"),
represent = lambda opt: \
delphi_role_opts.get(opt, UNKNOWN_OPT),
requires = IS_IN_SET(delphi_role_opts,
zero=None),
comment = DIV(_class="tooltip",
_title="%s|%s|%s|%s|%s" % (T("Status"),
T("Guests can view all details"),
T("A Contributor can additionally Post comments to the proposed Solutions & add alternative Solutions"),
T("A Participant can additionally Vote"),
T("A Moderator can additionally create Problems & control Memberships")))
),
*s3_meta_fields()
)
# CRUD strings
crud_strings[tablename] = Storage(
label_create = T("Add Member"),
title_display = T("Membership Details"),
title_list = T("Group Members"),
title_update = T("Edit Membership"),
label_list_button = T("List Members"),
label_delete_button = T("Remove Person from Group"),
msg_record_created = T("Person added to Group"),
msg_record_modified = T("Membership updated"),
msg_record_deleted = T("Person removed from Group"),
msg_list_empty = T("This Group has no Members yet"))
configure(tablename,
list_fields = ["id",
"group_id",
"user_id",
"status",
"req",
],
)
# ---------------------------------------------------------------------
# Problems
# ---------------------------------------------------------------------
tablename = "delphi_problem"
define_table(tablename,
group_id(),
Field("code", length=8,
label = T("Problem Code"),
represent = lambda v: v or NONE,
),
Field("name", length=255, notnull=True, unique=True,
label = T("Problem Title"),
),
Field("description", "text",
label = T("Description"),
represent = s3_comments_represent,
),
Field("criteria", "text", notnull=True,
label = T("Criteria"),
),
Field("active", "boolean",
default = True,
label = T("Active"),
represent = s3_yes_no_represent,
),
*s3_meta_fields()
)
# @todo: make lazy_table
table = db[tablename]
table.modified_on.label = T("Last Modification")
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Add Problem"),
title_display = T("Problem Details"),
title_list = T("Problems"),
title_update = T("Edit Problem"),
label_list_button = T("List Problems"),
label_delete_button = T("Delete Problem"),
msg_record_created = T("Problem added"),
msg_record_modified = T("Problem updated"),
msg_record_deleted = T("Problem deleted"),
msg_list_empty = T("No Problems currently defined"))
configure(tablename,
deduplicate = self.problem_duplicate,
list_fields = ["id",
"group_id",
"code",
"name",
"description",
"created_by",
"modified_on",
],
orderby = table.code,
)
# Components
add_components(tablename,
delphi_solution = "problem_id",
)
problem_id = S3ReusableField("problem_id", "reference %s" % tablename,
notnull=True,
label = T("Problem"),
represent = self.delphi_problem_represent,
requires = IS_ONE_OF(db, "delphi_problem.id",
self.delphi_problem_represent
),
)
# ---------------------------------------------------------------------
# Solutions
# ---------------------------------------------------------------------
tablename = "delphi_solution"
define_table(tablename,
problem_id(),
Field("name",
label = T("Title"),
requires = IS_NOT_EMPTY(),
),
Field("description", "text",
label = T("Description"),
represent = s3_comments_represent,
),
Field("changes", "integer",
default = 0,
label = T("Changes"),
writable = False,
),
Field.Method("comments",
delphi_solution_comments),
Field.Method("votes",
delphi_solution_votes),
*s3_meta_fields()
)
# @todo: make lazy_table
table = db[tablename]
table.created_by.label = T("Suggested By")
table.modified_on.label = T("Last Modification")
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Add Solution"),
title_display = T("Solution Details"),
title_list = T("Solutions"),
title_update = T("Edit Solution"),
label_list_button = T("List Solutions"),
label_delete_button = T("Delete Solution"),
msg_record_created = T("Solution added"),
msg_record_modified = T("Solution updated"),
msg_record_deleted = T("Solution deleted"),
msg_list_empty = T("No Solutions currently defined"))
configure(tablename,
extra_fields = ["problem_id"],
list_fields = ["id",
#"problem_id",
"name",
"description",
"created_by",
"modified_on",
(T("Voted on"), "votes"),
(T("Comments"), "comments"),
],
)
solution_represent = S3Represent(lookup=tablename)
solution_id = S3ReusableField("solution_id", "reference %s" % tablename,
label = T("Solution"),
represent = solution_represent,
requires = IS_EMPTY_OR(
IS_ONE_OF(db, "delphi_solution.id",
solution_represent
)),
)
# ---------------------------------------------------------------------
# Votes
# ---------------------------------------------------------------------
tablename = "delphi_vote"
define_table(tablename,
problem_id(),
solution_id(empty = False),
Field("rank", "integer",
label = T("Rank"),
),
*s3_meta_fields()
)
# ---------------------------------------------------------------------
# Comments
# @ToDo: Attachments?
#
# Parent field allows us to:
# * easily filter for top-level threads
# * easily filter for next level of threading
# * hook a new reply into the correct location in the hierarchy
#
# ---------------------------------------------------------------------
tablename = "delphi_comment"
define_table(tablename,
Field("parent", "reference delphi_comment",
requires = IS_EMPTY_OR(
IS_ONE_OF_EMPTY(db, "delphi_comment.id")),
readable=False,
),
problem_id(),
# @ToDo: Tag to 1+ Solutions
#solution_multi_id(),
solution_id(),
Field("body", "text", notnull=True,
label = T("Comment"),
),
*s3_meta_fields()
)
configure(tablename,
list_fields = ["id",
"problem_id",
"solution_id",
"created_by",
"modified_on",
],
)
# ---------------------------------------------------------------------
# Pass names back to global scope (s3.*)
return dict(delphi_solution_represent = solution_represent,
delphi_DelphiUser = S3DelphiUser,
)
# -------------------------------------------------------------------------
@staticmethod
def delphi_group_represent(id, row=None):
""" FK representation """
if not row:
db = current.db
table = db.delphi_group
row = db(table.id == id).select(table.id,
table.name,
limitby = (0, 1)).first()
elif not id:
return current.messages["NONE"]
try:
return A(row.name,
_href=URL(c="delphi",
f="group",
args=[row.id]))
except:
return current.messages.UNKNOWN_OPT
# ---------------------------------------------------------------------
@staticmethod
def delphi_problem_represent(id, row=None, show_link=False,
solutions=True):
""" FK representation """
if not row:
db = current.db
table = db.delphi_problem
row = db(table.id == id).select(table.id,
table.name,
limitby = (0, 1)).first()
elif not id:
return current.messages["NONE"]
try:
if show_link:
if solutions:
url = URL(c="delphi", f="problem", args=[row.id, "solution"])
else:
url = URL(c="delphi", f="problem", args=[row.id])
return A(row.name, _href=url)
else:
return row.name
except:
return current.messages.UNKNOWN_OPT
# ---------------------------------------------------------------------
@staticmethod
def group_duplicate(item):
"""
This callback will be called when importing records
it will look to see if the record being imported is a duplicate.
@param item: An S3ImportItem object which includes all the details
of the record being imported
If the record is a duplicate then it will set the item method to update
Rules for finding a duplicate:
- Look for a record with the same name, ignoring case
"""
table = item.table
data = item.data
name = "name" in data and data.name
query = (table.name.lower() == name.lower())
duplicate = current.db(query).select(table.id,
limitby=(0, 1)).first()
if duplicate:
item.id = duplicate.id
item.method = item.METHOD.UPDATE
# ---------------------------------------------------------------------
@staticmethod
def problem_duplicate(item):
"""
This callback will be called when importing records
it will look to see if the record being imported is a duplicate.
@param item: An S3ImportItem object which includes all the details
of the record being imported
If the record is a duplicate then it will set the item method to update
Rules for finding a duplicate:
- Look for a record with the same name, ignoring case
"""
table = item.table
name = "name" in item.data and item.data.name
query = (table.name.lower() == name.lower())
duplicate = current.db(query).select(table.id,
limitby=(0, 1)).first()
if duplicate:
item.id = duplicate.id
item.method = item.METHOD.UPDATE
# =============================================================================
def delphi_solution_comments(row):
""" Clickable number of comments for a solution, virtual field """
if hasattr(row, "delphi_solution"):
row = row.delphi_solution
try:
solution_id = row.id
problem_id = row.problem_id
except AttributeError:
return None
ctable = current.s3db.delphi_comment
query = (ctable.solution_id == solution_id)
comments = current.db(query).count()
url = URL(c="delphi", f="problem",
args=[problem_id, "solution", solution_id, "discuss"])
return A(comments, _href=url)
def delphi_solution_votes(row):
""" Clickable number of solutions for a problem, virtual field """
if hasattr(row, "delphi_solution"):
row = row.delphi_solution
try:
solution_id = row.id
problem_id = row.problem_id
except AttributeError:
return None
vtable = current.s3db.delphi_vote
query = (vtable.solution_id == solution_id)
votes = current.db(query).count()
url = URL(c="delphi", f="problem",
args=[problem_id, "results"])
return A(votes, _href=url)
# =============================================================================
class S3DelphiUser:
""" Delphi User class """
def user(self):
""" Used by Discuss() (& summary()) """
return current.s3db.auth_user[self.user_id]
def __init__(self, group_id=None):
auth = current.auth
user_id = auth.user.id if auth.is_logged_in() else None
status = 1 # guest
membership = None
if auth.s3_has_role("DelphiAdmin"):
# DelphiAdmin is Moderator for every Group
status = 4
elif user_id != None and group_id != None:
table = current.s3db.delphi_membership
query = (table.group_id == group_id) & \
(table.user_id == user_id)
membership = current.db(query).select()
if membership:
membership = membership[0]
status = membership.status
self.authorised = (status == 4)
# Only Moderators & Participants can Vote
self.can_vote = status in (3, 4)
# All but Guests can add Solutions & Discuss
self.can_add_item = status != 1
self.can_post = status != 1
self.membership = membership
self.status = status
self.user_id = user_id
# END =========================================================================
| mit |
shinglyu/servo | tests/wpt/web-platform-tests/tools/pywebsocket/src/test/test_msgutil.py | 413 | 54959 | #!/usr/bin/env python
#
# Copyright 2012, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests for msgutil module."""
import array
import Queue
import random
import struct
import unittest
import zlib
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from mod_pywebsocket import common
from mod_pywebsocket.extensions import DeflateFrameExtensionProcessor
from mod_pywebsocket.extensions import PerMessageCompressExtensionProcessor
from mod_pywebsocket.extensions import PerMessageDeflateExtensionProcessor
from mod_pywebsocket import msgutil
from mod_pywebsocket.stream import InvalidUTF8Exception
from mod_pywebsocket.stream import Stream
from mod_pywebsocket.stream import StreamHixie75
from mod_pywebsocket.stream import StreamOptions
from mod_pywebsocket import util
from test import mock
# We use one fixed nonce for testing instead of cryptographically secure PRNG.
_MASKING_NONCE = 'ABCD'
def _mask_hybi(frame):
frame_key = map(ord, _MASKING_NONCE)
frame_key_len = len(frame_key)
result = array.array('B')
result.fromstring(frame)
count = 0
for i in xrange(len(result)):
result[i] ^= frame_key[count]
count = (count + 1) % frame_key_len
return _MASKING_NONCE + result.tostring()
def _install_extension_processor(processor, request, stream_options):
response = processor.get_extension_response()
if response is not None:
processor.setup_stream_options(stream_options)
request.ws_extension_processors.append(processor)
def _create_request_from_rawdata(
read_data,
deflate_frame_request=None,
permessage_compression_request=None,
permessage_deflate_request=None):
req = mock.MockRequest(connection=mock.MockConn(''.join(read_data)))
req.ws_version = common.VERSION_HYBI_LATEST
req.ws_extension_processors = []
processor = None
if deflate_frame_request is not None:
processor = DeflateFrameExtensionProcessor(deflate_frame_request)
elif permessage_compression_request is not None:
processor = PerMessageCompressExtensionProcessor(
permessage_compression_request)
elif permessage_deflate_request is not None:
processor = PerMessageDeflateExtensionProcessor(
permessage_deflate_request)
stream_options = StreamOptions()
if processor is not None:
_install_extension_processor(processor, req, stream_options)
req.ws_stream = Stream(req, stream_options)
return req
def _create_request(*frames):
"""Creates MockRequest using data given as frames.
frames will be returned on calling request.connection.read() where request
is MockRequest returned by this function.
"""
read_data = []
for (header, body) in frames:
read_data.append(header + _mask_hybi(body))
return _create_request_from_rawdata(read_data)
def _create_blocking_request():
"""Creates MockRequest.
Data written to a MockRequest can be read out by calling
request.connection.written_data().
"""
req = mock.MockRequest(connection=mock.MockBlockingConn())
req.ws_version = common.VERSION_HYBI_LATEST
stream_options = StreamOptions()
req.ws_stream = Stream(req, stream_options)
return req
def _create_request_hixie75(read_data=''):
req = mock.MockRequest(connection=mock.MockConn(read_data))
req.ws_stream = StreamHixie75(req)
return req
def _create_blocking_request_hixie75():
req = mock.MockRequest(connection=mock.MockBlockingConn())
req.ws_stream = StreamHixie75(req)
return req
class BasicMessageTest(unittest.TestCase):
"""Basic tests for Stream."""
def test_send_message(self):
request = _create_request()
msgutil.send_message(request, 'Hello')
self.assertEqual('\x81\x05Hello', request.connection.written_data())
payload = 'a' * 125
request = _create_request()
msgutil.send_message(request, payload)
self.assertEqual('\x81\x7d' + payload,
request.connection.written_data())
def test_send_medium_message(self):
payload = 'a' * 126
request = _create_request()
msgutil.send_message(request, payload)
self.assertEqual('\x81\x7e\x00\x7e' + payload,
request.connection.written_data())
payload = 'a' * ((1 << 16) - 1)
request = _create_request()
msgutil.send_message(request, payload)
self.assertEqual('\x81\x7e\xff\xff' + payload,
request.connection.written_data())
def test_send_large_message(self):
payload = 'a' * (1 << 16)
request = _create_request()
msgutil.send_message(request, payload)
self.assertEqual('\x81\x7f\x00\x00\x00\x00\x00\x01\x00\x00' + payload,
request.connection.written_data())
def test_send_message_unicode(self):
request = _create_request()
msgutil.send_message(request, u'\u65e5')
# U+65e5 is encoded as e6,97,a5 in UTF-8
self.assertEqual('\x81\x03\xe6\x97\xa5',
request.connection.written_data())
def test_send_message_fragments(self):
request = _create_request()
msgutil.send_message(request, 'Hello', False)
msgutil.send_message(request, ' ', False)
msgutil.send_message(request, 'World', False)
msgutil.send_message(request, '!', True)
self.assertEqual('\x01\x05Hello\x00\x01 \x00\x05World\x80\x01!',
request.connection.written_data())
def test_send_fragments_immediate_zero_termination(self):
request = _create_request()
msgutil.send_message(request, 'Hello World!', False)
msgutil.send_message(request, '', True)
self.assertEqual('\x01\x0cHello World!\x80\x00',
request.connection.written_data())
def test_receive_message(self):
request = _create_request(
('\x81\x85', 'Hello'), ('\x81\x86', 'World!'))
self.assertEqual('Hello', msgutil.receive_message(request))
self.assertEqual('World!', msgutil.receive_message(request))
payload = 'a' * 125
request = _create_request(('\x81\xfd', payload))
self.assertEqual(payload, msgutil.receive_message(request))
def test_receive_medium_message(self):
payload = 'a' * 126
request = _create_request(('\x81\xfe\x00\x7e', payload))
self.assertEqual(payload, msgutil.receive_message(request))
payload = 'a' * ((1 << 16) - 1)
request = _create_request(('\x81\xfe\xff\xff', payload))
self.assertEqual(payload, msgutil.receive_message(request))
def test_receive_large_message(self):
payload = 'a' * (1 << 16)
request = _create_request(
('\x81\xff\x00\x00\x00\x00\x00\x01\x00\x00', payload))
self.assertEqual(payload, msgutil.receive_message(request))
def test_receive_length_not_encoded_using_minimal_number_of_bytes(self):
# Log warning on receiving bad payload length field that doesn't use
# minimal number of bytes but continue processing.
payload = 'a'
# 1 byte can be represented without extended payload length field.
request = _create_request(
('\x81\xff\x00\x00\x00\x00\x00\x00\x00\x01', payload))
self.assertEqual(payload, msgutil.receive_message(request))
def test_receive_message_unicode(self):
request = _create_request(('\x81\x83', '\xe6\x9c\xac'))
# U+672c is encoded as e6,9c,ac in UTF-8
self.assertEqual(u'\u672c', msgutil.receive_message(request))
def test_receive_message_erroneous_unicode(self):
# \x80 and \x81 are invalid as UTF-8.
request = _create_request(('\x81\x82', '\x80\x81'))
# Invalid characters should raise InvalidUTF8Exception
self.assertRaises(InvalidUTF8Exception,
msgutil.receive_message,
request)
def test_receive_fragments(self):
request = _create_request(
('\x01\x85', 'Hello'),
('\x00\x81', ' '),
('\x00\x85', 'World'),
('\x80\x81', '!'))
self.assertEqual('Hello World!', msgutil.receive_message(request))
def test_receive_fragments_unicode(self):
# UTF-8 encodes U+6f22 into e6bca2 and U+5b57 into e5ad97.
request = _create_request(
('\x01\x82', '\xe6\xbc'),
('\x00\x82', '\xa2\xe5'),
('\x80\x82', '\xad\x97'))
self.assertEqual(u'\u6f22\u5b57', msgutil.receive_message(request))
def test_receive_fragments_immediate_zero_termination(self):
request = _create_request(
('\x01\x8c', 'Hello World!'), ('\x80\x80', ''))
self.assertEqual('Hello World!', msgutil.receive_message(request))
def test_receive_fragments_duplicate_start(self):
request = _create_request(
('\x01\x85', 'Hello'), ('\x01\x85', 'World'))
self.assertRaises(msgutil.InvalidFrameException,
msgutil.receive_message,
request)
def test_receive_fragments_intermediate_but_not_started(self):
request = _create_request(('\x00\x85', 'Hello'))
self.assertRaises(msgutil.InvalidFrameException,
msgutil.receive_message,
request)
def test_receive_fragments_end_but_not_started(self):
request = _create_request(('\x80\x85', 'Hello'))
self.assertRaises(msgutil.InvalidFrameException,
msgutil.receive_message,
request)
def test_receive_message_discard(self):
request = _create_request(
('\x8f\x86', 'IGNORE'), ('\x81\x85', 'Hello'),
('\x8f\x89', 'DISREGARD'), ('\x81\x86', 'World!'))
self.assertRaises(msgutil.UnsupportedFrameException,
msgutil.receive_message, request)
self.assertEqual('Hello', msgutil.receive_message(request))
self.assertRaises(msgutil.UnsupportedFrameException,
msgutil.receive_message, request)
self.assertEqual('World!', msgutil.receive_message(request))
def test_receive_close(self):
request = _create_request(
('\x88\x8a', struct.pack('!H', 1000) + 'Good bye'))
self.assertEqual(None, msgutil.receive_message(request))
self.assertEqual(1000, request.ws_close_code)
self.assertEqual('Good bye', request.ws_close_reason)
def test_send_longest_close(self):
reason = 'a' * 123
request = _create_request(
('\x88\xfd',
struct.pack('!H', common.STATUS_NORMAL_CLOSURE) + reason))
request.ws_stream.close_connection(common.STATUS_NORMAL_CLOSURE,
reason)
self.assertEqual(request.ws_close_code, common.STATUS_NORMAL_CLOSURE)
self.assertEqual(request.ws_close_reason, reason)
def test_send_close_too_long(self):
request = _create_request()
self.assertRaises(msgutil.BadOperationException,
Stream.close_connection,
request.ws_stream,
common.STATUS_NORMAL_CLOSURE,
'a' * 124)
def test_send_close_inconsistent_code_and_reason(self):
request = _create_request()
# reason parameter must not be specified when code is None.
self.assertRaises(msgutil.BadOperationException,
Stream.close_connection,
request.ws_stream,
None,
'a')
def test_send_ping(self):
request = _create_request()
msgutil.send_ping(request, 'Hello World!')
self.assertEqual('\x89\x0cHello World!',
request.connection.written_data())
def test_send_longest_ping(self):
request = _create_request()
msgutil.send_ping(request, 'a' * 125)
self.assertEqual('\x89\x7d' + 'a' * 125,
request.connection.written_data())
def test_send_ping_too_long(self):
request = _create_request()
self.assertRaises(msgutil.BadOperationException,
msgutil.send_ping,
request,
'a' * 126)
def test_receive_ping(self):
"""Tests receiving a ping control frame."""
def handler(request, message):
request.called = True
# Stream automatically respond to ping with pong without any action
# by application layer.
request = _create_request(
('\x89\x85', 'Hello'), ('\x81\x85', 'World'))
self.assertEqual('World', msgutil.receive_message(request))
self.assertEqual('\x8a\x05Hello',
request.connection.written_data())
request = _create_request(
('\x89\x85', 'Hello'), ('\x81\x85', 'World'))
request.on_ping_handler = handler
self.assertEqual('World', msgutil.receive_message(request))
self.assertTrue(request.called)
def test_receive_longest_ping(self):
request = _create_request(
('\x89\xfd', 'a' * 125), ('\x81\x85', 'World'))
self.assertEqual('World', msgutil.receive_message(request))
self.assertEqual('\x8a\x7d' + 'a' * 125,
request.connection.written_data())
def test_receive_ping_too_long(self):
request = _create_request(('\x89\xfe\x00\x7e', 'a' * 126))
self.assertRaises(msgutil.InvalidFrameException,
msgutil.receive_message,
request)
def test_receive_pong(self):
"""Tests receiving a pong control frame."""
def handler(request, message):
request.called = True
request = _create_request(
('\x8a\x85', 'Hello'), ('\x81\x85', 'World'))
request.on_pong_handler = handler
msgutil.send_ping(request, 'Hello')
self.assertEqual('\x89\x05Hello',
request.connection.written_data())
# Valid pong is received, but receive_message won't return for it.
self.assertEqual('World', msgutil.receive_message(request))
# Check that nothing was written after receive_message call.
self.assertEqual('\x89\x05Hello',
request.connection.written_data())
self.assertTrue(request.called)
def test_receive_unsolicited_pong(self):
# Unsolicited pong is allowed from HyBi 07.
request = _create_request(
('\x8a\x85', 'Hello'), ('\x81\x85', 'World'))
msgutil.receive_message(request)
request = _create_request(
('\x8a\x85', 'Hello'), ('\x81\x85', 'World'))
msgutil.send_ping(request, 'Jumbo')
# Body mismatch.
msgutil.receive_message(request)
def test_ping_cannot_be_fragmented(self):
request = _create_request(('\x09\x85', 'Hello'))
self.assertRaises(msgutil.InvalidFrameException,
msgutil.receive_message,
request)
def test_ping_with_too_long_payload(self):
request = _create_request(('\x89\xfe\x01\x00', 'a' * 256))
self.assertRaises(msgutil.InvalidFrameException,
msgutil.receive_message,
request)
class DeflateFrameTest(unittest.TestCase):
"""Tests for checking deflate-frame extension."""
def test_send_message(self):
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
request = _create_request_from_rawdata(
'', deflate_frame_request=extension)
msgutil.send_message(request, 'Hello')
msgutil.send_message(request, 'World')
expected = ''
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
expected += '\xc1%c' % len(compressed_hello)
expected += compressed_hello
compressed_world = compress.compress('World')
compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_world = compressed_world[:-4]
expected += '\xc1%c' % len(compressed_world)
expected += compressed_world
self.assertEqual(expected, request.connection.written_data())
def test_send_message_bfinal(self):
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
request = _create_request_from_rawdata(
'', deflate_frame_request=extension)
self.assertEquals(1, len(request.ws_extension_processors))
deflate_frame_processor = request.ws_extension_processors[0]
deflate_frame_processor.set_bfinal(True)
msgutil.send_message(request, 'Hello')
msgutil.send_message(request, 'World')
expected = ''
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_FINISH)
compressed_hello = compressed_hello + chr(0)
expected += '\xc1%c' % len(compressed_hello)
expected += compressed_hello
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_world = compress.compress('World')
compressed_world += compress.flush(zlib.Z_FINISH)
compressed_world = compressed_world + chr(0)
expected += '\xc1%c' % len(compressed_world)
expected += compressed_world
self.assertEqual(expected, request.connection.written_data())
def test_send_message_comp_bit(self):
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
request = _create_request_from_rawdata(
'', deflate_frame_request=extension)
self.assertEquals(1, len(request.ws_extension_processors))
deflate_frame_processor = request.ws_extension_processors[0]
msgutil.send_message(request, 'Hello')
deflate_frame_processor.disable_outgoing_compression()
msgutil.send_message(request, 'Hello')
deflate_frame_processor.enable_outgoing_compression()
msgutil.send_message(request, 'Hello')
expected = ''
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
expected += '\xc1%c' % len(compressed_hello)
expected += compressed_hello
expected += '\x81\x05Hello'
compressed_2nd_hello = compress.compress('Hello')
compressed_2nd_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_2nd_hello = compressed_2nd_hello[:-4]
expected += '\xc1%c' % len(compressed_2nd_hello)
expected += compressed_2nd_hello
self.assertEqual(expected, request.connection.written_data())
def test_send_message_no_context_takeover_parameter(self):
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
extension.add_parameter('no_context_takeover', None)
request = _create_request_from_rawdata(
'', deflate_frame_request=extension)
for i in xrange(3):
msgutil.send_message(request, 'Hello')
compressed_message = compress.compress('Hello')
compressed_message += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_message = compressed_message[:-4]
expected = '\xc1%c' % len(compressed_message)
expected += compressed_message
self.assertEqual(
expected + expected + expected, request.connection.written_data())
def test_bad_request_parameters(self):
"""Tests that if there's anything wrong with deflate-frame extension
request, deflate-frame is rejected.
"""
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
# max_window_bits less than 8 is illegal.
extension.add_parameter('max_window_bits', '7')
processor = DeflateFrameExtensionProcessor(extension)
self.assertEqual(None, processor.get_extension_response())
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
# max_window_bits greater than 15 is illegal.
extension.add_parameter('max_window_bits', '16')
processor = DeflateFrameExtensionProcessor(extension)
self.assertEqual(None, processor.get_extension_response())
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
# Non integer max_window_bits is illegal.
extension.add_parameter('max_window_bits', 'foobar')
processor = DeflateFrameExtensionProcessor(extension)
self.assertEqual(None, processor.get_extension_response())
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
# no_context_takeover must not have any value.
extension.add_parameter('no_context_takeover', 'foobar')
processor = DeflateFrameExtensionProcessor(extension)
self.assertEqual(None, processor.get_extension_response())
def test_response_parameters(self):
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
processor = DeflateFrameExtensionProcessor(extension)
processor.set_response_window_bits(8)
response = processor.get_extension_response()
self.assertTrue(response.has_parameter('max_window_bits'))
self.assertEqual('8', response.get_parameter_value('max_window_bits'))
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
processor = DeflateFrameExtensionProcessor(extension)
processor.set_response_no_context_takeover(True)
response = processor.get_extension_response()
self.assertTrue(response.has_parameter('no_context_takeover'))
self.assertTrue(
response.get_parameter_value('no_context_takeover') is None)
def test_receive_message(self):
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
data = ''
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
data += '\xc1%c' % (len(compressed_hello) | 0x80)
data += _mask_hybi(compressed_hello)
compressed_websocket = compress.compress('WebSocket')
compressed_websocket += compress.flush(zlib.Z_FINISH)
compressed_websocket += '\x00'
data += '\xc1%c' % (len(compressed_websocket) | 0x80)
data += _mask_hybi(compressed_websocket)
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_world = compress.compress('World')
compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_world = compressed_world[:-4]
data += '\xc1%c' % (len(compressed_world) | 0x80)
data += _mask_hybi(compressed_world)
# Close frame
data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
request = _create_request_from_rawdata(
data, deflate_frame_request=extension)
self.assertEqual('Hello', msgutil.receive_message(request))
self.assertEqual('WebSocket', msgutil.receive_message(request))
self.assertEqual('World', msgutil.receive_message(request))
self.assertEqual(None, msgutil.receive_message(request))
def test_receive_message_client_using_smaller_window(self):
"""Test that frames coming from a client which is using smaller window
size that the server are correctly received.
"""
# Using the smallest window bits of 8 for generating input frames.
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -8)
data = ''
# Use a frame whose content is bigger than the clients' DEFLATE window
# size before compression. The content mainly consists of 'a' but
# repetition of 'b' is put at the head and tail so that if the window
# size is big, the head is back-referenced but if small, not.
payload = 'b' * 64 + 'a' * 1024 + 'b' * 64
compressed_hello = compress.compress(payload)
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
data += '\xc1%c' % (len(compressed_hello) | 0x80)
data += _mask_hybi(compressed_hello)
# Close frame
data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
request = _create_request_from_rawdata(
data, deflate_frame_request=extension)
self.assertEqual(payload, msgutil.receive_message(request))
self.assertEqual(None, msgutil.receive_message(request))
def test_receive_message_comp_bit(self):
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
data = ''
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
data += '\xc1%c' % (len(compressed_hello) | 0x80)
data += _mask_hybi(compressed_hello)
data += '\x81\x85' + _mask_hybi('Hello')
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_2nd_hello = compress.compress('Hello')
compressed_2nd_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_2nd_hello = compressed_2nd_hello[:-4]
data += '\xc1%c' % (len(compressed_2nd_hello) | 0x80)
data += _mask_hybi(compressed_2nd_hello)
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
request = _create_request_from_rawdata(
data, deflate_frame_request=extension)
for i in xrange(3):
self.assertEqual('Hello', msgutil.receive_message(request))
def test_receive_message_various_btype(self):
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
data = ''
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
data += '\xc1%c' % (len(compressed_hello) | 0x80)
data += _mask_hybi(compressed_hello)
compressed_websocket = compress.compress('WebSocket')
compressed_websocket += compress.flush(zlib.Z_FINISH)
compressed_websocket += '\x00'
data += '\xc1%c' % (len(compressed_websocket) | 0x80)
data += _mask_hybi(compressed_websocket)
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_world = compress.compress('World')
compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_world = compressed_world[:-4]
data += '\xc1%c' % (len(compressed_world) | 0x80)
data += _mask_hybi(compressed_world)
# Close frame
data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')
extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
request = _create_request_from_rawdata(
data, deflate_frame_request=extension)
self.assertEqual('Hello', msgutil.receive_message(request))
self.assertEqual('WebSocket', msgutil.receive_message(request))
self.assertEqual('World', msgutil.receive_message(request))
self.assertEqual(None, msgutil.receive_message(request))
class PerMessageDeflateTest(unittest.TestCase):
"""Tests for permessage-deflate extension."""
def test_send_message(self):
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
msgutil.send_message(request, 'Hello')
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
expected = '\xc1%c' % len(compressed_hello)
expected += compressed_hello
self.assertEqual(expected, request.connection.written_data())
def test_send_empty_message(self):
"""Test that an empty message is compressed correctly."""
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
msgutil.send_message(request, '')
# Payload in binary: 0b00000010 0b00000000
# From LSB,
# - 1 bit of BFINAL (0)
# - 2 bits of BTYPE (01 that means fixed Huffman)
# - 7 bits of the first code (0000000 that is the code for the
# end-of-block)
# - 1 bit of BFINAL (0)
# - 2 bits of BTYPE (no compression)
# - 3 bits of padding
self.assertEqual('\xc1\x02\x02\x00',
request.connection.written_data())
def test_send_message_with_null_character(self):
"""Test that a simple payload (one null) is framed correctly."""
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
msgutil.send_message(request, '\x00')
# Payload in binary: 0b01100010 0b00000000 0b00000000
# From LSB,
# - 1 bit of BFINAL (0)
# - 2 bits of BTYPE (01 that means fixed Huffman)
# - 8 bits of the first code (00110000 that is the code for the literal
# alphabet 0x00)
# - 7 bits of the second code (0000000 that is the code for the
# end-of-block)
# - 1 bit of BFINAL (0)
# - 2 bits of BTYPE (no compression)
# - 2 bits of padding
self.assertEqual('\xc1\x03\x62\x00\x00',
request.connection.written_data())
def test_send_two_messages(self):
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
msgutil.send_message(request, 'Hello')
msgutil.send_message(request, 'World')
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
expected = ''
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
expected += '\xc1%c' % len(compressed_hello)
expected += compressed_hello
compressed_world = compress.compress('World')
compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_world = compressed_world[:-4]
expected += '\xc1%c' % len(compressed_world)
expected += compressed_world
self.assertEqual(expected, request.connection.written_data())
def test_send_message_fragmented(self):
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
msgutil.send_message(request, 'Hello', end=False)
msgutil.send_message(request, 'Goodbye', end=False)
msgutil.send_message(request, 'World')
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
expected = '\x41%c' % len(compressed_hello)
expected += compressed_hello
compressed_goodbye = compress.compress('Goodbye')
compressed_goodbye += compress.flush(zlib.Z_SYNC_FLUSH)
expected += '\x00%c' % len(compressed_goodbye)
expected += compressed_goodbye
compressed_world = compress.compress('World')
compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_world = compressed_world[:-4]
expected += '\x80%c' % len(compressed_world)
expected += compressed_world
self.assertEqual(expected, request.connection.written_data())
def test_send_message_fragmented_empty_first_frame(self):
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
msgutil.send_message(request, '', end=False)
msgutil.send_message(request, 'Hello')
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_hello = compress.compress('')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
expected = '\x41%c' % len(compressed_hello)
expected += compressed_hello
compressed_empty = compress.compress('Hello')
compressed_empty += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_empty = compressed_empty[:-4]
expected += '\x80%c' % len(compressed_empty)
expected += compressed_empty
print '%r' % expected
self.assertEqual(expected, request.connection.written_data())
def test_send_message_fragmented_empty_last_frame(self):
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
msgutil.send_message(request, 'Hello', end=False)
msgutil.send_message(request, '')
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
expected = '\x41%c' % len(compressed_hello)
expected += compressed_hello
compressed_empty = compress.compress('')
compressed_empty += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_empty = compressed_empty[:-4]
expected += '\x80%c' % len(compressed_empty)
expected += compressed_empty
self.assertEqual(expected, request.connection.written_data())
def test_send_message_using_small_window(self):
common_part = 'abcdefghijklmnopqrstuvwxyz'
test_message = common_part + '-' * 30000 + common_part
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
extension.add_parameter('server_max_window_bits', '8')
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
msgutil.send_message(request, test_message)
expected_websocket_header_size = 2
expected_websocket_payload_size = 91
actual_frame = request.connection.written_data()
self.assertEqual(expected_websocket_header_size +
expected_websocket_payload_size,
len(actual_frame))
actual_header = actual_frame[0:expected_websocket_header_size]
actual_payload = actual_frame[expected_websocket_header_size:]
self.assertEqual(
'\xc1%c' % expected_websocket_payload_size, actual_header)
decompress = zlib.decompressobj(-8)
decompressed_message = decompress.decompress(
actual_payload + '\x00\x00\xff\xff')
decompressed_message += decompress.flush()
self.assertEqual(test_message, decompressed_message)
self.assertEqual(0, len(decompress.unused_data))
self.assertEqual(0, len(decompress.unconsumed_tail))
def test_send_message_no_context_takeover_parameter(self):
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
extension.add_parameter('server_no_context_takeover', None)
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
for i in xrange(3):
msgutil.send_message(request, 'Hello', end=False)
msgutil.send_message(request, 'Hello', end=True)
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
first_hello = compress.compress('Hello')
first_hello += compress.flush(zlib.Z_SYNC_FLUSH)
expected = '\x41%c' % len(first_hello)
expected += first_hello
second_hello = compress.compress('Hello')
second_hello += compress.flush(zlib.Z_SYNC_FLUSH)
second_hello = second_hello[:-4]
expected += '\x80%c' % len(second_hello)
expected += second_hello
self.assertEqual(
expected + expected + expected,
request.connection.written_data())
def test_send_message_fragmented_bfinal(self):
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
'', permessage_deflate_request=extension)
self.assertEquals(1, len(request.ws_extension_processors))
request.ws_extension_processors[0].set_bfinal(True)
msgutil.send_message(request, 'Hello', end=False)
msgutil.send_message(request, 'World', end=True)
expected = ''
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_FINISH)
compressed_hello = compressed_hello + chr(0)
expected += '\x41%c' % len(compressed_hello)
expected += compressed_hello
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_world = compress.compress('World')
compressed_world += compress.flush(zlib.Z_FINISH)
compressed_world = compressed_world + chr(0)
expected += '\x80%c' % len(compressed_world)
expected += compressed_world
self.assertEqual(expected, request.connection.written_data())
def test_receive_message_deflate(self):
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_hello = compress.compress('Hello')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
data = '\xc1%c' % (len(compressed_hello) | 0x80)
data += _mask_hybi(compressed_hello)
# Close frame
data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
data, permessage_deflate_request=extension)
self.assertEqual('Hello', msgutil.receive_message(request))
self.assertEqual(None, msgutil.receive_message(request))
def test_receive_message_random_section(self):
"""Test that a compressed message fragmented into lots of chunks is
correctly received.
"""
random.seed(a=0)
payload = ''.join(
[chr(random.randint(0, 255)) for i in xrange(1000)])
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_payload = compress.compress(payload)
compressed_payload += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_payload = compressed_payload[:-4]
# Fragment the compressed payload into lots of frames.
bytes_chunked = 0
data = ''
frame_count = 0
chunk_sizes = []
while bytes_chunked < len(compressed_payload):
# Make sure that
# - the length of chunks are equal or less than 125 so that we can
# use 1 octet length header format for all frames.
# - at least 10 chunks are created.
chunk_size = random.randint(
1, min(125,
len(compressed_payload) / 10,
len(compressed_payload) - bytes_chunked))
chunk_sizes.append(chunk_size)
chunk = compressed_payload[
bytes_chunked:bytes_chunked + chunk_size]
bytes_chunked += chunk_size
first_octet = 0x00
if len(data) == 0:
first_octet = first_octet | 0x42
if bytes_chunked == len(compressed_payload):
first_octet = first_octet | 0x80
data += '%c%c' % (first_octet, chunk_size | 0x80)
data += _mask_hybi(chunk)
frame_count += 1
print "Chunk sizes: %r" % chunk_sizes
self.assertTrue(len(chunk_sizes) > 10)
# Close frame
data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
data, permessage_deflate_request=extension)
self.assertEqual(payload, msgutil.receive_message(request))
self.assertEqual(None, msgutil.receive_message(request))
def test_receive_two_messages(self):
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
data = ''
compressed_hello = compress.compress('HelloWebSocket')
compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_hello = compressed_hello[:-4]
split_position = len(compressed_hello) / 2
data += '\x41%c' % (split_position | 0x80)
data += _mask_hybi(compressed_hello[:split_position])
data += '\x80%c' % ((len(compressed_hello) - split_position) | 0x80)
data += _mask_hybi(compressed_hello[split_position:])
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_world = compress.compress('World')
compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_world = compressed_world[:-4]
data += '\xc1%c' % (len(compressed_world) | 0x80)
data += _mask_hybi(compressed_world)
# Close frame
data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
data, permessage_deflate_request=extension)
self.assertEqual('HelloWebSocket', msgutil.receive_message(request))
self.assertEqual('World', msgutil.receive_message(request))
self.assertEqual(None, msgutil.receive_message(request))
def test_receive_message_mixed_btype(self):
"""Test that a message compressed using lots of DEFLATE blocks with
various flush mode is correctly received.
"""
random.seed(a=0)
payload = ''.join(
[chr(random.randint(0, 255)) for i in xrange(1000)])
compress = None
# Fragment the compressed payload into lots of frames.
bytes_chunked = 0
compressed_payload = ''
chunk_sizes = []
methods = []
sync_used = False
finish_used = False
while bytes_chunked < len(payload):
# Make sure at least 10 chunks are created.
chunk_size = random.randint(
1, min(100, len(payload) - bytes_chunked))
chunk_sizes.append(chunk_size)
chunk = payload[bytes_chunked:bytes_chunked + chunk_size]
bytes_chunked += chunk_size
if compress is None:
compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION,
zlib.DEFLATED,
-zlib.MAX_WBITS)
if bytes_chunked == len(payload):
compressed_payload += compress.compress(chunk)
compressed_payload += compress.flush(zlib.Z_SYNC_FLUSH)
compressed_payload = compressed_payload[:-4]
else:
method = random.randint(0, 1)
methods.append(method)
if method == 0:
compressed_payload += compress.compress(chunk)
compressed_payload += compress.flush(zlib.Z_SYNC_FLUSH)
sync_used = True
else:
compressed_payload += compress.compress(chunk)
compressed_payload += compress.flush(zlib.Z_FINISH)
compress = None
finish_used = True
print "Chunk sizes: %r" % chunk_sizes
self.assertTrue(len(chunk_sizes) > 10)
print "Methods: %r" % methods
self.assertTrue(sync_used)
self.assertTrue(finish_used)
self.assertTrue(125 < len(compressed_payload))
self.assertTrue(len(compressed_payload) < 65536)
data = '\xc2\xfe' + struct.pack('!H', len(compressed_payload))
data += _mask_hybi(compressed_payload)
# Close frame
data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')
extension = common.ExtensionParameter(
common.PERMESSAGE_DEFLATE_EXTENSION)
request = _create_request_from_rawdata(
data, permessage_deflate_request=extension)
self.assertEqual(payload, msgutil.receive_message(request))
self.assertEqual(None, msgutil.receive_message(request))
class PerMessageCompressTest(unittest.TestCase):
"""Tests for checking permessage-compression extension."""
def test_deflate_response_parameters(self):
extension = common.ExtensionParameter(
common.PERMESSAGE_COMPRESSION_EXTENSION)
extension.add_parameter('method', 'deflate')
processor = PerMessageCompressExtensionProcessor(extension)
response = processor.get_extension_response()
self.assertEqual('deflate',
response.get_parameter_value('method'))
extension = common.ExtensionParameter(
common.PERMESSAGE_COMPRESSION_EXTENSION)
extension.add_parameter('method', 'deflate')
processor = PerMessageCompressExtensionProcessor(extension)
def _compression_processor_hook(compression_processor):
compression_processor.set_client_max_window_bits(8)
compression_processor.set_client_no_context_takeover(True)
processor.set_compression_processor_hook(
_compression_processor_hook)
response = processor.get_extension_response()
self.assertEqual(
'deflate; client_max_window_bits=8; client_no_context_takeover',
response.get_parameter_value('method'))
class MessageTestHixie75(unittest.TestCase):
"""Tests for draft-hixie-thewebsocketprotocol-76 stream class."""
def test_send_message(self):
request = _create_request_hixie75()
msgutil.send_message(request, 'Hello')
self.assertEqual('\x00Hello\xff', request.connection.written_data())
def test_send_message_unicode(self):
request = _create_request_hixie75()
msgutil.send_message(request, u'\u65e5')
# U+65e5 is encoded as e6,97,a5 in UTF-8
self.assertEqual('\x00\xe6\x97\xa5\xff',
request.connection.written_data())
def test_receive_message(self):
request = _create_request_hixie75('\x00Hello\xff\x00World!\xff')
self.assertEqual('Hello', msgutil.receive_message(request))
self.assertEqual('World!', msgutil.receive_message(request))
def test_receive_message_unicode(self):
request = _create_request_hixie75('\x00\xe6\x9c\xac\xff')
# U+672c is encoded as e6,9c,ac in UTF-8
self.assertEqual(u'\u672c', msgutil.receive_message(request))
def test_receive_message_erroneous_unicode(self):
# \x80 and \x81 are invalid as UTF-8.
request = _create_request_hixie75('\x00\x80\x81\xff')
# Invalid characters should be replaced with
# U+fffd REPLACEMENT CHARACTER
self.assertEqual(u'\ufffd\ufffd', msgutil.receive_message(request))
def test_receive_message_discard(self):
request = _create_request_hixie75('\x80\x06IGNORE\x00Hello\xff'
'\x01DISREGARD\xff\x00World!\xff')
self.assertEqual('Hello', msgutil.receive_message(request))
self.assertEqual('World!', msgutil.receive_message(request))
class MessageReceiverTest(unittest.TestCase):
"""Tests the Stream class using MessageReceiver."""
def test_queue(self):
request = _create_blocking_request()
receiver = msgutil.MessageReceiver(request)
self.assertEqual(None, receiver.receive_nowait())
request.connection.put_bytes('\x81\x86' + _mask_hybi('Hello!'))
self.assertEqual('Hello!', receiver.receive())
def test_onmessage(self):
onmessage_queue = Queue.Queue()
def onmessage_handler(message):
onmessage_queue.put(message)
request = _create_blocking_request()
receiver = msgutil.MessageReceiver(request, onmessage_handler)
request.connection.put_bytes('\x81\x86' + _mask_hybi('Hello!'))
self.assertEqual('Hello!', onmessage_queue.get())
class MessageReceiverHixie75Test(unittest.TestCase):
"""Tests the StreamHixie75 class using MessageReceiver."""
def test_queue(self):
request = _create_blocking_request_hixie75()
receiver = msgutil.MessageReceiver(request)
self.assertEqual(None, receiver.receive_nowait())
request.connection.put_bytes('\x00Hello!\xff')
self.assertEqual('Hello!', receiver.receive())
def test_onmessage(self):
onmessage_queue = Queue.Queue()
def onmessage_handler(message):
onmessage_queue.put(message)
request = _create_blocking_request_hixie75()
receiver = msgutil.MessageReceiver(request, onmessage_handler)
request.connection.put_bytes('\x00Hello!\xff')
self.assertEqual('Hello!', onmessage_queue.get())
class MessageSenderTest(unittest.TestCase):
"""Tests the Stream class using MessageSender."""
def test_send(self):
request = _create_blocking_request()
sender = msgutil.MessageSender(request)
sender.send('World')
self.assertEqual('\x81\x05World', request.connection.written_data())
def test_send_nowait(self):
# Use a queue to check the bytes written by MessageSender.
# request.connection.written_data() cannot be used here because
# MessageSender runs in a separate thread.
send_queue = Queue.Queue()
def write(bytes):
send_queue.put(bytes)
request = _create_blocking_request()
request.connection.write = write
sender = msgutil.MessageSender(request)
sender.send_nowait('Hello')
sender.send_nowait('World')
self.assertEqual('\x81\x05Hello', send_queue.get())
self.assertEqual('\x81\x05World', send_queue.get())
class MessageSenderHixie75Test(unittest.TestCase):
"""Tests the StreamHixie75 class using MessageSender."""
def test_send(self):
request = _create_blocking_request_hixie75()
sender = msgutil.MessageSender(request)
sender.send('World')
self.assertEqual('\x00World\xff', request.connection.written_data())
def test_send_nowait(self):
# Use a queue to check the bytes written by MessageSender.
# request.connection.written_data() cannot be used here because
# MessageSender runs in a separate thread.
send_queue = Queue.Queue()
def write(bytes):
send_queue.put(bytes)
request = _create_blocking_request_hixie75()
request.connection.write = write
sender = msgutil.MessageSender(request)
sender.send_nowait('Hello')
sender.send_nowait('World')
self.assertEqual('\x00Hello\xff', send_queue.get())
self.assertEqual('\x00World\xff', send_queue.get())
if __name__ == '__main__':
unittest.main()
# vi:sts=4 sw=4 et
| mpl-2.0 |
tashaxe/Red-DiscordBot | lib/pip/__init__.py | 328 | 11348 | #!/usr/bin/env python
from __future__ import absolute_import
import locale
import logging
import os
import optparse
import warnings
import sys
import re
# 2016-06-17 barry@debian.org: urllib3 1.14 added optional support for socks,
# but if invoked (i.e. imported), it will issue a warning to stderr if socks
# isn't available. requests unconditionally imports urllib3's socks contrib
# module, triggering this warning. The warning breaks DEP-8 tests (because of
# the stderr output) and is just plain annoying in normal usage. I don't want
# to add socks as yet another dependency for pip, nor do I want to allow-stder
# in the DEP-8 tests, so just suppress the warning. pdb tells me this has to
# be done before the import of pip.vcs.
from pip._vendor.requests.packages.urllib3.exceptions import DependencyWarning
warnings.filterwarnings("ignore", category=DependencyWarning) # noqa
from pip.exceptions import InstallationError, CommandError, PipError
from pip.utils import get_installed_distributions, get_prog
from pip.utils import deprecation, dist_is_editable
from pip.vcs import git, mercurial, subversion, bazaar # noqa
from pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
from pip.commands import get_summaries, get_similar_commands
from pip.commands import commands_dict
from pip._vendor.requests.packages.urllib3.exceptions import (
InsecureRequestWarning,
)
# assignment for flake8 to be happy
# This fixes a peculiarity when importing via __import__ - as we are
# initialising the pip module, "from pip import cmdoptions" is recursive
# and appears not to work properly in that situation.
import pip.cmdoptions
cmdoptions = pip.cmdoptions
# The version as used in the setup.py and the docs conf.py
__version__ = "9.0.1"
logger = logging.getLogger(__name__)
# Hide the InsecureRequestWarning from urllib3
warnings.filterwarnings("ignore", category=InsecureRequestWarning)
def autocomplete():
"""Command and option completion for the main option parser (and options)
and its subcommands (and options).
Enable by sourcing one of the completion shell scripts (bash, zsh or fish).
"""
# Don't complete if user hasn't sourced bash_completion file.
if 'PIP_AUTO_COMPLETE' not in os.environ:
return
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try:
current = cwords[cword - 1]
except IndexError:
current = ''
subcommands = [cmd for cmd, summary in get_summaries()]
options = []
# subcommand
try:
subcommand_name = [w for w in cwords if w in subcommands][0]
except IndexError:
subcommand_name = None
parser = create_main_parser()
# subcommand options
if subcommand_name:
# special case: 'help' subcommand has no options
if subcommand_name == 'help':
sys.exit(1)
# special case: list locally installed dists for uninstall command
if subcommand_name == 'uninstall' and not current.startswith('-'):
installed = []
lc = current.lower()
for dist in get_installed_distributions(local_only=True):
if dist.key.startswith(lc) and dist.key not in cwords[1:]:
installed.append(dist.key)
# if there are no dists installed, fall back to option completion
if installed:
for dist in installed:
print(dist)
sys.exit(1)
subcommand = commands_dict[subcommand_name]()
options += [(opt.get_opt_string(), opt.nargs)
for opt in subcommand.parser.option_list_all
if opt.help != optparse.SUPPRESS_HELP]
# filter out previously specified options from available options
prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
options = [(x, v) for (x, v) in options if x not in prev_opts]
# filter options by current input
options = [(k, v) for k, v in options if k.startswith(current)]
for option in options:
opt_label = option[0]
# append '=' to options which require args
if option[1]:
opt_label += '='
print(opt_label)
else:
# show main parser options only when necessary
if current.startswith('-') or current.startswith('--'):
opts = [i.option_list for i in parser.option_groups]
opts.append(parser.option_list)
opts = (o for it in opts for o in it)
subcommands += [i.get_opt_string() for i in opts
if i.help != optparse.SUPPRESS_HELP]
print(' '.join([x for x in subcommands if x.startswith(current)]))
sys.exit(1)
def create_main_parser():
parser_kw = {
'usage': '\n%prog <command> [options]',
'add_help_option': False,
'formatter': UpdatingDefaultsHelpFormatter(),
'name': 'global',
'prog': get_prog(),
}
parser = ConfigOptionParser(**parser_kw)
parser.disable_interspersed_args()
pip_pkg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
parser.version = 'pip %s from %s (python %s)' % (
__version__, pip_pkg_dir, sys.version[:3])
# add the general options
gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
parser.add_option_group(gen_opts)
parser.main = True # so the help formatter knows
# create command listing for description
command_summaries = get_summaries()
description = [''] + ['%-27s %s' % (i, j) for i, j in command_summaries]
parser.description = '\n'.join(description)
return parser
def parseopts(args):
parser = create_main_parser()
# Note: parser calls disable_interspersed_args(), so the result of this
# call is to split the initial args into the general options before the
# subcommand and everything else.
# For example:
# args: ['--timeout=5', 'install', '--user', 'INITools']
# general_options: ['--timeout==5']
# args_else: ['install', '--user', 'INITools']
general_options, args_else = parser.parse_args(args)
# --version
if general_options.version:
sys.stdout.write(parser.version)
sys.stdout.write(os.linesep)
sys.exit()
# pip || pip help -> print_help()
if not args_else or (args_else[0] == 'help' and len(args_else) == 1):
parser.print_help()
sys.exit()
# the subcommand name
cmd_name = args_else[0]
if cmd_name not in commands_dict:
guess = get_similar_commands(cmd_name)
msg = ['unknown command "%s"' % cmd_name]
if guess:
msg.append('maybe you meant "%s"' % guess)
raise CommandError(' - '.join(msg))
# all the args without the subcommand
cmd_args = args[:]
cmd_args.remove(cmd_name)
return cmd_name, cmd_args
def check_isolated(args):
isolated = False
if "--isolated" in args:
isolated = True
return isolated
def main(args=None):
if args is None:
args = sys.argv[1:]
# Configure our deprecation warnings to be sent through loggers
deprecation.install_warning_logger()
autocomplete()
try:
cmd_name, cmd_args = parseopts(args)
except PipError as exc:
sys.stderr.write("ERROR: %s" % exc)
sys.stderr.write(os.linesep)
sys.exit(1)
# Needed for locale.getpreferredencoding(False) to work
# in pip.utils.encoding.auto_decode
try:
locale.setlocale(locale.LC_ALL, '')
except locale.Error as e:
# setlocale can apparently crash if locale are uninitialized
logger.debug("Ignoring error %s when setting locale", e)
command = commands_dict[cmd_name](isolated=check_isolated(cmd_args))
return command.main(cmd_args)
# ###########################################################
# # Writing freeze files
class FrozenRequirement(object):
def __init__(self, name, req, editable, comments=()):
self.name = name
self.req = req
self.editable = editable
self.comments = comments
_rev_re = re.compile(r'-r(\d+)$')
_date_re = re.compile(r'-(20\d\d\d\d\d\d)$')
@classmethod
def from_dist(cls, dist, dependency_links):
location = os.path.normcase(os.path.abspath(dist.location))
comments = []
from pip.vcs import vcs, get_src_requirement
if dist_is_editable(dist) and vcs.get_backend_name(location):
editable = True
try:
req = get_src_requirement(dist, location)
except InstallationError as exc:
logger.warning(
"Error when trying to get requirement for VCS system %s, "
"falling back to uneditable format", exc
)
req = None
if req is None:
logger.warning(
'Could not determine repository location of %s', location
)
comments.append(
'## !! Could not determine repository location'
)
req = dist.as_requirement()
editable = False
else:
editable = False
req = dist.as_requirement()
specs = req.specs
assert len(specs) == 1 and specs[0][0] in ["==", "==="], \
'Expected 1 spec with == or ===; specs = %r; dist = %r' % \
(specs, dist)
version = specs[0][1]
ver_match = cls._rev_re.search(version)
date_match = cls._date_re.search(version)
if ver_match or date_match:
svn_backend = vcs.get_backend('svn')
if svn_backend:
svn_location = svn_backend().get_location(
dist,
dependency_links,
)
if not svn_location:
logger.warning(
'Warning: cannot find svn location for %s', req)
comments.append(
'## FIXME: could not find svn URL in dependency_links '
'for this package:'
)
else:
comments.append(
'# Installing as editable to satisfy requirement %s:' %
req
)
if ver_match:
rev = ver_match.group(1)
else:
rev = '{%s}' % date_match.group(1)
editable = True
req = '%s@%s#egg=%s' % (
svn_location,
rev,
cls.egg_name(dist)
)
return cls(dist.project_name, req, editable, comments)
@staticmethod
def egg_name(dist):
name = dist.egg_name()
match = re.search(r'-py\d\.\d$', name)
if match:
name = name[:match.start()]
return name
def __str__(self):
req = self.req
if self.editable:
req = '-e %s' % req
return '\n'.join(list(self.comments) + [str(req)]) + '\n'
if __name__ == '__main__':
sys.exit(main())
| gpl-3.0 |
keeeener/nicki | platform/external/webkit/Tools/Scripts/webkitpy/tool/steps/checkstyle.py | 15 | 2811 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
from webkitpy.common.system.executive import ScriptError
from webkitpy.tool.steps.abstractstep import AbstractStep
from webkitpy.tool.steps.options import Options
from webkitpy.common.system.deprecated_logging import error
class CheckStyle(AbstractStep):
@classmethod
def options(cls):
return AbstractStep.options() + [
Options.non_interactive,
Options.check_style,
Options.git_commit,
]
def run(self, state):
if not self._options.check_style:
return
os.chdir(self._tool.scm().checkout_root)
args = []
if self._options.git_commit:
args.append("--git-commit")
args.append(self._options.git_commit)
args.append("--diff-files")
args.extend(self._changed_files(state))
try:
self._tool.executive.run_and_throw_if_fail(self._tool.port().check_webkit_style_command() + args)
except ScriptError, e:
if self._options.non_interactive:
# We need to re-raise the exception here to have the
# style-queue do the right thing.
raise e
if not self._tool.user.confirm("Are you sure you want to continue?"):
exit(1)
| gpl-2.0 |
jjscarafia/odoo | addons/mrp/wizard/__init__.py | 374 | 1199 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import mrp_product_produce
import mrp_price
import mrp_workcenter_load
import change_production_qty
import stock_move
#import mrp_change_standard_price
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
orgito/ansible | lib/ansible/modules/utilities/logic/wait_for_connection.py | 14 | 3059 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: wait_for_connection
short_description: Waits until remote system is reachable/usable
description:
- Waits for a total of C(timeout) seconds.
- Retries the transport connection after a timeout of C(connect_timeout).
- Tests the transport connection every C(sleep) seconds.
- This module makes use of internal ansible transport (and configuration) and the ping/win_ping module to guarantee correct end-to-end functioning.
- This module is also supported for Windows targets.
version_added: "2.3"
options:
connect_timeout:
description:
- Maximum number of seconds to wait for a connection to happen before closing and retrying.
default: 5
delay:
description:
- Number of seconds to wait before starting to poll.
default: 0
sleep:
default: 1
description:
- Number of seconds to sleep between checks.
timeout:
description:
- Maximum number of seconds to wait for.
default: 600
notes:
- This module is also supported for Windows targets.
seealso:
- module: wait_for
- module: win_wait_for
- module: win_wait_for_process
author:
- Dag Wieers (@dagwieers)
'''
EXAMPLES = r'''
- name: Wait 600 seconds for target connection to become reachable/usable
wait_for_connection:
- name: Wait 300 seconds, but only start checking after 60 seconds
wait_for_connection:
delay: 60
timeout: 300
# Wake desktops, wait for them to become ready and continue playbook
- hosts: all
gather_facts: no
tasks:
- name: Send magic Wake-On-Lan packet to turn on individual systems
wakeonlan:
mac: '{{ mac }}'
broadcast: 192.168.0.255
delegate_to: localhost
- name: Wait for system to become reachable
wait_for_connection:
- name: Gather facts for first time
setup:
# Build a new VM, wait for it to become ready and continue playbook
- hosts: all
gather_facts: no
tasks:
- name: Clone new VM, if missing
vmware_guest:
hostname: '{{ vcenter_ipaddress }}'
name: '{{ inventory_hostname_short }}'
template: Windows 2012R2
customization:
hostname: '{{ vm_shortname }}'
runonce:
- powershell.exe -ExecutionPolicy Unrestricted -File C:\Windows\Temp\ConfigureRemotingForAnsible.ps1 -ForceNewSSLCert -EnableCredSSP
delegate_to: localhost
- name: Wait for system to become reachable over WinRM
wait_for_connection:
timeout: 900
- name: Gather facts for first time
setup:
'''
RETURN = r'''
elapsed:
description: The number of seconds that elapsed waiting for the connection to appear.
returned: always
type: int
sample: 23
'''
| gpl-3.0 |
FusionSP/android_external_chromium_org | tools/telemetry/telemetry/unittest/json_results.py | 27 | 8638 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import functools
import json
import re
import time
import unittest
import urllib2
# TODO(dpranke): This code is largely cloned from, and redundant with,
# src/mojo/tools/run_mojo_python_tests.py, and also duplicates logic
# in test-webkitpy and run-webkit-tests. We should consolidate the
# python TestResult parsing/converting/uploading code as much as possible.
def AddOptions(parser):
parser.add_option('--metadata', action='append', default=[],
help=('optional key=value metadata that will be stored '
'in the results files (can be used for revision '
'numbers, etc.)'))
parser.add_option('--write-full-results-to', metavar='FILENAME',
action='store',
help='The path to write the list of full results to.')
parser.add_option('--builder-name',
help='The name of the builder as shown on the waterfall.')
parser.add_option('--master-name',
help='The name of the buildbot master.')
parser.add_option("--test-results-server", default="",
help=('If specified, upload full_results.json file to '
'this server.'))
parser.add_option('--test-type',
help=('Name of test type / step on the waterfall '
'(e.g., "telemetry_unittests").'))
def ValidateArgs(parser, args):
for val in args.metadata:
if '=' not in val:
parser.error('Error: malformed metadata "%s"' % val)
if (args.test_results_server and
(not args.builder_name or not args.master_name or not args.test_type)):
parser.error('Error: --builder-name, --master-name, and --test-type '
'must be specified along with --test-result-server.')
def WriteFullResultsIfNecessary(args, full_results):
if not args.write_full_results_to:
return
with open(args.write_full_results_to, 'w') as fp:
json.dump(full_results, fp, indent=2)
fp.write("\n")
def UploadFullResultsIfNecessary(args, full_results):
if not args.test_results_server:
return False, ''
url = 'http://%s/testfile/upload' % args.test_results_server
attrs = [('builder', args.builder_name),
('master', args.master_name),
('testtype', args.test_type)]
content_type, data = _EncodeMultiPartFormData(attrs, full_results)
return _UploadData(url, data, content_type)
TEST_SEPARATOR = '.'
def FullResults(args, suite, results):
"""Convert the unittest results to the Chromium JSON test result format.
This matches run-webkit-tests (the layout tests) and the flakiness dashboard.
"""
full_results = {}
full_results['interrupted'] = False
full_results['path_delimiter'] = TEST_SEPARATOR
full_results['version'] = 3
full_results['seconds_since_epoch'] = time.time()
full_results['builder_name'] = args.builder_name or ''
for md in args.metadata:
key, val = md.split('=', 1)
full_results[key] = val
all_test_names = AllTestNames(suite)
sets_of_passing_test_names = map(PassingTestNames, results)
sets_of_failing_test_names = map(functools.partial(FailedTestNames, suite),
results)
# TODO(crbug.com/405379): This handles tests that are skipped via the
# unittest skip decorators (like skipUnless). The tests that are skipped via
# telemetry's decorators package are not included in the test suite at all so
# we need those to be passed in in order to include them.
skipped_tests = (set(all_test_names) - sets_of_passing_test_names[0]
- sets_of_failing_test_names[0])
num_tests = len(all_test_names)
num_failures = NumFailuresAfterRetries(suite, results)
num_skips = len(skipped_tests)
num_passes = num_tests - num_failures - num_skips
full_results['num_failures_by_type'] = {
'FAIL': num_failures,
'PASS': num_passes,
'SKIP': num_skips,
}
full_results['tests'] = {}
for test_name in all_test_names:
if test_name in skipped_tests:
value = {
'expected': 'SKIP',
'actual': 'SKIP',
}
else:
value = {
'expected': 'PASS',
'actual': ActualResultsForTest(test_name,
sets_of_failing_test_names,
sets_of_passing_test_names),
}
if value['actual'].endswith('FAIL'):
value['is_unexpected'] = True
_AddPathToTrie(full_results['tests'], test_name, value)
return full_results
def ActualResultsForTest(test_name, sets_of_failing_test_names,
sets_of_passing_test_names):
actuals = []
for retry_num in range(len(sets_of_failing_test_names)):
if test_name in sets_of_failing_test_names[retry_num]:
actuals.append('FAIL')
elif test_name in sets_of_passing_test_names[retry_num]:
assert ((retry_num == 0) or
(test_name in sets_of_failing_test_names[retry_num - 1])), (
'We should not have run a test that did not fail '
'on the previous run.')
actuals.append('PASS')
assert actuals, 'We did not find any result data for %s.' % test_name
return ' '.join(actuals)
def ExitCodeFromFullResults(full_results):
return 1 if full_results['num_failures_by_type']['FAIL'] else 0
def AllTestNames(suite):
test_names = []
# _tests is protected pylint: disable=W0212
for test in suite._tests:
if isinstance(test, unittest.suite.TestSuite):
test_names.extend(AllTestNames(test))
else:
test_names.append(test.id())
return test_names
def NumFailuresAfterRetries(suite, results):
return len(FailedTestNames(suite, results[-1]))
def FailedTestNames(suite, result):
failed_test_names = set()
for test, error in result.failures + result.errors:
if isinstance(test, unittest.TestCase):
failed_test_names.add(test.id())
elif isinstance(test, unittest.suite._ErrorHolder): # pylint: disable=W0212
# If there's an error in setUpClass or setUpModule, unittest gives us an
# _ErrorHolder object. We can parse the object's id for the class or
# module that failed, then find all tests in that class or module.
match = re.match('setUp[a-zA-Z]+ \\((.+)\\)', test.id())
assert match, "Don't know how to retry after this error:\n%s" % error
module_or_class = match.groups()[0]
failed_test_names |= _FindChildren(module_or_class, AllTestNames(suite))
else:
assert False, 'Unknown test type: %s' % test.__class__
return failed_test_names
def _FindChildren(parent, potential_children):
children = set()
parent_name_parts = parent.split('.')
for potential_child in potential_children:
child_name_parts = potential_child.split('.')
if parent_name_parts == child_name_parts[:len(parent_name_parts)]:
children.add(potential_child)
return children
def PassingTestNames(result):
return set(test.id() for test in result.successes)
def _AddPathToTrie(trie, path, value):
if TEST_SEPARATOR not in path:
trie[path] = value
return
directory, rest = path.split(TEST_SEPARATOR, 1)
if directory not in trie:
trie[directory] = {}
_AddPathToTrie(trie[directory], rest, value)
def _EncodeMultiPartFormData(attrs, full_results):
# Cloned from webkitpy/common/net/file_uploader.py
BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
CRLF = '\r\n'
lines = []
for key, value in attrs:
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="%s"' % key)
lines.append('')
lines.append(value)
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="file"; '
'filename="full_results.json"')
lines.append('Content-Type: application/json')
lines.append('')
lines.append(json.dumps(full_results))
lines.append('--' + BOUNDARY + '--')
lines.append('')
body = CRLF.join(lines)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def _UploadData(url, data, content_type):
request = urllib2.Request(url, data, {'Content-Type': content_type})
try:
response = urllib2.urlopen(request)
if response.code == 200:
return False, ''
return True, ('Uploading the JSON results failed with %d: "%s"' %
(response.code, response.read()))
except Exception as e:
return True, 'Uploading the JSON results raised "%s"\n' % str(e)
| bsd-3-clause |
factorlibre/OCB | addons/base_report_designer/plugin/openerp_report_designer/bin/script/lib/gui.py | 382 | 31513 | ##########################################################################
#
# Copyright (c) 2003-2004 Danny Brewer d29583@groovegarden.com
# Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>).
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# See: http://www.gnu.org/licenses/lgpl.html
#
##############################################################################
import uno
import unohelper
import pythonloader
if __name__<>"package":
from actions import *
#------------------------------------------------------------
# Uno ServiceManager access
# A different version of this routine and global variable
# is needed for code running inside a component.
#------------------------------------------------------------
# The ServiceManager of the running OOo.
# It is cached in a global variable.
goServiceManager = False
pythonloader.DEBUG = 0
def getServiceManager( cHost="localhost", cPort="2002" ):
"""Get the ServiceManager from the running OpenOffice.org.
Then retain it in the global variable goServiceManager for future use.
This is similar to the GetProcessServiceManager() in OOo Basic.
"""
global goServiceManager
global pythonloader
if not goServiceManager:
# Get the uno component context from the PyUNO runtime
oLocalContext = uno.getComponentContext()
# Create the UnoUrlResolver on the Python side.
# Connect to the running OpenOffice.org and get its context.
if __name__<>"package":
oLocalResolver = oLocalContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", oLocalContext )
oContext = oLocalResolver.resolve( "uno:socket,host=" + cHost + ",port=" + cPort + ";urp;StarOffice.ComponentContext" )
# Get the ServiceManager object
goServiceManager = oContext.ServiceManager
else:
goServiceManager=oLocalContext.ServiceManager
return goServiceManager
#------------------------------------------------------------
# Uno convenience functions
# The stuff in this section is just to make
# python progrmaming of OOo more like using OOo Basic.
#------------------------------------------------------------
# This is the same as ServiceManager.createInstance( ... )
def createUnoService( cClass ):
"""A handy way to create a global objects within the running OOo.
Similar to the function of the same name in OOo Basic.
"""
oServiceManager = getServiceManager()
oObj = oServiceManager.createInstance( cClass )
return oObj
# The StarDesktop object. (global like in OOo Basic)
# It is cached in a global variable.
StarDesktop = None
def getDesktop():
"""An easy way to obtain the Desktop object from a running OOo.
"""
global StarDesktop
if StarDesktop == None:
StarDesktop = createUnoService( "com.sun.star.frame.Desktop" )
return StarDesktop
# preload the StarDesktop variable.
#getDesktop()
# The CoreReflection object.
# It is cached in a global variable.
goCoreReflection = False
def getCoreReflection():
global goCoreReflection
if not goCoreReflection:
goCoreReflection = createUnoService( "com.sun.star.reflection.CoreReflection" )
return goCoreReflection
def createUnoStruct( cTypeName ):
"""Create a UNO struct and return it.
Similar to the function of the same name in OOo Basic.
"""
oCoreReflection = getCoreReflection()
# Get the IDL class for the type name
oXIdlClass = oCoreReflection.forName( cTypeName )
# Create the struct.
oReturnValue, oStruct = oXIdlClass.createObject( None )
return oStruct
#------------------------------------------------------------
# API helpers
#------------------------------------------------------------
def hasUnoInterface( oObject, cInterfaceName ):
"""Similar to Basic's HasUnoInterfaces() function, but singular not plural."""
# Get the Introspection service.
oIntrospection = createUnoService( "com.sun.star.beans.Introspection" )
# Now inspect the object to learn about it.
oObjInfo = oIntrospection.inspect( oObject )
# Obtain an array describing all methods of the object.
oMethods = oObjInfo.getMethods( uno.getConstantByName( "com.sun.star.beans.MethodConcept.ALL" ) )
# Now look at every method.
for oMethod in oMethods:
# Check the method's interface to see if
# these aren't the droids you're looking for.
cMethodInterfaceName = oMethod.getDeclaringClass().getName()
if cMethodInterfaceName == cInterfaceName:
return True
return False
def hasUnoInterfaces( oObject, *cInterfaces ):
"""Similar to the function of the same name in OOo Basic."""
for cInterface in cInterfaces:
if not hasUnoInterface( oObject, cInterface ):
return False
return True
#------------------------------------------------------------
# High level general purpose functions
#------------------------------------------------------------
def makePropertyValue( cName=None, uValue=None, nHandle=None, nState=None ):
"""Create a com.sun.star.beans.PropertyValue struct and return it.
"""
oPropertyValue = createUnoStruct( "com.sun.star.beans.PropertyValue" )
if cName != None:
oPropertyValue.Name = cName
if uValue != None:
oPropertyValue.Value = uValue
if nHandle != None:
oPropertyValue.Handle = nHandle
if nState != None:
oPropertyValue.State = nState
return oPropertyValue
def makePoint( nX, nY ):
"""Create a com.sun.star.awt.Point struct."""
oPoint = createUnoStruct( "com.sun.star.awt.Point" )
oPoint.X = nX
oPoint.Y = nY
return oPoint
def makeSize( nWidth, nHeight ):
"""Create a com.sun.star.awt.Size struct."""
oSize = createUnoStruct( "com.sun.star.awt.Size" )
oSize.Width = nWidth
oSize.Height = nHeight
return oSize
def makeRectangle( nX, nY, nWidth, nHeight ):
"""Create a com.sun.star.awt.Rectangle struct."""
oRect = createUnoStruct( "com.sun.star.awt.Rectangle" )
oRect.X = nX
oRect.Y = nY
oRect.Width = nWidth
oRect.Height = nHeight
return oRect
def Array( *args ):
"""This is just sugar coating so that code from OOoBasic which
contains the Array() function can work perfectly in python."""
tArray = ()
for arg in args:
tArray += (arg,)
return tArray
def loadComponentFromURL( cUrl, tProperties=() ):
"""Open or Create a document from it's URL.
New documents are created from URL's such as:
private:factory/sdraw
private:factory/swriter
private:factory/scalc
private:factory/simpress
"""
StarDesktop = getDesktop()
oDocument = StarDesktop.loadComponentFromURL( cUrl, "_blank", 0, tProperties )
return oDocument
#------------------------------------------------------------
# Styles
#------------------------------------------------------------
def defineStyle( oDrawDoc, cStyleFamily, cStyleName, cParentStyleName=None ):
"""Add a new style to the style catalog if it is not already present.
This returns the style object so that you can alter its properties.
"""
oStyleFamily = oDrawDoc.getStyleFamilies().getByName( cStyleFamily )
# Does the style already exist?
if oStyleFamily.hasByName( cStyleName ):
# then get it so we can return it.
oStyle = oStyleFamily.getByName( cStyleName )
else:
# Create new style object.
oStyle = oDrawDoc.createInstance( "com.sun.star.style.Style" )
# Set its parent style
if cParentStyleName != None:
oStyle.setParentStyle( cParentStyleName )
# Add the new style to the style family.
oStyleFamily.insertByName( cStyleName, oStyle )
return oStyle
def getStyle( oDrawDoc, cStyleFamily, cStyleName ):
"""Lookup and return a style from the document.
"""
return oDrawDoc.getStyleFamilies().getByName( cStyleFamily ).getByName( cStyleName )
#------------------------------------------------------------
# General Utility functions
#------------------------------------------------------------
def convertToURL( cPathname ):
"""Convert a Windows or Linux pathname into an OOo URL."""
if len( cPathname ) > 1:
if cPathname[1:2] == ":":
cPathname = "/" + cPathname[0] + "|" + cPathname[2:]
cPathname = cPathname.replace( "\\", "/" )
cPathname = "file://" + cPathname
return cPathname
# The global Awt Toolkit.
# This is initialized the first time it is needed.
#goAwtToolkit = createUnoService( "com.sun.star.awt.Toolkit" )
goAwtToolkit = None
def getAwtToolkit():
global goAwtToolkit
if goAwtToolkit == None:
goAwtToolkit = createUnoService( "com.sun.star.awt.Toolkit" )
return goAwtToolkit
# This class builds dialog boxes.
# This can be used in two different ways...
# 1. by subclassing it (elegant)
# 2. without subclassing it (less elegant)
class DBModalDialog:
"""Class to build a dialog box from the com.sun.star.awt.* services.
This doesn't do anything you couldn't already do using OOo's UNO API,
this just makes it much easier.
You can change the dialog box size, position, title, etc.
You can add controls, and listeners for those controls to the dialog box.
This class can be used by subclassing it, or without subclassing it.
"""
def __init__( self, nPositionX=None, nPositionY=None, nWidth=None, nHeight=None, cTitle=None ):
self.oDialogModel = createUnoService( "com.sun.star.awt.UnoControlDialogModel" )
if nPositionX != None: self.oDialogModel.PositionX = nPositionX
if nPositionY != None: self.oDialogModel.PositionY = nPositionY
if nWidth != None: self.oDialogModel.Width = nWidth
if nHeight != None: self.oDialogModel.Height = nHeight
if cTitle != None: self.oDialogModel.Title = cTitle
self.oDialogControl = createUnoService( "com.sun.star.awt.UnoControlDialog" )
self.oDialogControl.setModel( self.oDialogModel )
def release( self ):
"""Release resources.
After calling this, you can no longer use this object.
"""
self.oDialogControl.dispose()
#--------------------------------------------------
# Dialog box adjustments
#--------------------------------------------------
def setDialogPosition( self, nX, nY ):
self.oDialogModel.PositionX = nX
self.oDialogModel.PositionY = nY
def setDialogSize( self, nWidth, nHeight ):
self.oDialogModel.Width = nWidth
self.oDialogModel.Height = nHeight
def setDialogTitle( self, cCaption ):
self.oDialogModel.Title = cCaption
def setVisible( self, bVisible ):
self.oDialogControl.setVisible( bVisible )
#--------------------------------------------------
# com.sun.star.awt.UnoControlButton
#--------------------------------------------------
# After you add a Button control, you can call self.setControlModelProperty()
# passing any of the properties for a...
# com.sun.star.awt.UnoControlButtonModel
# com.sun.star.awt.UnoControlDialogElement
# com.sun.star.awt.UnoControlModel
def addButton( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
cLabel=None,
actionListenerProc=None,
nTabIndex=None ):
self.addControl( "com.sun.star.awt.UnoControlButtonModel",
cCtrlName, nPositionX, nPositionY, nWidth, nHeight, bDropdown=None, bMultiSelection=None,
cLabel=cLabel,
nTabIndex=nTabIndex )
if actionListenerProc != None:
self.addActionListenerProc( cCtrlName, actionListenerProc )
def setButtonLabel( self, cCtrlName, cLabel ):
"""Set the label of the control."""
oControl = self.getControl( cCtrlName )
oControl.setLabel( cLabel )
#--------------------------------------------------
# com.sun.star.awt.UnoControlEditModel
#--------------------------------------------------
def addEdit( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
cText=None,
textListenerProc=None ):
"""Add a Edit control to the window."""
self.addControl( "com.sun.star.awt.UnoControlEditModel",
cCtrlName, nPositionX, nPositionY, nWidth, nHeight, bDropdown=None)
if cText != None:
self.setEditText( cCtrlName, cText )
if textListenerProc != None:
self.addTextListenerProc( cCtrlName, textListenerProc )
#--------------------------------------------------
# com.sun.star.awt.UnoControlCheckBox
#--------------------------------------------------
# After you add a CheckBox control, you can call self.setControlModelProperty()
# passing any of the properties for a...
# com.sun.star.awt.UnoControlCheckBoxModel
# com.sun.star.awt.UnoControlDialogElement
# com.sun.star.awt.UnoControlModel
def addCheckBox( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
cLabel=None,
itemListenerProc=None,
nTabIndex=None ):
self.addControl( "com.sun.star.awt.UnoControlCheckBoxModel",
cCtrlName, nPositionX, nPositionY, nWidth, nHeight, bDropdown=None, bMultiSelection=None,
cLabel=cLabel,
nTabIndex=nTabIndex )
if itemListenerProc != None:
self.addItemListenerProc( cCtrlName, itemListenerProc )
def setEditText( self, cCtrlName, cText ):
"""Set the text of the edit box."""
oControl = self.getControl( cCtrlName )
oControl.setText( cText )
def getEditText( self, cCtrlName):
"""Set the text of the edit box."""
oControl = self.getControl( cCtrlName )
return oControl.getText()
def setCheckBoxLabel( self, cCtrlName, cLabel ):
"""Set the label of the control."""
oControl = self.getControl( cCtrlName )
oControl.setLabel( cLabel )
def getCheckBoxState( self, cCtrlName ):
"""Get the state of the control."""
oControl = self.getControl( cCtrlName )
return oControl.getState();
def setCheckBoxState( self, cCtrlName, nState ):
"""Set the state of the control."""
oControl = self.getControl( cCtrlName )
oControl.setState( nState )
def enableCheckBoxTriState( self, cCtrlName, bTriStateEnable ):
"""Enable or disable the tri state mode of the control."""
oControl = self.getControl( cCtrlName )
oControl.enableTriState( bTriStateEnable )
#--------------------------------------------------
# com.sun.star.awt.UnoControlFixedText
#--------------------------------------------------
def addFixedText( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
cLabel=None ):
self.addControl( "com.sun.star.awt.UnoControlFixedTextModel",
cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
bDropdown=None, bMultiSelection=None,
cLabel=cLabel )
return self.getControl( cCtrlName )
#--------------------------------------------------
# Add Controls to dialog
#--------------------------------------------------
def addControl( self, cCtrlServiceName,
cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
bDropdown=None,
bMultiSelection=None,
cLabel=None,
nTabIndex=None,
sImagePath=None,
):
oControlModel = self.oDialogModel.createInstance( cCtrlServiceName )
self.oDialogModel.insertByName( cCtrlName, oControlModel )
# if negative coordinates are given for X or Y position,
# then make that coordinate be relative to the right/bottom
# edge of the dialog box instead of to the left/top.
if nPositionX < 0: nPositionX = self.oDialogModel.Width + nPositionX - nWidth
if nPositionY < 0: nPositionY = self.oDialogModel.Height + nPositionY - nHeight
oControlModel.PositionX = nPositionX
oControlModel.PositionY = nPositionY
oControlModel.Width = nWidth
oControlModel.Height = nHeight
oControlModel.Name = cCtrlName
if bDropdown != None:
oControlModel.Dropdown = bDropdown
if bMultiSelection!=None:
oControlModel.MultiSelection=bMultiSelection
if cLabel != None:
oControlModel.Label = cLabel
if nTabIndex != None:
oControlModel.TabIndex = nTabIndex
if sImagePath != None:
oControlModel.ImageURL = sImagePath
#--------------------------------------------------
# Access controls and control models
#--------------------------------------------------
#--------------------------------------------------
# com.sun.star.awt.UnoContorlListBoxModel
#--------------------------------------------------
def addComboListBox( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
bDropdown=True,
bMultiSelection=False,
itemListenerProc=None,
actionListenerProc=None,
):
mod = self.addControl( "com.sun.star.awt.UnoControlListBoxModel",
cCtrlName, nPositionX, nPositionY, nWidth, nHeight,bDropdown,bMultiSelection )
if itemListenerProc != None:
self.addItemListenerProc( cCtrlName, itemListenerProc )
def addListBoxItems( self, cCtrlName, tcItemTexts, nPosition=0 ):
"""Add a tupple of items to the ListBox at specified position."""
oControl = self.getControl( cCtrlName )
oControl.addItems( tcItemTexts, nPosition )
def selectListBoxItem( self, cCtrlName, cItemText, bSelect=True ):
"""Selects/Deselects the ispecified item."""
oControl = self.getControl( cCtrlName )
return oControl.selectItem( cItemText, bSelect )
def selectListBoxItemPos( self, cCtrlName, nItemPos, bSelect=True ):
"""Select/Deselect the item at the specified position."""
oControl = self.getControl( cCtrlName )
return oControl.selectItemPos( nItemPos, bSelect )
def removeListBoxItems( self, cCtrlName, nPosition, nCount=1 ):
"""Remove items from a ListBox."""
oControl = self.getControl( cCtrlName )
oControl.removeItems( nPosition, nCount )
def getListBoxItemCount( self, cCtrlName ):
"""Get the number of items in a ListBox."""
oControl = self.getControl( cCtrlName )
return oControl.getItemCount()
def getListBoxSelectedItem( self, cCtrlName ):
"""Returns the currently selected item."""
oControl = self.getControl( cCtrlName )
return oControl.getSelectedItem()
def getListBoxItem( self, cCtrlName, nPosition ):
"""Return the item at specified position within the ListBox."""
oControl = self.getControl( cCtrlName )
return oControl.getItem( nPosition )
def getListBoxSelectedItemPos(self,cCtrlName):
oControl = self.getControl( cCtrlName )
return oControl.getSelectedItemPos()
def getListBoxSelectedItems(self,cCtrlName):
oControl = self.getControl( cCtrlName )
return oControl.getSelectedItems()
def getListBoxSelectedItemsPos(self,cCtrlName):
oControl = self.getControl( cCtrlName )
return oControl.getSelectedItemsPos()
#--------------------------------------------------
# com.sun.star.awt.UnoControlComboBoxModel
#--------------------------------------------------
def addComboBox( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
bDropdown=True,
itemListenerProc=None,
actionListenerProc=None ):
mod = self.addControl( "com.sun.star.awt.UnoControlComboBoxModel",
cCtrlName, nPositionX, nPositionY, nWidth, nHeight,bDropdown)
if itemListenerProc != None:
self.addItemListenerProc( cCtrlName, itemListenerProc )
if actionListenerProc != None:
self.addActionListenerProc( cCtrlName, actionListenerProc )
def setComboBoxText( self, cCtrlName, cText ):
"""Set the text of the ComboBox."""
oControl = self.getControl( cCtrlName )
oControl.setText( cText )
def getComboBoxText( self, cCtrlName):
"""Set the text of the ComboBox."""
oControl = self.getControl( cCtrlName )
return oControl.getText()
def getComboBoxSelectedText( self, cCtrlName ):
"""Get the selected text of the ComboBox."""
oControl = self.getControl( cCtrlName )
return oControl.getSelectedText();
def getControl( self, cCtrlName ):
"""Get the control (not its model) for a particular control name.
The control returned includes the service com.sun.star.awt.UnoControl,
and another control-specific service which inherits from it.
"""
oControl = self.oDialogControl.getControl( cCtrlName )
return oControl
def getControlModel( self, cCtrlName ):
"""Get the control model (not the control) for a particular control name.
The model returned includes the service UnoControlModel,
and another control-specific service which inherits from it.
"""
oControl = self.getControl( cCtrlName )
oControlModel = oControl.getModel()
return oControlModel
#---------------------------------------------------
# com.sun.star.awt.UnoControlImageControlModel
#---------------------------------------------------
def addImageControl( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
sImagePath="",
itemListenerProc=None,
actionListenerProc=None ):
mod = self.addControl( "com.sun.star.awt.UnoControlImageControlModel",
cCtrlName, nPositionX, nPositionY, nWidth, nHeight, sImagePath=sImagePath)
if itemListenerProc != None:
self.addItemListenerProc( cCtrlName, itemListenerProc )
if actionListenerProc != None:
self.addActionListenerProc( cCtrlName, actionListenerProc )
#--------------------------------------------------
# Adjust properties of control models
#--------------------------------------------------
def setControlModelProperty( self, cCtrlName, cPropertyName, uValue ):
"""Set the value of a property of a control's model.
This affects the control model, not the control.
"""
oControlModel = self.getControlModel( cCtrlName )
oControlModel.setPropertyValue( cPropertyName, uValue )
def getControlModelProperty( self, cCtrlName, cPropertyName ):
"""Get the value of a property of a control's model.
This affects the control model, not the control.
"""
oControlModel = self.getControlModel( cCtrlName )
return oControlModel.getPropertyValue( cPropertyName )
#--------------------------------------------------
# Sugar coated property adjustments to control models.
#--------------------------------------------------
def setEnabled( self, cCtrlName, bEnabled=True ):
"""Supported controls...
UnoControlButtonModel
UnoControlCheckBoxModel
"""
self.setControlModelProperty( cCtrlName, "Enabled", bEnabled )
def getEnabled( self, cCtrlName ):
"""Supported controls...
UnoControlButtonModel
UnoControlCheckBoxModel
"""
return self.getControlModelProperty( cCtrlName, "Enabled" )
def setState( self, cCtrlName, nState ):
"""Supported controls...
UnoControlButtonModel
UnoControlCheckBoxModel
"""
self.setControlModelProperty( cCtrlName, "Status", nState )
def getState( self, cCtrlName ):
"""Supported controls...
UnoControlButtonModel
UnoControlCheckBoxModel
"""
return self.getControlModelProperty( cCtrlName, "Status" )
def setLabel( self, cCtrlName, cLabel ):
"""Supported controls...
UnoControlButtonModel
UnoControlCheckBoxModel
"""
self.setControlModelProperty( cCtrlName, "Label", cLabel )
def getLabel( self, cCtrlName ):
"""Supported controls...
UnoControlButtonModel
UnoControlCheckBoxModel
"""
return self.getControlModelProperty( cCtrlName, "Label" )
def setHelpText( self, cCtrlName, cHelpText ):
"""Supported controls...
UnoControlButtonModel
UnoControlCheckBoxModel
"""
self.setControlModelProperty( cCtrlName, "HelpText", cHelpText )
def getHelpText( self, cCtrlName ):
"""Supported controls...
UnoControlButtonModel
UnoControlCheckBoxModel
"""
return self.getControlModelProperty( cCtrlName, "HelpText" )
#--------------------------------------------------
# Adjust controls (not models)
#--------------------------------------------------
# The following apply to all controls which are a
# com.sun.star.awt.UnoControl
def setDesignMode( self, cCtrlName, bDesignMode=True ):
oControl = self.getControl( cCtrlName )
oControl.setDesignMode( bDesignMode )
def isDesignMode( self, cCtrlName, bDesignMode=True ):
oControl = self.getControl( cCtrlName )
return oControl.isDesignMode()
def isTransparent( self, cCtrlName, bDesignMode=True ):
oControl = self.getControl( cCtrlName )
return oControl.isTransparent()
# The following apply to all controls which are a
# com.sun.star.awt.UnoControlDialogElement
def setPosition( self, cCtrlName, nPositionX, nPositionY ):
self.setControlModelProperty( cCtrlName, "PositionX", nPositionX )
self.setControlModelProperty( cCtrlName, "PositionY", nPositionY )
def setPositionX( self, cCtrlName, nPositionX ):
self.setControlModelProperty( cCtrlName, "PositionX", nPositionX )
def setPositionY( self, cCtrlName, nPositionY ):
self.setControlModelProperty( cCtrlName, "PositionY", nPositionY )
def getPositionX( self, cCtrlName ):
return self.getControlModelProperty( cCtrlName, "PositionX" )
def getPositionY( self, cCtrlName ):
return self.getControlModelProperty( cCtrlName, "PositionY" )
def setSize( self, cCtrlName, nWidth, nHeight ):
self.setControlModelProperty( cCtrlName, "Width", nWidth )
self.setControlModelProperty( cCtrlName, "Height", nHeight )
def setWidth( self, cCtrlName, nWidth ):
self.setControlModelProperty( cCtrlName, "Width", nWidth )
def setHeight( self, cCtrlName, nHeight ):
self.setControlModelProperty( cCtrlName, "Height", nHeight )
def getWidth( self, cCtrlName ):
return self.getControlModelProperty( cCtrlName, "Width" )
def getHeight( self, cCtrlName ):
return self.getControlModelProperty( cCtrlName, "Height" )
def setTabIndex( self, cCtrlName, nWidth, nTabIndex ):
self.setControlModelProperty( cCtrlName, "TabIndex", nTabIndex )
def getTabIndex( self, cCtrlName ):
return self.getControlModelProperty( cCtrlName, "TabIndex" )
def setStep( self, cCtrlName, nWidth, nStep ):
self.setControlModelProperty( cCtrlName, "Step", nStep )
def getStep( self, cCtrlName ):
return self.getControlModelProperty( cCtrlName, "Step" )
def setTag( self, cCtrlName, nWidth, cTag ):
self.setControlModelProperty( cCtrlName, "Tag", cTag )
def getTag( self, cCtrlName ):
return self.getControlModelProperty( cCtrlName, "Tag" )
def setEchoChar(self, cCtrlName , cVal):
self.setControlModelProperty(cCtrlName, "EchoChar", cVal)
def getEchoChar(self, cCtrlName):
return self.setControlModelProperty(cCtrlName, "EchoChar")
#--------------------------------------------------
# Add listeners to controls.
#--------------------------------------------------
# This applies to...
# UnoControlButton
def addActionListenerProc( self, cCtrlName, actionListenerProc ):
"""Create an com.sun.star.awt.XActionListener object and add it to a control.
A listener object is created which will call the python procedure actionListenerProc.
The actionListenerProc can be either a method or a global procedure.
The following controls support XActionListener:
UnoControlButton
"""
oControl = self.getControl( cCtrlName )
oActionListener = ActionListenerProcAdapter( actionListenerProc )
oControl.addActionListener( oActionListener )
# This applies to...
# UnoControlCheckBox
def addItemListenerProc( self, cCtrlName, itemListenerProc ):
"""Create an com.sun.star.awt.XItemListener object and add it to a control.
A listener object is created which will call the python procedure itemListenerProc.
The itemListenerProc can be either a method or a global procedure.
The following controls support XActionListener:
UnoControlCheckBox
"""
oControl = self.getControl( cCtrlName )
oActionListener = ItemListenerProcAdapter( itemListenerProc )
oControl.addItemListener( oActionListener )
#--------------------------------------------------
# Display the modal dialog.
#--------------------------------------------------
def doModalDialog( self, sObjName,sValue):
"""Display the dialog as a modal dialog."""
self.oDialogControl.setVisible( True )
if not sValue==None:
self.selectListBoxItem( sObjName, sValue, True )
self.oDialogControl.execute()
def endExecute( self ):
"""Call this from within one of the listeners to end the modal dialog.
For instance, the listener on your OK or Cancel button would call this to end the dialog.
"""
self.oDialogControl.endExecute()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
skirsdeda/django | django/contrib/flatpages/models.py | 35 | 1531 | from __future__ import unicode_literals
from django.db import models
from django.contrib.sites.models import Site
from django.core.urlresolvers import get_script_prefix
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import iri_to_uri, python_2_unicode_compatible
@python_2_unicode_compatible
class FlatPage(models.Model):
url = models.CharField(_('URL'), max_length=100, db_index=True)
title = models.CharField(_('title'), max_length=200)
content = models.TextField(_('content'), blank=True)
enable_comments = models.BooleanField(_('enable comments'), default=False)
template_name = models.CharField(_('template name'), max_length=70, blank=True,
help_text=_(
"Example: 'flatpages/contact_page.html'. If this isn't provided, "
"the system will use 'flatpages/default.html'."
),
)
registration_required = models.BooleanField(_('registration required'),
help_text=_("If this is checked, only logged-in users will be able to view the page."),
default=False)
sites = models.ManyToManyField(Site)
class Meta:
db_table = 'django_flatpage'
verbose_name = _('flat page')
verbose_name_plural = _('flat pages')
ordering = ('url',)
def __str__(self):
return "%s -- %s" % (self.url, self.title)
def get_absolute_url(self):
# Handle script prefix manually because we bypass reverse()
return iri_to_uri(get_script_prefix().rstrip('/') + self.url)
| bsd-3-clause |
agustinhenze/nikola.debian | nikola/plugins/command/check.py | 3 | 16206 | # -*- coding: utf-8 -*-
# Copyright © 2012-2015 Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Check the generated site."""
from __future__ import print_function
from collections import defaultdict
import os
import re
import sys
import time
try:
from urllib import unquote
from urlparse import urlparse, urljoin, urldefrag
except ImportError:
from urllib.parse import unquote, urlparse, urljoin, urldefrag # NOQA
from doit.loader import generate_tasks
import lxml.html
import requests
from nikola.plugin_categories import Command
from nikola.utils import get_logger, STDERR_HANDLER
def _call_nikola_list(site):
files = []
deps = defaultdict(list)
for task in generate_tasks('render_site', site.gen_tasks('render_site', "Task", '')):
files.extend(task.targets)
for target in task.targets:
deps[target].extend(task.file_dep)
for task in generate_tasks('post_render', site.gen_tasks('render_site', "LateTask", '')):
files.extend(task.targets)
for target in task.targets:
deps[target].extend(task.file_dep)
return files, deps
def real_scan_files(site):
"""Scan for files."""
task_fnames = set([])
real_fnames = set([])
output_folder = site.config['OUTPUT_FOLDER']
# First check that all targets are generated in the right places
for fname in _call_nikola_list(site)[0]:
fname = fname.strip()
if fname.startswith(output_folder):
task_fnames.add(fname)
# And now check that there are no non-target files
for root, dirs, files in os.walk(output_folder, followlinks=True):
for src_name in files:
fname = os.path.join(root, src_name)
real_fnames.add(fname)
only_on_output = list(real_fnames - task_fnames)
only_on_input = list(task_fnames - real_fnames)
return (only_on_output, only_on_input)
def fs_relpath_from_url_path(url_path):
"""Create a filesystem relative path from an URL path."""
# Expects as input an urlparse(s).path
url_path = unquote(url_path)
# in windows relative paths don't begin with os.sep
if sys.platform == 'win32' and len(url_path):
url_path = url_path.replace('/', '\\')
return url_path
class CommandCheck(Command):
"""Check the generated site."""
name = "check"
logger = None
doc_usage = "[-v] (-l [--find-sources] [-r] | -f [--clean-files])"
doc_purpose = "check links and files in the generated site"
cmd_options = [
{
'name': 'links',
'short': 'l',
'long': 'check-links',
'type': bool,
'default': False,
'help': 'Check for dangling links',
},
{
'name': 'files',
'short': 'f',
'long': 'check-files',
'type': bool,
'default': False,
'help': 'Check for unknown (orphaned and not generated) files',
},
{
'name': 'clean',
'long': 'clean-files',
'type': bool,
'default': False,
'help': 'Remove all unknown files, use with caution',
},
{
'name': 'find_sources',
'long': 'find-sources',
'type': bool,
'default': False,
'help': 'List possible source files for files with broken links.',
},
{
'name': 'verbose',
'long': 'verbose',
'short': 'v',
'type': bool,
'default': False,
'help': 'Be more verbose.',
},
{
'name': 'remote',
'long': 'remote',
'short': 'r',
'type': bool,
'default': False,
'help': 'Check that remote links work.',
},
]
def _execute(self, options, args):
"""Check the generated site."""
self.logger = get_logger('check', STDERR_HANDLER)
if not options['links'] and not options['files'] and not options['clean']:
print(self.help())
return False
if options['verbose']:
self.logger.level = 1
else:
self.logger.level = 4
if options['links']:
failure = self.scan_links(options['find_sources'], options['remote'])
if options['files']:
failure = self.scan_files()
if options['clean']:
failure = self.clean_files()
if failure:
return 1
existing_targets = set([])
checked_remote_targets = {}
def analyze(self, fname, find_sources=False, check_remote=False):
"""Analyze links on a page."""
rv = False
self.whitelist = [re.compile(x) for x in self.site.config['LINK_CHECK_WHITELIST']]
base_url = urlparse(self.site.config['BASE_URL'])
self.existing_targets.add(self.site.config['SITE_URL'])
self.existing_targets.add(self.site.config['BASE_URL'])
url_type = self.site.config['URL_TYPE']
deps = {}
if find_sources:
deps = _call_nikola_list(self.site)[1]
if url_type in ('absolute', 'full_path'):
url_netloc_to_root = urlparse(self.site.config['BASE_URL']).path
try:
filename = fname
if filename.startswith(self.site.config['CACHE_FOLDER']):
# Do not look at links in the cache, which are not parsed by
# anyone and may result in false positives. Problems arise
# with galleries, for example. Full rationale: (Issue #1447)
self.logger.notice("Ignoring {0} (in cache, links may be incorrect)".format(filename))
return False
if not os.path.exists(fname):
# Quietly ignore files that don’t exist; use `nikola check -f` instead (Issue #1831)
return False
d = lxml.html.fromstring(open(filename, 'rb').read())
for l in d.iterlinks():
target = l[2]
if target == "#":
continue
target, _ = urldefrag(target)
parsed = urlparse(target)
# Warn about links from https to http (mixed-security)
if base_url.netloc == parsed.netloc and base_url.scheme == "https" and parsed.scheme == "http":
self.logger.warn("Mixed-content security for link in {0}: {1}".format(filename, target))
# Absolute links to other domains, skip
# Absolute links when using only paths, skip.
if ((parsed.scheme or target.startswith('//')) and parsed.netloc != base_url.netloc) or \
((parsed.scheme or target.startswith('//')) and url_type in ('rel_path', 'full_path')):
if not check_remote or parsed.scheme not in ["http", "https"]:
continue
if parsed.netloc == base_url.netloc: # absolute URL to self.site
continue
if target in self.checked_remote_targets: # already checked this exact target
if self.checked_remote_targets[target] in [301, 307]:
self.logger.warn("Remote link PERMANENTLY redirected in {0}: {1} [Error {2}]".format(filename, target, self.checked_remote_targets[target]))
elif self.checked_remote_targets[target] in [302, 308]:
self.logger.info("Remote link temporarily redirected in {1}: {2} [HTTP: {3}]".format(filename, target, self.checked_remote_targets[target]))
elif self.checked_remote_targets[target] > 399:
self.logger.error("Broken link in {0}: {1} [Error {2}]".format(filename, target, self.checked_remote_targets[target]))
continue
# Skip whitelisted targets
if any(re.search(_, target) for _ in self.whitelist):
continue
# Check the remote link works
req_headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0 (Nikola)'} # I’m a real boy!
resp = requests.head(target, headers=req_headers, allow_redirects=False)
# Retry client errors (4xx) as GET requests because many servers are broken
if resp.status_code >= 400 and resp.status_code <= 499:
time.sleep(0.5)
resp = requests.get(target, headers=req_headers, allow_redirects=False)
# Follow redirects and see where they lead, redirects to errors will be reported twice
if resp.status_code in [301, 302, 307, 308]:
redir_status_code = resp.status_code
time.sleep(0.5)
# Known redirects are retested using GET because IIS servers otherwise get HEADaches
resp = requests.get(target, headers=req_headers, allow_redirects=True)
# Permanent redirects should be updated
if redir_status_code in [301, 308]:
self.logger.warn("Remote link moved PERMANENTLY to \"{0}\" and should be updated in {1}: {2} [HTTP: {3}]".format(resp.url, filename, target, redir_status_code))
if redir_status_code in [302, 307]:
self.logger.info("Remote link temporarily redirected to \"{0}\" in {1}: {2} [HTTP: {3}]".format(resp.url, filename, target, redir_status_code))
self.checked_remote_targets[resp.url] = resp.status_code
self.checked_remote_targets[target] = redir_status_code
else:
self.checked_remote_targets[target] = resp.status_code
if resp.status_code > 399: # Error
self.logger.error("Broken link in {0}: {1} [Error {2}]".format(filename, target, resp.status_code))
continue
elif resp.status_code <= 399: # The address leads *somewhere* that is not an error
self.logger.debug("Successfully checked remote link in {0}: {1} [HTTP: {2}]".format(filename, target, resp.status_code))
continue
self.logger.warn("Could not check remote link in {0}: {1} [Unknown problem]".format(filename, target))
continue
if url_type == 'rel_path':
if target.startswith('/'):
target_filename = os.path.abspath(
os.path.join(self.site.config['OUTPUT_FOLDER'], unquote(target.lstrip('/'))))
else: # Relative path
target_filename = os.path.abspath(
os.path.join(os.path.dirname(filename), unquote(target)))
elif url_type in ('full_path', 'absolute'):
if url_type == 'absolute':
# convert to 'full_path' case, ie url relative to root
url_rel_path = parsed.path[len(url_netloc_to_root):]
else:
# convert to relative to base path
url_rel_path = target[len(url_netloc_to_root):]
if url_rel_path == '' or url_rel_path.endswith('/'):
url_rel_path = urljoin(url_rel_path, self.site.config['INDEX_FILE'])
fs_rel_path = fs_relpath_from_url_path(url_rel_path)
target_filename = os.path.join(self.site.config['OUTPUT_FOLDER'], fs_rel_path)
if any(re.search(x, target_filename) for x in self.whitelist):
continue
elif target_filename not in self.existing_targets:
if os.path.exists(target_filename):
self.logger.notice("Good link {0} => {1}".format(target, target_filename))
self.existing_targets.add(target_filename)
else:
rv = True
self.logger.warn("Broken link in {0}: {1}".format(filename, target))
if find_sources:
self.logger.warn("Possible sources:")
self.logger.warn("\n".join(deps[filename]))
self.logger.warn("===============================\n")
except Exception as exc:
self.logger.error("Error with: {0} {1}".format(filename, exc))
return rv
def scan_links(self, find_sources=False, check_remote=False):
"""Check links on the site."""
self.logger.info("Checking Links:")
self.logger.info("===============\n")
self.logger.notice("{0} mode".format(self.site.config['URL_TYPE']))
failure = False
# Maybe we should just examine all HTML files
output_folder = self.site.config['OUTPUT_FOLDER']
for fname in _call_nikola_list(self.site)[0]:
if fname.startswith(output_folder) and '.html' == fname[-5:]:
if self.analyze(fname, find_sources, check_remote):
failure = True
if not failure:
self.logger.info("All links checked.")
return failure
def scan_files(self):
"""Check files in the site, find missing and orphaned files."""
failure = False
self.logger.info("Checking Files:")
self.logger.info("===============\n")
only_on_output, only_on_input = real_scan_files(self.site)
# Ignore folders
only_on_output = [p for p in only_on_output if not os.path.isdir(p)]
only_on_input = [p for p in only_on_input if not os.path.isdir(p)]
if only_on_output:
only_on_output.sort()
self.logger.warn("Files from unknown origins (orphans):")
for f in only_on_output:
self.logger.warn(f)
failure = True
if only_on_input:
only_on_input.sort()
self.logger.warn("Files not generated:")
for f in only_on_input:
self.logger.warn(f)
if not failure:
self.logger.info("All files checked.")
return failure
def clean_files(self):
"""Remove orphaned files."""
only_on_output, _ = real_scan_files(self.site)
for f in only_on_output:
self.logger.info('removed: {0}'.format(f))
os.unlink(f)
# Find empty directories and remove them
output_folder = self.site.config['OUTPUT_FOLDER']
all_dirs = []
for root, dirs, files in os.walk(output_folder, followlinks=True):
all_dirs.append(root)
all_dirs.sort(key=len, reverse=True)
for d in all_dirs:
try:
os.rmdir(d)
self.logger.info('removed: {0}/'.format(d))
except OSError:
pass
return True
| mit |
2014c2g5/2014c2 | exts/w2/static/Brython2.0.0-20140209-164925/Lib/linecache.py | 785 | 3864 | """Cache lines from files.
This is intended to read lines from modules imported -- hence if a filename
is not found, it will look down the module search path for a file by
that name.
"""
import sys
import os
import tokenize
__all__ = ["getline", "clearcache", "checkcache"]
def getline(filename, lineno, module_globals=None):
lines = getlines(filename, module_globals)
if 1 <= lineno <= len(lines):
return lines[lineno-1]
else:
return ''
# The cache
cache = {} # The cache
def clearcache():
"""Clear the cache entirely."""
global cache
cache = {}
def getlines(filename, module_globals=None):
"""Get the lines for a file from the cache.
Update the cache if it doesn't contain an entry for this file already."""
if filename in cache:
return cache[filename][2]
else:
return updatecache(filename, module_globals)
def checkcache(filename=None):
"""Discard cache entries that are out of date.
(This is not checked upon each call!)"""
if filename is None:
filenames = list(cache.keys())
else:
if filename in cache:
filenames = [filename]
else:
return
for filename in filenames:
size, mtime, lines, fullname = cache[filename]
if mtime is None:
continue # no-op for files loaded via a __loader__
try:
stat = os.stat(fullname)
except os.error:
del cache[filename]
continue
if size != stat.st_size or mtime != stat.st_mtime:
del cache[filename]
def updatecache(filename, module_globals=None):
"""Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list."""
if filename in cache:
del cache[filename]
if not filename or (filename.startswith('<') and filename.endswith('>')):
return []
fullname = filename
try:
stat = os.stat(fullname)
except OSError:
basename = filename
# Try for a __loader__, if available
if module_globals and '__loader__' in module_globals:
name = module_globals.get('__name__')
loader = module_globals['__loader__']
get_source = getattr(loader, 'get_source', None)
if name and get_source:
try:
data = get_source(name)
except (ImportError, IOError):
pass
else:
if data is None:
# No luck, the PEP302 loader cannot find the source
# for this module.
return []
cache[filename] = (
len(data), None,
[line+'\n' for line in data.splitlines()], fullname
)
return cache[filename][2]
# Try looking through the module search path, which is only useful
# when handling a relative filename.
if os.path.isabs(filename):
return []
for dirname in sys.path:
try:
fullname = os.path.join(dirname, basename)
except (TypeError, AttributeError):
# Not sufficiently string-like to do anything useful with.
continue
try:
stat = os.stat(fullname)
break
except os.error:
pass
else:
return []
try:
with tokenize.open(fullname) as fp:
lines = fp.readlines()
except IOError:
return []
if lines and not lines[-1].endswith('\n'):
lines[-1] += '\n'
size, mtime = stat.st_size, stat.st_mtime
cache[filename] = size, mtime, lines, fullname
return lines
| gpl-2.0 |
bclau/nova | nova/objects/base.py | 4 | 21053 | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Nova common internal object model"""
import collections
import copy
import functools
from nova import context
from nova import exception
from nova.objects import utils as obj_utils
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.openstack.common.rpc import common as rpc_common
import nova.openstack.common.rpc.serializer
LOG = logging.getLogger('object')
class NotSpecifiedSentinel:
pass
def get_attrname(name):
"""Return the mangled name of the attribute's underlying storage."""
return '_%s' % name
def make_class_properties(cls):
# NOTE(danms/comstud): Inherit fields from super classes.
# mro() returns the current class first and returns 'object' last, so
# those can be skipped. Also be careful to not overwrite any fields
# that already exist. And make sure each cls has its own copy of
# fields and that it is not sharing the dict with a super class.
cls.fields = dict(cls.fields)
for supercls in cls.mro()[1:-1]:
if not hasattr(supercls, 'fields'):
continue
for field, typefn in supercls.fields.items():
if field not in cls.fields:
cls.fields[field] = typefn
for name, typefn in cls.fields.iteritems():
def getter(self, name=name):
attrname = get_attrname(name)
if not hasattr(self, attrname):
self.obj_load_attr(name)
return getattr(self, attrname)
def setter(self, value, name=name, typefn=typefn):
self._changed_fields.add(name)
try:
return setattr(self, get_attrname(name), typefn(value))
except Exception:
attr = "%s.%s" % (self.obj_name(), name)
LOG.exception(_('Error setting %(attr)s') %
{'attr': attr})
raise
setattr(cls, name, property(getter, setter))
class NovaObjectMetaclass(type):
"""Metaclass that allows tracking of object classes."""
# NOTE(danms): This is what controls whether object operations are
# remoted. If this is not None, use it to remote things over RPC.
indirection_api = None
def __init__(cls, names, bases, dict_):
if not hasattr(cls, '_obj_classes'):
# This will be set in the 'NovaObject' class.
cls._obj_classes = collections.defaultdict(list)
else:
# Add the subclass to NovaObject._obj_classes
make_class_properties(cls)
cls._obj_classes[cls.obj_name()].append(cls)
# These are decorators that mark an object's method as remotable.
# If the metaclass is configured to forward object methods to an
# indirection service, these will result in making an RPC call
# instead of directly calling the implementation in the object. Instead,
# the object implementation on the remote end will perform the
# requested action and the result will be returned here.
def remotable_classmethod(fn):
"""Decorator for remotable classmethods."""
@functools.wraps(fn)
def wrapper(cls, context, *args, **kwargs):
if NovaObject.indirection_api:
result = NovaObject.indirection_api.object_class_action(
context, cls.obj_name(), fn.__name__, cls.version,
args, kwargs)
else:
result = fn(cls, context, *args, **kwargs)
if isinstance(result, NovaObject):
result._context = context
return result
return classmethod(wrapper)
# See comment above for remotable_classmethod()
#
# Note that this will use either the provided context, or the one
# stashed in the object. If neither are present, the object is
# "orphaned" and remotable methods cannot be called.
def remotable(fn):
"""Decorator for remotable object methods."""
@functools.wraps(fn)
def wrapper(self, *args, **kwargs):
ctxt = self._context
try:
if isinstance(args[0], (context.RequestContext,
rpc_common.CommonRpcContext)):
ctxt = args[0]
args = args[1:]
except IndexError:
pass
if ctxt is None:
raise exception.OrphanedObjectError(method=fn.__name__,
objtype=self.obj_name())
# Force this to be set if it wasn't before.
self._context = ctxt
if NovaObject.indirection_api:
updates, result = NovaObject.indirection_api.object_action(
ctxt, self, fn.__name__, args, kwargs)
for key, value in updates.iteritems():
if key in self.fields:
self[key] = self._attr_from_primitive(key, value)
self._changed_fields = set(updates.get('obj_what_changed', []))
return result
else:
return fn(self, ctxt, *args, **kwargs)
return wrapper
# Object versioning rules
#
# Each service has its set of objects, each with a version attached. When
# a client attempts to call an object method, the server checks to see if
# the version of that object matches (in a compatible way) its object
# implementation. If so, cool, and if not, fail.
def check_object_version(server, client):
try:
client_major, _client_minor = client.split('.')
server_major, _server_minor = server.split('.')
client_minor = int(_client_minor)
server_minor = int(_server_minor)
except ValueError:
raise exception.IncompatibleObjectVersion(
_('Invalid version string'))
if client_major != server_major:
raise exception.IncompatibleObjectVersion(
dict(client=client_major, server=server_major))
if client_minor > server_minor:
raise exception.IncompatibleObjectVersion(
dict(client=client_minor, server=server_minor))
class NovaObject(object):
"""Base class and object factory.
This forms the base of all objects that can be remoted or instantiated
via RPC. Simply defining a class that inherits from this base class
will make it remotely instantiatable. Objects should implement the
necessary "get" classmethod routines as well as "save" object methods
as appropriate.
"""
__metaclass__ = NovaObjectMetaclass
# Version of this object (see rules above check_object_version())
version = '1.0'
# The fields present in this object as key:typefn pairs. For example:
#
# fields = { 'foo': int,
# 'bar': str,
# 'baz': lambda x: str(x).ljust(8),
# }
fields = {}
obj_extra_fields = []
def __init__(self):
self._changed_fields = set()
self._context = None
@classmethod
def obj_name(cls):
"""Return a canonical name for this object which will be used over
the wire for remote hydration.
"""
return cls.__name__
@classmethod
def obj_class_from_name(cls, objname, objver):
"""Returns a class from the registry based on a name and version."""
if objname not in cls._obj_classes:
LOG.error(_('Unable to instantiate unregistered object type '
'%(objtype)s') % dict(objtype=objname))
raise exception.UnsupportedObjectError(objtype=objname)
compatible_match = None
for objclass in cls._obj_classes[objname]:
if objclass.version == objver:
return objclass
try:
check_object_version(objclass.version, objver)
compatible_match = objclass
except exception.IncompatibleObjectVersion:
pass
if compatible_match:
return compatible_match
raise exception.IncompatibleObjectVersion(objname=objname,
objver=objver)
def _attr_from_primitive(self, attribute, value):
"""Attribute deserialization dispatcher.
This calls self._attr_foo_from_primitive(value) for an attribute
foo with value, if it exists, otherwise it assumes the value
is suitable for the attribute's setter method.
"""
handler = '_attr_%s_from_primitive' % attribute
if hasattr(self, handler):
return getattr(self, handler)(value)
return value
@classmethod
def obj_from_primitive(cls, primitive, context=None):
"""Simple base-case hydration.
This calls self._attr_from_primitive() for each item in fields.
"""
if primitive['nova_object.namespace'] != 'nova':
# NOTE(danms): We don't do anything with this now, but it's
# there for "the future"
raise exception.UnsupportedObjectError(
objtype='%s.%s' % (primitive['nova_object.namespace'],
primitive['nova_object.name']))
objname = primitive['nova_object.name']
objver = primitive['nova_object.version']
objdata = primitive['nova_object.data']
objclass = cls.obj_class_from_name(objname, objver)
self = objclass()
self._context = context
for name in self.fields:
if name in objdata:
setattr(self, name,
self._attr_from_primitive(name, objdata[name]))
changes = primitive.get('nova_object.changes', [])
self._changed_fields = set([x for x in changes if x in self.fields])
return self
def _attr_to_primitive(self, attribute):
"""Attribute serialization dispatcher.
This calls self._attr_foo_to_primitive() for an attribute foo,
if it exists, otherwise it assumes the attribute itself is
primitive-enough to be sent over the RPC wire.
"""
handler = '_attr_%s_to_primitive' % attribute
if hasattr(self, handler):
return getattr(self, handler)()
else:
return getattr(self, attribute)
def obj_clone(self):
"""Create a copy."""
return copy.deepcopy(self)
def obj_to_primitive(self):
"""Simple base-case dehydration.
This calls self._attr_to_primitive() for each item in fields.
"""
primitive = dict()
for name in self.fields:
if self.obj_attr_is_set(name):
primitive[name] = self._attr_to_primitive(name)
obj = {'nova_object.name': self.obj_name(),
'nova_object.namespace': 'nova',
'nova_object.version': self.version,
'nova_object.data': primitive}
if self.obj_what_changed():
obj['nova_object.changes'] = list(self.obj_what_changed())
return obj
def obj_load_attr(self, attrname):
"""Load an additional attribute from the real object.
This should use self._conductor, and cache any data that might
be useful for future load operations.
"""
raise NotImplementedError(
_("Cannot load '%s' in the base class") % attrname)
def save(self, context):
"""Save the changed fields back to the store.
This is optional for subclasses, but is presented here in the base
class for consistency among those that do.
"""
raise NotImplementedError('Cannot save anything in the base class')
def obj_what_changed(self):
"""Returns a set of fields that have been modified."""
return self._changed_fields
def obj_get_changes(self):
"""Returns a dict of changed fields and their new values."""
changes = {}
for key in self.obj_what_changed():
changes[key] = self[key]
return changes
def obj_reset_changes(self, fields=None):
"""Reset the list of fields that have been changed.
Note that this is NOT "revert to previous values"
"""
if fields:
self._changed_fields -= set(fields)
else:
self._changed_fields.clear()
def obj_attr_is_set(self, attrname):
"""Test object to see if attrname is present.
Returns True if the named attribute has a value set, or
False if not. Raises AttributeError if attrname is not
a valid attribute for this object.
"""
if attrname not in self.obj_fields:
raise AttributeError(
_("%(objname)s object has no attribute '%(attrname)s'") %
{'objname': self.obj_name(), 'attrname': attrname})
return hasattr(self, get_attrname(attrname))
@property
def obj_fields(self):
return self.fields.keys() + self.obj_extra_fields
# dictish syntactic sugar
def iteritems(self):
"""For backwards-compatibility with dict-based objects.
NOTE(danms): May be removed in the future.
"""
for name in self.obj_fields:
if (self.obj_attr_is_set(name) or
name in self.obj_extra_fields):
yield name, getattr(self, name)
items = lambda self: list(self.iteritems())
def __getitem__(self, name):
"""For backwards-compatibility with dict-based objects.
NOTE(danms): May be removed in the future.
"""
return getattr(self, name)
def __setitem__(self, name, value):
"""For backwards-compatibility with dict-based objects.
NOTE(danms): May be removed in the future.
"""
setattr(self, name, value)
def __contains__(self, name):
"""For backwards-compatibility with dict-based objects.
NOTE(danms): May be removed in the future.
"""
try:
return self.obj_attr_is_set(name)
except AttributeError:
return False
def get(self, key, value=NotSpecifiedSentinel):
"""For backwards-compatibility with dict-based objects.
NOTE(danms): May be removed in the future.
"""
if key not in self.obj_fields:
raise AttributeError("'%s' object has no attribute '%s'" % (
self.__class__, key))
if value != NotSpecifiedSentinel and not self.obj_attr_is_set(key):
return value
else:
return self[key]
def update(self, updates):
"""For backwards-compatibility with dict-base objects.
NOTE(danms): May be removed in the future.
"""
for key, value in updates.items():
self[key] = value
class NovaPersistentObject(object):
"""Mixin class for Persistent objects.
This adds the fields that we use in common for all persisent objects.
"""
fields = {
'created_at': obj_utils.datetime_or_str_or_none,
'updated_at': obj_utils.datetime_or_str_or_none,
'deleted_at': obj_utils.datetime_or_str_or_none,
'deleted': bool,
}
_attr_created_at_from_primitive = obj_utils.dt_deserializer
_attr_updated_at_from_primitive = obj_utils.dt_deserializer
_attr_deleted_at_from_primitive = obj_utils.dt_deserializer
_attr_created_at_to_primitive = obj_utils.dt_serializer('created_at')
_attr_updated_at_to_primitive = obj_utils.dt_serializer('updated_at')
_attr_deleted_at_to_primitive = obj_utils.dt_serializer('deleted_at')
class ObjectListBase(object):
"""Mixin class for lists of objects.
This mixin class can be added as a base class for an object that
is implementing a list of objects. It adds a single field of 'objects',
which is the list store, and behaves like a list itself. It supports
serialization of the list of objects automatically.
"""
fields = {
'objects': list,
}
def __iter__(self):
"""List iterator interface."""
return iter(self.objects)
def __len__(self):
"""List length."""
return len(self.objects)
def __getitem__(self, index):
"""List index access."""
if isinstance(index, slice):
new_obj = self.__class__()
new_obj.objects = self.objects[index]
# NOTE(danms): We must be mixed in with a NovaObject!
new_obj.obj_reset_changes()
new_obj._context = self._context
return new_obj
return self.objects[index]
def __contains__(self, value):
"""List membership test."""
return value in self.objects
def count(self, value):
"""List count of value occurrences."""
return self.objects.count(value)
def index(self, value):
"""List index of value."""
return self.objects.index(value)
def _attr_objects_to_primitive(self):
"""Serialization of object list."""
return [x.obj_to_primitive() for x in self.objects]
def _attr_objects_from_primitive(self, value):
"""Deserialization of object list."""
objects = []
for entity in value:
obj = NovaObject.obj_from_primitive(entity, context=self._context)
objects.append(obj)
return objects
class NovaObjectSerializer(nova.openstack.common.rpc.serializer.Serializer):
"""A NovaObject-aware Serializer.
This implements the Oslo Serializer interface and provides the
ability to serialize and deserialize NovaObject entities. Any service
that needs to accept or return NovaObjects as arguments or result values
should pass this to its RpcProxy and RpcDispatcher objects.
"""
def _process_iterable(self, context, action_fn, values):
"""Process an iterable, taking an action on each value.
:param:context: Request context
:param:action_fn: Action to take on each item in values
:param:values: Iterable container of things to take action on
:returns: A new container of the same type (except set) with
items from values having had action applied.
"""
iterable = values.__class__
if iterable == set:
# NOTE(danms): A set can't have an unhashable value inside, such as
# a dict. Convert sets to tuples, which is fine, since we can't
# send them over RPC anyway.
iterable = tuple
return iterable([action_fn(context, value) for value in values])
def serialize_entity(self, context, entity):
if isinstance(entity, (tuple, list, set)):
entity = self._process_iterable(context, self.serialize_entity,
entity)
elif (hasattr(entity, 'obj_to_primitive') and
callable(entity.obj_to_primitive)):
entity = entity.obj_to_primitive()
return entity
def deserialize_entity(self, context, entity):
if isinstance(entity, dict) and 'nova_object.name' in entity:
entity = NovaObject.obj_from_primitive(entity, context=context)
elif isinstance(entity, (tuple, list, set)):
entity = self._process_iterable(context, self.deserialize_entity,
entity)
return entity
def obj_to_primitive(obj):
"""Recursively turn an object into a python primitive.
A NovaObject becomes a dict, and anything that implements ObjectListBase
becomes a list.
"""
if isinstance(obj, ObjectListBase):
return [obj_to_primitive(x) for x in obj]
elif isinstance(obj, NovaObject):
result = {}
for key, value in obj.iteritems():
result[key] = obj_to_primitive(value)
return result
else:
return obj
def obj_make_list(context, list_obj, item_cls, db_list, **extra_args):
"""Construct an object list from a list of primitives.
This calls item_cls._from_db_object() on each item of db_list, and
adds the resulting object to list_obj.
:param:context: Request contextr
:param:list_obj: An ObjectListBase object
:param:item_cls: The NovaObject class of the objects within the list
:param:db_list: The list of primitives to convert to objects
:param:extra_args: Extra arguments to pass to _from_db_object()
:returns: list_obj
"""
list_obj.objects = []
for db_item in db_list:
item = item_cls._from_db_object(context, item_cls(), db_item,
**extra_args)
list_obj.objects.append(item)
list_obj._context = context
list_obj.obj_reset_changes()
return list_obj
| apache-2.0 |
yashu-seth/networkx | networkx/algorithms/coloring/tests/test_coloring.py | 24 | 10511 | # -*- coding: utf-8 -*-
"""Greedy coloring test suite.
Run with nose: nosetests -v test_coloring.py
"""
__author__ = "\n".join(["Christian Olsson <chro@itu.dk>",
"Jan Aagaard Meier <jmei@itu.dk>",
"Henrik Haugbølle <hhau@itu.dk>",
"Jake VanderPlas <jakevdp@uw.edu>"])
import networkx as nx
from nose.tools import *
ALL_STRATEGIES = [
'largest_first',
'random_sequential',
'smallest_last',
'independent_set',
'connected_sequential_bfs',
'connected_sequential_dfs',
'connected_sequential',
'saturation_largest_first',
'DSATUR',
]
# List of strategies where interchange=True results in an error
INTERCHANGE_INVALID = [
'independent_set',
'saturation_largest_first',
'DSATUR'
]
class TestColoring:
def test_basic_cases(self):
def check_basic_case(graph_func, n_nodes, strategy, interchange):
graph = graph_func()
coloring = nx.coloring.greedy_color(graph,
strategy=strategy,
interchange=interchange)
assert_true(verify_length(coloring, n_nodes))
assert_true(verify_coloring(graph, coloring))
for graph_func, n_nodes in BASIC_TEST_CASES.items():
for interchange in [True, False]:
for strategy in ALL_STRATEGIES:
if interchange and (strategy in INTERCHANGE_INVALID):
continue
yield (check_basic_case, graph_func,
n_nodes, strategy, interchange)
def test_special_cases(self):
def check_special_case(strategy, graph_func, interchange, colors):
graph = graph_func()
coloring = nx.coloring.greedy_color(graph,
strategy=strategy,
interchange=interchange)
if not hasattr(colors, '__len__'):
colors = [colors]
assert_true(any(verify_length(coloring, n_colors)
for n_colors in colors))
assert_true(verify_coloring(graph, coloring))
for strategy, arglist in SPECIAL_TEST_CASES.items():
for args in arglist:
yield (check_special_case, strategy, args[0], args[1], args[2])
def test_interchange_invalid(self):
graph = one_node_graph()
def check_raises(strategy):
assert_raises(nx.NetworkXPointlessConcept,
nx.coloring.greedy_color,
graph, strategy=strategy, interchange=True)
for strategy in INTERCHANGE_INVALID:
yield check_raises, strategy
def test_bad_inputs(self):
graph = one_node_graph()
assert_raises(nx.NetworkXError, nx.coloring.greedy_color,
graph, strategy='invalid strategy')
def test_strategy_as_function(self):
graph = lf_shc()
colors_1 = nx.coloring.greedy_color(graph,
'largest_first')
colors_2 = nx.coloring.greedy_color(graph,
nx.coloring.strategy_largest_first)
assert_equal(colors_1, colors_2)
############################## Utility functions ##############################
def verify_coloring(graph, coloring):
for node in graph.nodes():
if node not in coloring:
return False
color = coloring[node]
for neighbor in graph.neighbors(node):
if coloring[neighbor] == color:
return False
return True
def verify_length(coloring, expected):
coloring = dict_to_sets(coloring)
return len(coloring) == expected
def dict_to_sets(colors):
if len(colors) == 0:
return []
k = max(colors.values()) + 1
sets = [set() for _ in range(k)]
for (node, color) in colors.items():
sets[color].add(node)
return sets
############################## Graph Generation ##############################
def empty_graph():
return nx.Graph()
def one_node_graph():
graph = nx.Graph()
graph.add_nodes_from([1])
return graph
def two_node_graph():
graph = nx.Graph()
graph.add_nodes_from([1,2])
graph.add_edges_from([(1,2)])
return graph
def three_node_clique():
graph = nx.Graph()
graph.add_nodes_from([1,2, 3])
graph.add_edges_from([(1,2), (1,3), (2,3)])
return graph
def disconnected():
graph = nx.Graph()
graph.add_edges_from([
(1, 2),
(2, 3),
(4, 5),
(5, 6)
])
return graph
def rs_shc():
graph = nx.Graph()
graph.add_nodes_from([1,2,3,4])
graph.add_edges_from([
(1,2),
(2,3),
(3,4)
])
return graph
def slf_shc():
graph = nx.Graph()
graph.add_nodes_from([1,2,3,4,5,6,7])
graph.add_edges_from([
(1,2),
(1,5),
(1,6),
(2,3),
(2,7),
(3,4),
(3,7),
(4,5),
(4,6),
(5,6)
])
return graph
def slf_hc():
graph = nx.Graph()
graph.add_nodes_from([1,2,3,4,5,6,7,8])
graph.add_edges_from([
(1,2),
(1,3),
(1,4),
(1,5),
(2,3),
(2,4),
(2,6),
(5,7),
(5,8),
(6,7),
(6,8),
(7,8)
])
return graph
def lf_shc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
graph.add_edges_from([
(6, 1),
(1, 4),
(4, 3),
(3, 2),
(2, 5)
])
return graph
def lf_hc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
graph.add_edges_from([
(1, 7),
(1, 6),
(1, 3),
(1, 4),
(7, 2),
(2, 6),
(2, 3),
(2, 5),
(5, 3),
(5, 4),
(4, 3)
])
return graph
def sl_shc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
graph.add_edges_from([
(1, 2),
(1, 3),
(2, 3),
(1, 4),
(2, 5),
(3, 6),
(4, 5),
(4, 6),
(5, 6)
])
return graph
def sl_hc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
graph.add_edges_from([
(1, 2),
(1, 3),
(1, 5),
(1, 7),
(2, 3),
(2, 4),
(2, 8),
(8, 4),
(8, 6),
(8, 7),
(7, 5),
(7, 6),
(3, 4),
(4, 6),
(6, 5),
(5, 3)
])
return graph
def gis_shc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4])
graph.add_edges_from([
(1, 2),
(2, 3),
(3, 4)
])
return graph
def gis_hc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
graph.add_edges_from([
(1, 5),
(2, 5),
(3, 6),
(4, 6),
(5, 6)
])
return graph
def cs_shc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5])
graph.add_edges_from([
(1, 2),
(1, 5),
(2, 3),
(2, 4),
(2, 5),
(3, 4),
(4, 5)
])
return graph
def rsi_shc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
graph.add_edges_from([
(1, 2),
(1, 5),
(1, 6),
(2, 3),
(3, 4),
(4, 5),
(4, 6),
(5, 6)
])
return graph
def lfi_shc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
graph.add_edges_from([
(1, 2),
(1, 5),
(1, 6),
(2, 3),
(2, 7),
(3, 4),
(3, 7),
(4, 5),
(4, 6),
(5, 6)
])
return graph
def lfi_hc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
graph.add_edges_from([
(1, 2),
(1, 5),
(1, 6),
(1, 7),
(2, 3),
(2, 8),
(2, 9),
(3, 4),
(3, 8),
(3, 9),
(4, 5),
(4, 6),
(4, 7),
(5, 6)
])
return graph
def sli_shc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
graph.add_edges_from([
(1, 2),
(1, 3),
(1, 5),
(1, 7),
(2, 3),
(2, 6),
(3, 4),
(4, 5),
(4, 6),
(5, 7),
(6, 7)
])
return graph
def sli_hc():
graph = nx.Graph()
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
graph.add_edges_from([
(1, 2),
(1, 3),
(1, 4),
(1, 5),
(2, 3),
(2, 7),
(2, 8),
(2, 9),
(3, 6),
(3, 7),
(3, 9),
(4, 5),
(4, 6),
(4, 8),
(4, 9),
(5, 6),
(5, 7),
(5, 8),
(6, 7),
(6, 9),
(7, 8),
(8, 9)
])
return graph
#---------------------------------------------------------------------------
# Basic tests for all strategies
# For each basic graph function, specify the number of expected colors.
BASIC_TEST_CASES = {empty_graph: 0,
one_node_graph: 1,
two_node_graph: 2,
disconnected: 2,
three_node_clique: 3}
#---------------------------------------------------------------------------
# Special test cases. Each strategy has a list of tuples of the form
# (graph function, interchange, valid # of colors)
SPECIAL_TEST_CASES = {
'random_sequential': [
(rs_shc, False, (2, 3)),
(rs_shc, True, 2),
(rsi_shc, True, (3, 4))],
'saturation_largest_first': [
(slf_shc, False, (3, 4)),
(slf_hc, False, 4)],
'largest_first': [
(lf_shc, False, (2, 3)),
(lf_hc, False, 4),
(lf_shc, True, 2),
(lf_hc, True, 3),
(lfi_shc, True, (3, 4)),
(lfi_hc, True, 4)],
'smallest_last': [
(sl_shc, False, (3, 4)),
(sl_hc, False, 5),
(sl_shc, True, 3),
(sl_hc, True, 4),
(sli_shc, True, (3, 4)),
(sli_hc, True, 5)],
'independent_set': [
(gis_shc, False, (2, 3)),
(gis_hc, False, 3)],
'connected_sequential': [
(cs_shc, False, (3, 4)),
(cs_shc, True, 3)],
'connected_sequential_dfs': [
(cs_shc, False, (3, 4))],
}
| bsd-3-clause |
shinigota/dagpi_splendor | SplendorCode/src/mvc/Display.py | 1 | 32173 | from tkinter import *
from src.element.Card import Card
from src.element.ResourceType import ResourceType
from src.game.GameState import GameState
from src.mvc.EventType import EventType
from src.mvc.GameBoard import GameBoard
from src.mvc.GameRules import GameRules
from src.player.AI import AI
import time
class Display:
window = None
text = "test"
game_rules = None
game_board = None
w = None
h = None
nb_players = 1
false_position = None
def __init__(self):
self.window = Tk()
self.create_image()
def create_window(self):
print('Display -- create_window')
self.window.title(GameRules.game_name)
self.w, self.h = 1900, 1000
self.window.geometry("%dx%d+0+0" % (self.w, self.h))
self.window.config(bg=None)
def make_entry(self, parent, caption, var):
print('Display -- make_entry')
Label(parent, text=caption).pack()
entry = Entry(parent, textvariable=var)
entry.pack()
return entry
def popup_start_click_action(self):
print('Display -- popup_start_click_action')
popup = Toplevel(height=250, width=280)
# popup.protocol("WM_DELETE_WINDOW", self.on_exit)
Label(popup, text="Sélectionnez vos parametres", height=1,
width=30).pack()
self.user_name = StringVar()
self.user_name.set("Player")
Label(popup, text="Name:").pack()
entry = Entry(popup, textvariable=self.user_name)
entry.pack()
self.nb_players=1
self.players_level = dict()
self.players_canvas = dict()
self.players_position = dict()
self.players_position[self.nb_players] = Variable()
self.players_position[self.nb_players].set(int(self.nb_players))
Label(popup, text="Position:").pack()
entry = Entry(popup,
textvariable=self.players_position[self.nb_players])
entry.pack()
canvas = Canvas(popup, height=20,
width=160, background="grey")
canvas.create_text(82, 10, text="Ajouter un adversaire", fill="black")
canvas.bind("<Button-1>", lambda event,
p=popup,
c=canvas:
self.add_player_click_action(p, c))
canvas.pack()
# self.canvas_validate = Canvas(popup, height=20,
# width=60, background="grey")
# self.canvas_validate.create_text(30, 10, text="Valider",
# fill="black")
# self.canvas_validate.bind("<Button-1>", lambda event,
# p=popup:
# self.validate_popup_action(p))
# self.canvas_validate.pack()
def add_player_click_action(self, popup, canvas):
print('Display -- add_player_click_action')
try:
self.false_position.pack_forget()
except:
pass
if self.nb_players >= 2:
self.canvas_validate.pack_forget()
text_nb_players = self.nb_players
Label(popup, text="%s %s" % ("Adversaire n°", text_nb_players)).pack()
self.nb_players = self.nb_players + 1
self.players_level[self.nb_players] = Variable()
self.players_level[self.nb_players].set(0)
self.players_position[self.nb_players] = Variable()
c = Checkbutton(popup, text="Niveau difficile",
variable=self.players_level[self.nb_players])
c.pack()
self.players_position[self.nb_players].set(int(self.nb_players))
Label(popup, text="Position:").pack()
entry = Entry(popup,
textvariable=self.players_position[self.nb_players])
entry.pack()
self.players_canvas[self.nb_players] = c
if self.nb_players == 4:
self.canvas_validate.pack()
canvas.pack_forget()
elif self.nb_players == 2:
self.canvas_validate = Canvas(popup, height=20,
width=60, background="grey")
self.canvas_validate.create_text(30, 10, text="Valider",
fill="black")
self.canvas_validate.bind("<Button-1>", lambda event,
p=popup:
self.validate_popup_action(p))
self.canvas_validate.pack()
else:
self.canvas_validate.pack()
def validate_popup_action(self, popup):
print('Display -- validate_popup_action')
try:
self.false_position.pack_forget()
except:
pass
accept = True
temp_positions = []
for item in self.players_position:
try:
temp_positions.append(int(self.players_position[item].get()))
except:
accept = False
if accept:
for item in range(1, self.nb_players + 1):
if item not in temp_positions:
accept = False
if accept:
popup.destroy()
final_players = []
for key in range(1, self.nb_players+1):
players_dict = dict()
players_dict["position"] = self.players_position[key].get()
if key == 1:
players_dict["name"] = self.user_name.get()
players_dict["difficulty"] = 0
else:
players_dict["name"] = "IA %d" % key
players_dict["difficulty"] = self.players_level[key].get()
final_players.append(players_dict)
self.game_rules.event(EventType.START, final_players)
else:
self.false_position = Label(popup, text="Positions incorrectes",
fg="red")
self.false_position.pack()
def display_tiles(self):
print('Display -- display_tiles')
i = 1
y = 100
for tile in self.game_board.displayed_tiles:
x = 170 + 120 * (i - 1)
self.display_tile(self.window, x, y, tile, None)
i += 1
def display_tile(self, canvas, x, y, tile, event):
print('Display -- display_tile')
canvas = Canvas(canvas, width=100, height=100,
background='#725202')
canvas.create_image(50, 50, image=self.img_tile)
canvas.create_image(13, 13, image=self.get_image_points(tile.points))
i = 1
for key in tile.gems_conditions:
number = tile.gems_conditions[key]
if number > 0:
textcolor = "white"
if ResourceType.get_color(key) == "white":
textcolor = "black"
if i == 1:
canvas.create_image(27, 40, image=self.get_image_rect_gem(
key))
txtBuy1 = canvas.create_text(25, 40, text=number,
fill=textcolor)
i = 2
elif i == 2:
canvas.create_image(27, 80, image=self.get_image_rect_gem(
key))
txtBuy2 = canvas.create_text(25, 80, text=number,
fill=textcolor)
i = 3
elif i == 3:
canvas.create_image(77, 80, image=self.get_image_rect_gem(
key))
txtBuy3 = canvas.create_text(75, 80, text=number,
fill=textcolor)
i = 0
canvas.place(x=x, y=y)
if event is not None:
canvas.bind("<Button-1>", lambda event, e=event,
t=tile: self.game_rules.event(e,
t))
def display_cards(self):
print('Display -- display_cards')
for lvl in range(1, int(self.game_rules.nb_lvl_card) + 1):
i = 1
for card in self.game_board.displayed_cards[lvl]:
x = 170 + 120 * (i - 1)
y = 490 - (130 * (lvl - 1))
self.display_card(self.window, x, y, card,
EventType.CLICK_DISPLAYED_CARD)
i += 1
def display_card(self, canvas, x, y, card, event):
print('Display -- display_card')
canvas = Canvas(canvas, width=100, height=120,
background=self.get_color(int(card.level)))
canvas.create_image(50, 75, image=self.get_image_card_gem(
card.income_gem))
canvas.create_image(15, 20, image=self.get_image_points(card.points))
i = 1
for key in card.purchase_gems:
number = card.purchase_gems[key]
if number > 0:
textcolor = "white"
if ResourceType.get_color(key) == "white":
textcolor = "black"
if i == 1:
canvas.create_image(25, 100,
image=self.get_image_circle_gem(key))
txtBuy1 = canvas.create_text(25, 100, text=number,
fill=textcolor)
i = 2
elif i == 2:
canvas.create_image(75, 100,
image=self.get_image_circle_gem(key))
txtBuy2 = canvas.create_text(75, 100, text=number,
fill=textcolor)
i = 3
elif i == 3:
canvas.create_image(25, 60,
image=self.get_image_circle_gem(key))
txtBuy3 = canvas.create_text(25, 60, text=number,
fill=textcolor)
i = 4
elif i == 4:
canvas.create_image(75, 60,
image=self.get_image_circle_gem(key))
txtBuy4 = canvas.create_text(75, 60, text=number,
fill=textcolor)
i = 0
canvas.place(x=x,
y=y)
if event is not None:
canvas.bind("<Button-1>",
lambda event, e=event,
c=card: self.game_rules.event(e, c))
def display_stacks(self):
print('Display -- display_stacks')
for i in range(1, int(self.game_rules.nb_lvl_card) + 1):
self.display_stack(i, self.game_board.is_deck_empty(i))
def display_stack(self, level, empty):
print('Display -- display_stack')
color = Display.get_color(level)
if empty:
color = "grey"
canvas = Canvas(self.window, width=100, height=120)
canvas.create_image(50, 60, image=self.get_image_deck(level, empty))
canvas.place(x=50, y=490 - (130 * (level - 1)))
canvas.bind("<Button-1>", lambda event, e=EventType.CLICK_DECK_CARD,
l=level: self.game_rules.event(e, l))
def display_bank(self, bank):
print('Display -- display_bank')
x = 70
y = 650
for token in ResourceType.get_sorted_resources():
if token == "Gold":
self.display_gold(self.window, 70, 115, bank[token])
else:
self.display_gem(self.window, x, y, bank[token], token)
x += 100
def display_gold(self, canvas, x, y, nb):
print('Display -- display_gold')
canvas = Canvas(canvas, width=80, height=80)
canvas.create_image(40, 40, image=self.get_image_token_gem("Gold"))
canvas.create_image(40, 40, image=self.get_image_points(nb))
canvas.place(x=x, y=y)
def display_gem(self, canvas, x, y, nb, gem):
print('Display -- display_gem')
canvas = Canvas(canvas, width=80, height=80)
canvas.create_image(40, 40, image=self.get_image_token_gem(gem))
canvas.create_image(40, 40, image=self.get_image_points(nb))
canvas.place(x=x, y=y)
canvas.bind("<Button-1>",
lambda event, e=EventType.CLICK_TAKE_TOKEN_GAMEBOARD,
g=gem: self.game_rules.event(e, g))
###################### Display hand of player #################################
def display_players(self):
print('Display -- display_players')
x = 1300
y = 40
for player in self.game_board.players:
if type(player) == AI:
self.display_player_ia(x, y, player)
y += 280
else:
self.display_player_human(player)
def display_player_human(self, player):
print('Display -- display_player_human')
color = "grey"
if self.game_board.get_current_player() == player:
color = "orange"
canvas = Canvas(self.window, width=500, height=270,
highlightbackground=color)
self.display_player_bank(canvas, 100, 10, player)
canvas.create_text(50, 45, text=player.nickname, fill="black")
canvas.create_text(50, 65, text=str(player.calculate_total_points()) +
" / "
"%d" %
self.game_rules.nb_points_end,
fill="black")
y = 130
i = 1
for card in player.reserved_cards:
x = 10 + 120 * (i - 1)
self.display_card(canvas, x, y, card, EventType.RESERVE_PURCHASE)
i += 1
self.display_player_tile(canvas, 370, 140, player)
canvas.place(x=750, y=320)
def display_player_ia(self, x, y, player):
print('Display -- display_player_ia')
color = "grey"
if self.game_board.get_current_player() == player:
color = "orange"
canvas = Canvas(self.window, width=500, height=270,
highlightbackground=color)
canvas.place(x=x, y=y)
self.display_player_bank(canvas, 100, 10, player)
canvas.create_text(50, 45, text=player.nickname, fill="black")
canvas.create_text(50, 65, text=str(player.calculate_total_points()) +
" / "
"%d" %
self.game_rules.nb_points_end,
fill="black")
y = 130
i = 1
for card in player.reserved_cards:
x = 10 + 120 * (i - 1)
self.display_card_ia(canvas, x, y, card.level)
i += 1
self.display_player_tile(canvas, 370, 140, player)
def display_card_ia(self, canvas, x, y, level):
print('Display -- display_card_ia')
color = Display.get_color(level)
canvas = Canvas(canvas, width=100, height=120)
canvas.create_image(50, 60, image=self.get_image_deck(level, False))
canvas.place(x=x, y=y)
def display_player_tile(self, canvas, x, y, player):
print('Display -- display_player_tile')
canvas = Canvas(canvas, width=100, height=100,
background='#725202')
canvas.create_image(50, 50, image=self.img_tile)
canvas.create_image(50, 50, image=self.get_image_points(
len(player.owned_tiles)))
canvas.place(x=x, y=y)
def display_player_bank(self, canvas, x, y, player):
print('Display -- display_player_bank')
canvas = Canvas(canvas, width=390, height=120)
canvas.place(x=x, y=y)
x = 0
y = 60
for token in ResourceType.get_sorted_resources():
if token == "Gold":
self.display_player_gold(canvas, 320, 30, player.bank[token])
else:
self.display_player_gem(canvas, x, y, player.bank[token],
token)
x += 60
x = 0
y = 0
for token in ResourceType.get_sorted_resources():
if token == "Gold":
pass
else:
self.display_player_income_card(canvas, x, y,
player.get_card_income()[
token],
token)
x += 60
def display_player_gold(self, canvas, x, y, nb):
print('Display -- display_player_gold')
canvas = Canvas(canvas, width=60, height=60)
canvas.create_image(30, 30,
image=self.get_image_token_bank_gem("Gold"))
canvas.create_image(30, 30, image=self.get_image_points(nb))
canvas.place(x=x, y=y)
canvas.bind("<Button-1>",
lambda event, e=EventType.CLICK_GIVE_BACK_PLAYER_TOKEN,
g="Gold": self.game_rules.event(e, g))
def display_player_gem(self, canvas, x, y, nb, gem):
print('Display -- display_player_gem')
color = "white"
if ResourceType.get_color(gem) == "white":
color = "black"
canvas = Canvas(canvas, width=60, height=60)
canvas.create_image(30, 30, image=self.get_image_token_bank_gem(gem))
canvas.create_image(30, 30, image=self.get_image_points(nb))
canvas.place(x=x, y=y)
canvas.bind("<Button-1>",
lambda event, e=EventType.CLICK_GIVE_BACK_PLAYER_TOKEN,
g=gem: self.game_rules.event(e, g))
def display_player_income_card(self, canvas, x, y, nb, gem):
print('Display -- display_player_income_card')
color = "white"
if ResourceType.get_color(gem) == "white":
color = "black"
canvas = Canvas(canvas, width=60, height=60)
canvas.create_image(35, 30, image=self.get_image_rect_bank_gem(gem))
canvas.create_text(30, 30, text=nb, fill=color)
canvas.place(x=x, y=y)
def display_text_help(self):
print('Display -- display_text_help')
canvas = Canvas(self.window, width=500, height=70)
canvas.create_text(100, 30, text=self.game_board.help_text)
canvas.place(x=0, y=0)
def popup_select_card_action(self, isreserved, ispurchase, card):
print('Display -- opup_select_card_action')
# GameState.toggle_modal(True)
self.popup = Toplevel(height=250, width=280)
self.popup.protocol("WM_DELETE_WINDOW", self.on_exit)
Label(self.popup, text="Selectionnez votre action :", height=1,
width=30).place(x=40, y=10)
self.display_card(self.popup, 90, 50, card, None)
if isreserved:
canvas = Canvas(self.popup, height=20,
width=60, background="grey")
canvas.create_text(30, 10, text="Reserver", fill="black")
canvas.bind("<Button-1>", lambda event,
e=EventType.POPUP_RESERVE,
c=card:
self.click_on_popup(e, c))
canvas.place(x=60, y=200)
if ispurchase:
canvas = Canvas(self.popup, height=20,
width=60, background="grey")
canvas.create_text(30, 10, text="Acheter", fill="black")
canvas.bind("<Button-1>", lambda event,
e=EventType.POPUP_PURCHASE,
c=card:
self.click_on_popup(e, c))
canvas.place(x=160, y=200)
def popup_select_tile_action(self, tiles):
print('Display -- popup_select_tile_action')
# GameState.toggle_modal(True)
self.popup = Toplevel(height=170, width=565)
self.popup.protocol("WM_DELETE_WINDOW", self.on_exit)
Label(self.popup, text="Selectionnez votre Noble:", height=1,
width=30).place(x=180, y=10)
x = 10
y = 50
for tile in tiles:
self.display_tile(self.popup, x, y, tile, EventType.CLICK_TILE)
x += 110
def popup_txt(self, txt):
print('Display -- popup_txt')
# GameState.toggle_modal(True)
self.popup = Toplevel(height=300, width=260)
self.popup.protocol("WM_DELETE_WINDOW", self.on_exit)
label = Label(self.popup,
text=txt, height=7,
width=30)
label.place(x=20, y=50)
def click_on_popup(self, event, objet):
print('Display -- click_on_popup')
self.popup.destroy()
# GameState.toggle_modal(False)
self.game_rules.event(event, objet)
def on_exit(self):
print('Display -- on_exit')
self.game_rules.event(EventType.CLOSE_POPUP, None)
self.popup.destroy()
def create_image(self):
print('Display -- create_image')
self.img_bg = PhotoImage(file='../res/bakground.gif')
self.img_button = PhotoImage(file='../res/Button.gif')
self.img0 = PhotoImage(file='../res/0.gif')
self.img0 = self.img0.subsample(3, 3)
self.img1 = PhotoImage(file='../res/1.gif')
self.img1 = self.img1.subsample(3, 3)
self.img2 = PhotoImage(file='../res/2.gif')
self.img2 = self.img2.subsample(3, 3)
self.img3 = PhotoImage(file='../res/3.gif')
self.img3 = self.img3.subsample(3, 3)
self.img4 = PhotoImage(file='../res/4.gif')
self.img4 = self.img4.subsample(3, 3)
self.img5 = PhotoImage(file='../res/5.gif')
self.img5 = self.img5.subsample(3, 3)
self.img6 = PhotoImage(file='../res/6.gif')
self.img6 = self.img6.subsample(3, 3)
self.img7 = PhotoImage(file='../res/7.gif')
self.img7 = self.img7.subsample(3, 3)
self.img_card_D = PhotoImage(file='../res/card_diamant.gif')
self.img_card_D = self.img_card_D.subsample(5, 5)
self.img_card_E = PhotoImage(file='../res/card_emeraude.gif')
self.img_card_E = self.img_card_E.subsample(5, 5)
self.img_card_O = PhotoImage(file='../res/card_onyx.gif')
self.img_card_O = self.img_card_O.subsample(5, 5)
self.img_card_R = PhotoImage(file='../res/card_rubis.gif')
self.img_card_R = self.img_card_R.subsample(5, 5)
self.img_card_S = PhotoImage(file='../res/card_saphir.gif')
self.img_card_S = self.img_card_S.subsample(5, 5)
self.img_circle_D = PhotoImage(file='../res/white_circle.gif')
self.img_circle_D = self.img_circle_D.subsample(2, 2)
self.img_circle_E = PhotoImage(file='../res/green_circle.gif')
self.img_circle_E = self.img_circle_E.subsample(2, 2)
self.img_circle_O = PhotoImage(file='../res/black_circle.gif')
self.img_circle_O = self.img_circle_O.subsample(2, 2)
self.img_circle_R = PhotoImage(file='../res/red_circle.gif')
self.img_circle_R = self.img_circle_R.subsample(2, 2)
self.img_circle_S = PhotoImage(file='../res/blue_circle.gif')
self.img_circle_S = self.img_circle_S.subsample(2, 2)
self.img_rect_D = PhotoImage(file='../res/white_rect.gif')
self.img_rect_D = self.img_rect_D.subsample(2, 2)
self.img_rect_E = PhotoImage(file='../res/green_rect.gif')
self.img_rect_E = self.img_rect_E.subsample(2, 2)
self.img_rect_O = PhotoImage(file='../res/black_rect.gif')
self.img_rect_O = self.img_rect_O.subsample(2, 2)
self.img_rect_R = PhotoImage(file='../res/red_rect.gif')
self.img_rect_R = self.img_rect_R.subsample(2, 2)
self.img_rect_S = PhotoImage(file='../res/blue_rect.gif')
self.img_rect_S = self.img_rect_S.subsample(2, 2)
self.img_rect_bank_D = PhotoImage(file='../res/white_rect.gif')
self.img_rect_bank_E = PhotoImage(file='../res/green_rect.gif')
self.img_rect_bank_O = PhotoImage(file='../res/black_rect.gif')
self.img_rect_bank_R = PhotoImage(file='../res/red_rect.gif')
self.img_rect_bank_S = PhotoImage(file='../res/blue_rect.gif')
self.img_token_D = PhotoImage(file='../res/token_diamant.gif')
self.img_token_D = self.img_token_D.subsample(3, 3)
self.img_token_E = PhotoImage(file='../res/token_emeraude.gif')
self.img_token_E = self.img_token_E.subsample(3, 3)
self.img_token_R = PhotoImage(file='../res/token_rubis.gif')
self.img_token_R = self.img_token_R.subsample(3, 3)
self.img_token_S = PhotoImage(file='../res/token_saphir.gif')
self.img_token_S = self.img_token_S.subsample(3, 3)
self.img_token_O = PhotoImage(file='../res/token_onyx.gif')
self.img_token_O = self.img_token_O.subsample(3, 3)
self.img_token_G = PhotoImage(file='../res/token_gold.gif')
self.img_token_G = self.img_token_G.subsample(3, 3)
self.img_token_bank_D = PhotoImage(file='../res/token_diamant.gif')
self.img_token_bank_D = self.img_token_bank_D.subsample(4, 4)
self.img_token_bank_E = PhotoImage(file='../res/token_emeraude.gif')
self.img_token_bank_E = self.img_token_bank_E.subsample(4, 4)
self.img_token_bank_R = PhotoImage(file='../res/token_rubis.gif')
self.img_token_bank_R = self.img_token_bank_R.subsample(4, 4)
self.img_token_bank_S = PhotoImage(file='../res/token_saphir.gif')
self.img_token_bank_S = self.img_token_bank_S.subsample(4, 4)
self.img_token_bank_O = PhotoImage(file='../res/token_onyx.gif')
self.img_token_bank_O = self.img_token_bank_O.subsample(4, 4)
self.img_token_bank_G = PhotoImage(file='../res/token_gold.gif')
self.img_token_bank_G = self.img_token_bank_G.subsample(4, 4)
self.img_deck_1 = PhotoImage(file='../res/deck_lvl1.gif')
self.img_deck_1 = self.img_deck_1.subsample(3, 3)
self.img_deck_empty_1 = PhotoImage(file='../res/deck_lvl1_empty.gif')
self.img_deck_empty_1 = self.img_deck_empty_1.subsample(7, 7)
self.img_deck_2 = PhotoImage(file='../res/deck_lvl2.gif')
self.img_deck_2 = self.img_deck_2.subsample(3, 3)
self.img_deck_empty_2 = PhotoImage(file='../res/deck_lvl2_empty.gif')
self.img_deck_empty_2 = self.img_deck_empty_2.subsample(3, 3)
self.img_deck_3 = PhotoImage(file='../res/deck_lvl3.gif')
self.img_deck_3 = self.img_deck_3.subsample(3, 3)
self.img_deck_empty_3 = PhotoImage(file='../res/deck_lvl3_empty.gif')
self.img_deck_empty_3 = self.img_deck_empty_3.subsample(3, 3)
self.img_tile = PhotoImage(file='../res/tuile.gif')
self.img_tile = self.img_tile.subsample(1, 1)
def get_image_points(self, points):
print('Display -- get_image_points')
if points == 0:
return self.img0
elif points == 1:
return self.img1
elif points == 2:
return self.img2
elif points == 3:
return self.img3
elif points == 4:
return self.img4
elif points == 5:
return self.img5
elif points == 6:
return self.img6
elif points == 7:
return self.img7
def get_image_card_gem(self, gem):
print('Display -- get_image_card_gem')
if gem == "Diamond":
return self.img_card_D
elif gem == "Emerald":
return self.img_card_E
elif gem == "Sapphire":
return self.img_card_S
elif gem == "Onyx":
return self.img_card_O
elif gem == "Ruby":
return self.img_card_R
def get_image_deck(self, lvl, empty):
print('Display -- get_image_deck')
if lvl == 1:
if empty:
return self.img_deck_empty_1
else:
return self.img_deck_1
elif lvl == 2:
if empty:
return self.img_deck_empty_2
else:
return self.img_deck_2
elif lvl == 3:
if empty:
return self.img_deck_empty_3
else:
return self.img_deck_3
def get_image_circle_gem(self, gem):
print('Display -- get_image_circle_gem')
if gem == "Diamond":
return self.img_circle_D
elif gem == "Emerald":
return self.img_circle_E
elif gem == "Sapphire":
return self.img_circle_S
elif gem == "Onyx":
return self.img_circle_O
elif gem == "Ruby":
return self.img_circle_R
def get_image_rect_gem(self, gem):
print('Display -- get_image_rect_gem')
if gem == "Diamond":
return self.img_rect_D
elif gem == "Emerald":
return self.img_rect_E
elif gem == "Sapphire":
return self.img_rect_S
elif gem == "Onyx":
return self.img_rect_O
elif gem == "Ruby":
return self.img_rect_R
def get_image_token_gem(self, gem):
print('Display -- get_image_token_gem')
if gem == "Diamond":
return self.img_token_D
elif gem == "Emerald":
return self.img_token_E
elif gem == "Sapphire":
return self.img_token_S
elif gem == "Onyx":
return self.img_token_O
elif gem == "Ruby":
return self.img_token_R
elif gem == "Gold":
return self.img_token_G
def get_image_rect_bank_gem(self, gem):
print('Display -- get_image_rect_bank_gem')
if gem == "Diamond":
return self.img_rect_bank_D
elif gem == "Emerald":
return self.img_rect_bank_E
elif gem == "Sapphire":
return self.img_rect_bank_S
elif gem == "Onyx":
return self.img_rect_bank_O
elif gem == "Ruby":
return self.img_rect_bank_R
def get_image_token_bank_gem(self, gem):
print('Display -- get_image_token_bank_gem')
if gem == "Diamond":
return self.img_token_bank_D
elif gem == "Emerald":
return self.img_token_bank_E
elif gem == "Sapphire":
return self.img_token_bank_S
elif gem == "Onyx":
return self.img_token_bank_O
elif gem == "Ruby":
return self.img_token_bank_R
elif gem == "Gold":
return self.img_token_bank_G
@staticmethod
def get_color(level):
print('Display -- get_color')
if level == 1:
color = '#0483f9'
if level == 2:
color = '#05e002'
if level == 3:
color = '#ffac07'
return color
def refresh(self):
print('Display -- refresh')
canvas = Canvas(self.window, height=self.h, width=self.w)
canvas.place(x=0, y=0)
self.display_bank(self.game_board.bank)
self.display_stacks()
self.display_cards()
self.display_tiles()
self.display_players()
self.display_text_help()
def launch(self):
print('Display -- launch')
canvas = Canvas(self.window, height=self.h, width=self.w)
canvas.create_image(1000, 500, image=self.img_bg)
button_quit = Canvas(self.window, height=100, width=300)
button_start = Canvas(self.window, height=100, width=300)
button_start.create_image(151, 52, image=self.img_button)
button_quit.create_image(151, 52, image=self.img_button)
button_quit.place(x=1400, y=500)
button_start.place(x=300, y=500)
canvas.place(x=0, y=0)
button_start.create_text(150, 50, text='Start', fill='gold')
button_quit.create_text(150, 50, text='Quit', fill='gold')
button_quit.bind("<Button-1>", lambda a, b=None: self.window.destroy())
button_start.bind("<Button-1>",
lambda a, b=None: self.popup_start_click_action())
| gpl-3.0 |
guillaume-philippon/aquilon | lib/aquilon/worker/commands/compile_hostname.py | 2 | 1769 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2015,2016 Contributor
#
# 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.
"""Contains the logic for `aq compile`."""
from aquilon.worker.broker import BrokerCommand
from aquilon.worker.dbwrappers.host import hostname_to_host
from aquilon.worker.templates import Plenary, TemplateDomain
class CommandCompileHostname(BrokerCommand):
required_parameters = ["hostname"]
requires_readonly = True
def render(self, session, logger, hostname, pancinclude, pancexclude,
pancdebug, cleandeps, **_):
dbhost = hostname_to_host(session, hostname)
if pancdebug:
pancinclude = r'.*'
pancexclude = r'components/spma/functions.*'
dom = TemplateDomain(dbhost.branch, dbhost.sandbox_author,
logger=logger)
plenary = Plenary.get_plenary(dbhost, logger=logger)
with plenary.get_key():
dom.compile(session, only=plenary.object_templates,
panc_debug_include=pancinclude,
panc_debug_exclude=pancexclude,
cleandeps=cleandeps)
return
| apache-2.0 |
thejinchao/moboair_mosquitto | test/lib/03-publish-c2b-qos2.py | 19 | 3173 | #!/usr/bin/env python
# Test whether a client sends a correct PUBLISH to a topic with QoS 2.
# The client should connect to port 1888 with keepalive=60, clean session set,
# and client id publish-qos2-test
# The test will send a CONNACK message to the client with rc=0. Upon receiving
# the CONNACK the client should verify that rc==0. If not, it should exit with
# return code=1.
# On a successful CONNACK, the client should send a PUBLISH message with topic
# "pub/qos2/test", payload "message" and QoS=2.
# The test will not respond to the first PUBLISH message, so the client must
# resend the PUBLISH message with dup=1. Note that to keep test durations low, a
# message retry timeout of less than 10 seconds is required for this test.
# On receiving the second PUBLISH message, the test will send the correct
# PUBREC response. On receiving the correct PUBREC response, the client should
# send a PUBREL message.
# The test will not respond to the first PUBREL message, so the client must
# resend the PUBREL message with dup=1. On receiving the second PUBREL message,
# the test will send the correct PUBCOMP response. On receiving the correct
# PUBCOMP response, the client should send a DISCONNECT message.
import inspect
import os
import subprocess
import socket
import sys
import time
# From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"..")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
import mosq_test
rc = 1
keepalive = 60
connect_packet = mosq_test.gen_connect("publish-qos2-test", keepalive=keepalive)
connack_packet = mosq_test.gen_connack(rc=0)
disconnect_packet = mosq_test.gen_disconnect()
mid = 1
publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message")
publish_dup_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message", dup=True)
pubrec_packet = mosq_test.gen_pubrec(mid)
pubrel_packet = mosq_test.gen_pubrel(mid)
pubcomp_packet = mosq_test.gen_pubcomp(mid)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout(10)
sock.bind(('', 1888))
sock.listen(5)
client_args = sys.argv[1:]
env = dict(os.environ)
env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp'
try:
pp = env['PYTHONPATH']
except KeyError:
pp = ''
env['PYTHONPATH'] = '../../lib/python:'+pp
client = subprocess.Popen(client_args, env=env)
try:
(conn, address) = sock.accept()
conn.settimeout(10)
if mosq_test.expect_packet(conn, "connect", connect_packet):
conn.send(connack_packet)
if mosq_test.expect_packet(conn, "publish", publish_packet):
conn.send(pubrec_packet)
if mosq_test.expect_packet(conn, "pubrel", pubrel_packet):
conn.send(pubcomp_packet)
if mosq_test.expect_packet(conn, "disconnect", disconnect_packet):
rc = 0
conn.close()
finally:
client.terminate()
client.wait()
sock.close()
exit(rc)
| bsd-3-clause |
raags/ansible-modules-core | cloud/openstack/os_networks_facts.py | 30 | 4248 | #!/usr/bin/python
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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/>.
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
DOCUMENTATION = '''
---
module: os_networks_facts
short_description: Retrieve facts about one or more OpenStack networks.
version_added: "2.0"
author: "Davide Agnello (@dagnello)"
description:
- Retrieve facts about one or more networks from OpenStack.
requirements:
- "python >= 2.6"
- "shade"
options:
network:
description:
- Name or ID of the Network
required: false
filters:
description:
- A dictionary of meta data to use for further filtering. Elements of
this dictionary may be additional dictionaries.
required: false
extends_documentation_fragment: openstack
'''
EXAMPLES = '''
# Gather facts about previously created networks
- os_networks_facts:
auth:
auth_url: https://your_api_url.com:9000/v2.0
username: user
password: password
project_name: someproject
- debug: var=openstack_networks
# Gather facts about a previously created network by name
- os_networks_facts:
auth:
auth_url: https://your_api_url.com:9000/v2.0
username: user
password: password
project_name: someproject
name: network1
- debug: var=openstack_networks
# Gather facts about a previously created network with filter (note: name and
filters parameters are Not mutually exclusive)
- os_networks_facts:
auth:
auth_url: https://your_api_url.com:9000/v2.0
username: user
password: password
project_name: someproject
filters:
tenant_id: 55e2ce24b2a245b09f181bf025724cbe
subnets:
- 057d4bdf-6d4d-4728-bb0f-5ac45a6f7400
- 443d4dc0-91d4-4998-b21c-357d10433483
- debug: var=openstack_networks
'''
RETURN = '''
openstack_networks:
description: has all the openstack facts about the networks
returned: always, but can be null
type: complex
contains:
id:
description: Unique UUID.
returned: success
type: string
name:
description: Name given to the network.
returned: success
type: string
status:
description: Network status.
returned: success
type: string
subnets:
description: Subnet(s) included in this network.
returned: success
type: list of strings
tenant_id:
description: Tenant id associated with this network.
returned: success
type: string
shared:
description: Network shared flag.
returned: success
type: boolean
'''
def main():
argument_spec = openstack_full_argument_spec(
name=dict(required=False, default=None),
filters=dict(required=False, type='dict', default=None)
)
module = AnsibleModule(argument_spec)
if not HAS_SHADE:
module.fail_json(msg='shade is required for this module')
try:
cloud = shade.openstack_cloud(**module.params)
networks = cloud.search_networks(module.params['name'],
module.params['filters'])
module.exit_json(changed=False, ansible_facts=dict(
openstack_networks=networks))
except shade.OpenStackCloudException as e:
module.fail_json(msg=str(e))
# this is magic, see lib/ansible/module_common.py
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
if __name__ == '__main__':
main()
| gpl-3.0 |
tellesnobrega/horizon | openstack_dashboard/dashboards/project/volumes/test.py | 29 | 3468 | # Copyright 2012 Nebula, 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.
from django.core.urlresolvers import reverse
from django import http
from mox import IsA # noqa
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
INDEX_URL = reverse('horizon:project:volumes:index')
VOLUME_SNAPSHOTS_TAB_URL = reverse('horizon:project:volumes:snapshots_tab')
VOLUME_BACKUPS_TAB_URL = reverse('horizon:project:volumes:backups_tab')
class VolumeAndSnapshotsTests(test.TestCase):
@test.create_stubs({api.cinder: ('tenant_absolute_limits',
'volume_list',
'volume_snapshot_list',
'volume_backup_supported',
'volume_backup_list',
),
api.nova: ('server_list',)})
def _test_index(self, backup_supported=True):
vol_backups = self.cinder_volume_backups.list()
vol_snaps = self.cinder_volume_snapshots.list()
volumes = self.cinder_volumes.list()
api.cinder.volume_backup_supported(IsA(http.HttpRequest)).\
MultipleTimes().AndReturn(backup_supported)
api.cinder.volume_list(IsA(http.HttpRequest), search_opts=None).\
AndReturn(volumes)
api.nova.server_list(IsA(http.HttpRequest), search_opts=None).\
AndReturn([self.servers.list(), False])
api.cinder.volume_snapshot_list(
IsA(http.HttpRequest), search_opts=None).AndReturn(vol_snaps)
api.cinder.volume_snapshot_list(IsA(http.HttpRequest)).\
AndReturn(vol_snaps)
api.cinder.volume_list(IsA(http.HttpRequest)).AndReturn(volumes)
if backup_supported:
api.cinder.volume_backup_list(IsA(http.HttpRequest)).\
AndReturn(vol_backups)
api.cinder.volume_list(IsA(http.HttpRequest)).AndReturn(volumes)
api.cinder.tenant_absolute_limits(IsA(http.HttpRequest)).\
MultipleTimes().AndReturn(self.cinder_limits['absolute'])
self.mox.ReplayAll()
res = self.client.get(INDEX_URL)
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'project/volumes/index.html')
# Explicitly load the other tabs. If this doesn't work the test
# will fail due to "Expected methods never called."
res = self.client.get(VOLUME_SNAPSHOTS_TAB_URL)
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'project/volumes/index.html')
if backup_supported:
res = self.client.get(VOLUME_BACKUPS_TAB_URL)
self.assertTemplateUsed(res, 'project/volumes/index.html')
def test_index_backup_supported(self):
self._test_index(backup_supported=True)
def test_index_backup_not_supported(self):
self._test_index(backup_supported=False)
| apache-2.0 |
pankeshang/django-allauth | allauth/socialaccount/providers/stackexchange/views.py | 77 | 1315 | import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from allauth.socialaccount.providers import registry
from .provider import StackExchangeProvider
class StackExchangeOAuth2Adapter(OAuth2Adapter):
provider_id = StackExchangeProvider.id
access_token_url = 'https://stackexchange.com/oauth/access_token'
authorize_url = 'https://stackexchange.com/oauth'
profile_url = 'https://api.stackexchange.com/2.1/me'
def complete_login(self, request, app, token, **kwargs):
provider = registry.by_id(app.provider)
site = provider.get_site()
resp = requests.get(self.profile_url,
params={'access_token': token.token,
'key': app.key,
'site': site})
extra_data = resp.json()['items'][0]
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(StackExchangeOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(StackExchangeOAuth2Adapter)
| mit |
nrc/servo | tests/wpt/web-platform-tests/tools/html5lib/html5lib/filters/lint.py | 979 | 4306 | from __future__ import absolute_import, division, unicode_literals
from gettext import gettext
_ = gettext
from . import _base
from ..constants import cdataElements, rcdataElements, voidElements
from ..constants import spaceCharacters
spaceCharacters = "".join(spaceCharacters)
class LintError(Exception):
pass
class Filter(_base.Filter):
def __iter__(self):
open_elements = []
contentModelFlag = "PCDATA"
for token in _base.Filter.__iter__(self):
type = token["type"]
if type in ("StartTag", "EmptyTag"):
name = token["name"]
if contentModelFlag != "PCDATA":
raise LintError(_("StartTag not in PCDATA content model flag: %(tag)s") % {"tag": name})
if not isinstance(name, str):
raise LintError(_("Tag name is not a string: %(tag)r") % {"tag": name})
if not name:
raise LintError(_("Empty tag name"))
if type == "StartTag" and name in voidElements:
raise LintError(_("Void element reported as StartTag token: %(tag)s") % {"tag": name})
elif type == "EmptyTag" and name not in voidElements:
raise LintError(_("Non-void element reported as EmptyTag token: %(tag)s") % {"tag": token["name"]})
if type == "StartTag":
open_elements.append(name)
for name, value in token["data"]:
if not isinstance(name, str):
raise LintError(_("Attribute name is not a string: %(name)r") % {"name": name})
if not name:
raise LintError(_("Empty attribute name"))
if not isinstance(value, str):
raise LintError(_("Attribute value is not a string: %(value)r") % {"value": value})
if name in cdataElements:
contentModelFlag = "CDATA"
elif name in rcdataElements:
contentModelFlag = "RCDATA"
elif name == "plaintext":
contentModelFlag = "PLAINTEXT"
elif type == "EndTag":
name = token["name"]
if not isinstance(name, str):
raise LintError(_("Tag name is not a string: %(tag)r") % {"tag": name})
if not name:
raise LintError(_("Empty tag name"))
if name in voidElements:
raise LintError(_("Void element reported as EndTag token: %(tag)s") % {"tag": name})
start_name = open_elements.pop()
if start_name != name:
raise LintError(_("EndTag (%(end)s) does not match StartTag (%(start)s)") % {"end": name, "start": start_name})
contentModelFlag = "PCDATA"
elif type == "Comment":
if contentModelFlag != "PCDATA":
raise LintError(_("Comment not in PCDATA content model flag"))
elif type in ("Characters", "SpaceCharacters"):
data = token["data"]
if not isinstance(data, str):
raise LintError(_("Attribute name is not a string: %(name)r") % {"name": data})
if not data:
raise LintError(_("%(type)s token with empty data") % {"type": type})
if type == "SpaceCharacters":
data = data.strip(spaceCharacters)
if data:
raise LintError(_("Non-space character(s) found in SpaceCharacters token: %(token)r") % {"token": data})
elif type == "Doctype":
name = token["name"]
if contentModelFlag != "PCDATA":
raise LintError(_("Doctype not in PCDATA content model flag: %(name)s") % {"name": name})
if not isinstance(name, str):
raise LintError(_("Tag name is not a string: %(tag)r") % {"tag": name})
# XXX: what to do with token["data"] ?
elif type in ("ParseError", "SerializeError"):
pass
else:
raise LintError(_("Unknown token type: %(type)s") % {"type": type})
yield token
| mpl-2.0 |
bennyhat/me-benbrewer-academic-thesis-ns-3 | src/wifi/bindings/modulegen__gcc_LP64.py | 10 | 765133 | 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.wifi', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## propagation-environment.h (module 'propagation'): ns3::EnvironmentType [enumeration]
module.add_enum('EnvironmentType', ['UrbanEnvironment', 'SubUrbanEnvironment', 'OpenAreasEnvironment'], import_from_module='ns.propagation')
## qos-utils.h (module 'wifi'): ns3::AcIndex [enumeration]
module.add_enum('AcIndex', ['AC_BE', 'AC_BK', 'AC_VI', 'AC_VO', 'AC_BE_NQOS', 'AC_UNDEF'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacType [enumeration]
module.add_enum('WifiMacType', ['WIFI_MAC_CTL_RTS', 'WIFI_MAC_CTL_CTS', 'WIFI_MAC_CTL_ACK', 'WIFI_MAC_CTL_BACKREQ', 'WIFI_MAC_CTL_BACKRESP', 'WIFI_MAC_MGT_BEACON', 'WIFI_MAC_MGT_ASSOCIATION_REQUEST', 'WIFI_MAC_MGT_ASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_DISASSOCIATION', 'WIFI_MAC_MGT_REASSOCIATION_REQUEST', 'WIFI_MAC_MGT_REASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_PROBE_REQUEST', 'WIFI_MAC_MGT_PROBE_RESPONSE', 'WIFI_MAC_MGT_AUTHENTICATION', 'WIFI_MAC_MGT_DEAUTHENTICATION', 'WIFI_MAC_MGT_ACTION', 'WIFI_MAC_MGT_ACTION_NO_ACK', 'WIFI_MAC_MGT_MULTIHOP_ACTION', 'WIFI_MAC_DATA', 'WIFI_MAC_DATA_CFACK', 'WIFI_MAC_DATA_CFPOLL', 'WIFI_MAC_DATA_CFACK_CFPOLL', 'WIFI_MAC_DATA_NULL', 'WIFI_MAC_DATA_NULL_CFACK', 'WIFI_MAC_DATA_NULL_CFPOLL', 'WIFI_MAC_DATA_NULL_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA', 'WIFI_MAC_QOSDATA_CFACK', 'WIFI_MAC_QOSDATA_CFPOLL', 'WIFI_MAC_QOSDATA_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA_NULL', 'WIFI_MAC_QOSDATA_NULL_CFPOLL', 'WIFI_MAC_QOSDATA_NULL_CFACK_CFPOLL'])
## propagation-environment.h (module 'propagation'): ns3::CitySize [enumeration]
module.add_enum('CitySize', ['SmallCity', 'MediumCity', 'LargeCity'], import_from_module='ns.propagation')
## wifi-preamble.h (module 'wifi'): ns3::WifiPreamble [enumeration]
module.add_enum('WifiPreamble', ['WIFI_PREAMBLE_LONG', 'WIFI_PREAMBLE_SHORT'])
## wifi-mode.h (module 'wifi'): ns3::WifiModulationClass [enumeration]
module.add_enum('WifiModulationClass', ['WIFI_MOD_CLASS_UNKNOWN', 'WIFI_MOD_CLASS_IR', 'WIFI_MOD_CLASS_FHSS', 'WIFI_MOD_CLASS_DSSS', 'WIFI_MOD_CLASS_ERP_PBCC', 'WIFI_MOD_CLASS_DSSS_OFDM', 'WIFI_MOD_CLASS_ERP_OFDM', 'WIFI_MOD_CLASS_OFDM', 'WIFI_MOD_CLASS_HT'])
## wifi-phy-standard.h (module 'wifi'): ns3::WifiPhyStandard [enumeration]
module.add_enum('WifiPhyStandard', ['WIFI_PHY_STANDARD_80211a', 'WIFI_PHY_STANDARD_80211b', 'WIFI_PHY_STANDARD_80211g', 'WIFI_PHY_STANDARD_80211_10MHZ', 'WIFI_PHY_STANDARD_80211_5MHZ', 'WIFI_PHY_STANDARD_holland', 'WIFI_PHY_STANDARD_80211p_CCH', 'WIFI_PHY_STANDARD_80211p_SCH'])
## qos-tag.h (module 'wifi'): ns3::UserPriority [enumeration]
module.add_enum('UserPriority', ['UP_BK', 'UP_BE', 'UP_EE', 'UP_CL', 'UP_VI', 'UP_VO', 'UP_NC'])
## wifi-mode.h (module 'wifi'): ns3::WifiCodeRate [enumeration]
module.add_enum('WifiCodeRate', ['WIFI_CODE_RATE_UNDEFINED', 'WIFI_CODE_RATE_3_4', 'WIFI_CODE_RATE_2_3', 'WIFI_CODE_RATE_1_2'])
## edca-txop-n.h (module 'wifi'): ns3::TypeOfStation [enumeration]
module.add_enum('TypeOfStation', ['STA', 'AP', 'ADHOC_STA', 'MESH'])
## ctrl-headers.h (module 'wifi'): ns3::BlockAckType [enumeration]
module.add_enum('BlockAckType', ['BASIC_BLOCK_ACK', 'COMPRESSED_BLOCK_ACK', 'MULTI_TID_BLOCK_ACK'])
## 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')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class]
module.add_class('AsciiTraceHelper', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class]
module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True, import_from_module='ns.network')
## athstats-helper.h (module 'wifi'): ns3::AthstatsHelper [class]
module.add_class('AthstatsHelper')
## 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'])
## block-ack-manager.h (module 'wifi'): ns3::Bar [struct]
module.add_class('Bar')
## block-ack-agreement.h (module 'wifi'): ns3::BlockAckAgreement [class]
module.add_class('BlockAckAgreement')
## block-ack-cache.h (module 'wifi'): ns3::BlockAckCache [class]
module.add_class('BlockAckCache')
## block-ack-manager.h (module 'wifi'): ns3::BlockAckManager [class]
module.add_class('BlockAckManager')
## 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')
## capability-information.h (module 'wifi'): ns3::CapabilityInformation [class]
module.add_class('CapabilityInformation')
## dcf-manager.h (module 'wifi'): ns3::DcfManager [class]
module.add_class('DcfManager')
## dcf-manager.h (module 'wifi'): ns3::DcfState [class]
module.add_class('DcfState', allow_subclassing=True)
## dsss-error-rate-model.h (module 'wifi'): ns3::DsssErrorRateModel [class]
module.add_class('DsssErrorRateModel')
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId', import_from_module='ns.core')
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper [class]
module.add_class('InterferenceHelper')
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer [struct]
module.add_class('SnrPer', outer_class=root_module['ns3::InterferenceHelper'])
## 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'])
## mac-low.h (module 'wifi'): ns3::MacLowBlockAckEventListener [class]
module.add_class('MacLowBlockAckEventListener', allow_subclassing=True)
## mac-low.h (module 'wifi'): ns3::MacLowDcfListener [class]
module.add_class('MacLowDcfListener', allow_subclassing=True)
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionListener [class]
module.add_class('MacLowTransmissionListener', allow_subclassing=True)
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionParameters [class]
module.add_class('MacLowTransmissionParameters')
## mac-rx-middle.h (module 'wifi'): ns3::MacRxMiddle [class]
module.add_class('MacRxMiddle')
## 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')
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement [class]
module.add_class('OriginatorBlockAckAgreement', parent=root_module['ns3::BlockAckAgreement'])
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement::State [enumeration]
module.add_enum('State', ['PENDING', 'ESTABLISHED', 'INACTIVE', 'UNSUCCESSFUL'], outer_class=root_module['ns3::OriginatorBlockAckAgreement'])
## 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'])
## pcap-file.h (module 'network'): ns3::PcapFile [class]
module.add_class('PcapFile', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelper [class]
module.add_class('PcapHelper', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelper [enumeration]
module.add_enum('', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO'], outer_class=root_module['ns3::PcapHelper'], import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class]
module.add_class('PcapHelperForDevice', allow_subclassing=True, import_from_module='ns.network')
## propagation-cache.h (module 'propagation'): ns3::PropagationCache<ns3::JakesProcess> [class]
module.add_class('PropagationCache', import_from_module='ns.propagation', template_parameters=['ns3::JakesProcess'])
## random-variable.h (module 'core'): ns3::RandomVariable [class]
module.add_class('RandomVariable', import_from_module='ns.core')
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo [struct]
module.add_class('RateInfo')
## random-variable.h (module 'core'): ns3::SeedManager [class]
module.add_class('SeedManager', import_from_module='ns.core')
## random-variable.h (module 'core'): ns3::SequentialVariable [class]
module.add_class('SequentialVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## 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')
## status-code.h (module 'wifi'): ns3::StatusCode [class]
module.add_class('StatusCode')
## 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')
## random-variable.h (module 'core'): ns3::TriangularVariable [class]
module.add_class('TriangularVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## type-id.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId', import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration]
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct]
module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## random-variable.h (module 'core'): ns3::UniformVariable [class]
module.add_class('UniformVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## 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')
## random-variable.h (module 'core'): ns3::WeibullVariable [class]
module.add_class('WeibullVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## wifi-helper.h (module 'wifi'): ns3::WifiHelper [class]
module.add_class('WifiHelper')
## wifi-helper.h (module 'wifi'): ns3::WifiMacHelper [class]
module.add_class('WifiMacHelper', allow_subclassing=True)
## wifi-mode.h (module 'wifi'): ns3::WifiMode [class]
module.add_class('WifiMode')
## wifi-mode.h (module 'wifi'): ns3::WifiModeFactory [class]
module.add_class('WifiModeFactory')
## wifi-helper.h (module 'wifi'): ns3::WifiPhyHelper [class]
module.add_class('WifiPhyHelper', allow_subclassing=True)
## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener [class]
module.add_class('WifiPhyListener', allow_subclassing=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation [struct]
module.add_class('WifiRemoteStation')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo [class]
module.add_class('WifiRemoteStationInfo')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState [struct]
module.add_class('WifiRemoteStationState')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState [enumeration]
module.add_enum('', ['BRAND_NEW', 'DISASSOC', 'WAIT_ASSOC_TX_OK', 'GOT_ASSOC_TX_OK'], outer_class=root_module['ns3::WifiRemoteStationState'])
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiChannelHelper [class]
module.add_class('YansWifiChannelHelper')
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiPhyHelper [class]
module.add_class('YansWifiPhyHelper', parent=[root_module['ns3::WifiPhyHelper'], root_module['ns3::PcapHelperForDevice'], root_module['ns3::AsciiTraceHelperForDevice']])
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiPhyHelper::SupportedPcapDataLinkTypes [enumeration]
module.add_enum('SupportedPcapDataLinkTypes', ['DLT_IEEE802_11', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO'], outer_class=root_module['ns3::YansWifiPhyHelper'])
## random-variable.h (module 'core'): ns3::ZetaVariable [class]
module.add_class('ZetaVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## random-variable.h (module 'core'): ns3::ZipfVariable [class]
module.add_class('ZipfVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## chunk.h (module 'network'): ns3::Chunk [class]
module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## random-variable.h (module 'core'): ns3::ConstantVariable [class]
module.add_class('ConstantVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## random-variable.h (module 'core'): ns3::DeterministicVariable [class]
module.add_class('DeterministicVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## random-variable.h (module 'core'): ns3::EmpiricalVariable [class]
module.add_class('EmpiricalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## random-variable.h (module 'core'): ns3::ErlangVariable [class]
module.add_class('ErlangVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## random-variable.h (module 'core'): ns3::ExponentialVariable [class]
module.add_class('ExponentialVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## random-variable.h (module 'core'): ns3::GammaVariable [class]
module.add_class('GammaVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## header.h (module 'network'): ns3::Header [class]
module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## random-variable.h (module 'core'): ns3::IntEmpiricalVariable [class]
module.add_class('IntEmpiricalVariable', import_from_module='ns.core', parent=root_module['ns3::EmpiricalVariable'])
## random-variable.h (module 'core'): ns3::LogNormalVariable [class]
module.add_class('LogNormalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaRequestHeader [class]
module.add_class('MgtAddBaRequestHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaResponseHeader [class]
module.add_class('MgtAddBaResponseHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtAssocRequestHeader [class]
module.add_class('MgtAssocRequestHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtAssocResponseHeader [class]
module.add_class('MgtAssocResponseHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtDelBaHeader [class]
module.add_class('MgtDelBaHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtProbeRequestHeader [class]
module.add_class('MgtProbeRequestHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtProbeResponseHeader [class]
module.add_class('MgtProbeResponseHeader', parent=root_module['ns3::Header'])
## random-variable.h (module 'core'): ns3::NormalVariable [class]
module.add_class('NormalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## nqos-wifi-mac-helper.h (module 'wifi'): ns3::NqosWifiMacHelper [class]
module.add_class('NqosWifiMacHelper', parent=root_module['ns3::WifiMacHelper'])
## 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.h (module 'core'): ns3::ParetoVariable [class]
module.add_class('ParetoVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class]
module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=root_module['ns3::Object'])
## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel [class]
module.add_class('PropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::Object'])
## propagation-loss-model.h (module 'propagation'): ns3::PropagationLossModel [class]
module.add_class('PropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::Object'])
## qos-tag.h (module 'wifi'): ns3::QosTag [class]
module.add_class('QosTag', parent=root_module['ns3::Tag'])
## qos-wifi-mac-helper.h (module 'wifi'): ns3::QosWifiMacHelper [class]
module.add_class('QosWifiMacHelper', parent=root_module['ns3::WifiMacHelper'])
## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel [class]
module.add_class('RandomPropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationDelayModel'])
## propagation-loss-model.h (module 'propagation'): ns3::RandomPropagationLossModel [class]
module.add_class('RandomPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## propagation-loss-model.h (module 'propagation'): ns3::RangePropagationLossModel [class]
module.add_class('RangePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## 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::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::InterferenceHelper::Event', 'ns3::empty', 'ns3::DefaultDeleter<ns3::InterferenceHelper::Event>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::WifiInformationElement', 'ns3::empty', 'ns3::DefaultDeleter<ns3::WifiInformationElement>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## propagation-loss-model.h (module 'propagation'): ns3::ThreeLogDistancePropagationLossModel [class]
module.add_class('ThreeLogDistancePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time', import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time::Unit [enumeration]
module.add_enum('Unit', ['S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time [class]
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class]
module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## trailer.h (module 'network'): ns3::Trailer [class]
module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## propagation-loss-model.h (module 'propagation'): ns3::TwoRayGroundPropagationLossModel [class]
module.add_class('TwoRayGroundPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader [class]
module.add_class('WifiActionHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::CategoryValue [enumeration]
module.add_enum('CategoryValue', ['BLOCK_ACK', 'MESH_PEERING_MGT', 'MESH_LINK_METRIC', 'MESH_PATH_SELECTION', 'MESH_INTERWORKING', 'MESH_RESOURCE_COORDINATION', 'MESH_PROXY_FORWARDING'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::PeerLinkMgtActionValue [enumeration]
module.add_enum('PeerLinkMgtActionValue', ['PEER_LINK_OPEN', 'PEER_LINK_CONFIRM', 'PEER_LINK_CLOSE'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::LinkMetricActionValue [enumeration]
module.add_enum('LinkMetricActionValue', ['LINK_METRIC_REQUEST', 'LINK_METRIC_REPORT'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::PathSelectionActionValue [enumeration]
module.add_enum('PathSelectionActionValue', ['PATH_SELECTION'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::InterworkActionValue [enumeration]
module.add_enum('InterworkActionValue', ['PORTAL_ANNOUNCEMENT'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ResourceCoordinationActionValue [enumeration]
module.add_enum('ResourceCoordinationActionValue', ['CONGESTION_CONTROL_NOTIFICATION', 'MDA_SETUP_REQUEST', 'MDA_SETUP_REPLY', 'MDAOP_ADVERTISMENT_REQUEST', 'MDAOP_ADVERTISMENTS', 'MDAOP_SET_TEARDOWN', 'BEACON_TIMING_REQUEST', 'BEACON_TIMING_RESPONSE', 'TBTT_ADJUSTMENT_REQUEST', 'MESH_CHANNEL_SWITCH_ANNOUNCEMENT'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::BlockAckActionValue [enumeration]
module.add_enum('BlockAckActionValue', ['BLOCK_ACK_ADDBA_REQUEST', 'BLOCK_ACK_ADDBA_RESPONSE', 'BLOCK_ACK_DELBA'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue [union]
module.add_class('ActionValue', outer_class=root_module['ns3::WifiActionHeader'])
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElement [class]
module.add_class('WifiInformationElement', parent=root_module['ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >'])
## wifi-information-element-vector.h (module 'wifi'): ns3::WifiInformationElementVector [class]
module.add_class('WifiInformationElementVector', parent=root_module['ns3::Header'])
## wifi-mac.h (module 'wifi'): ns3::WifiMac [class]
module.add_class('WifiMac', parent=root_module['ns3::Object'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader [class]
module.add_class('WifiMacHeader', parent=root_module['ns3::Header'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::QosAckPolicy [enumeration]
module.add_enum('QosAckPolicy', ['NORMAL_ACK', 'NO_ACK', 'NO_EXPLICIT_ACK', 'BLOCK_ACK'], outer_class=root_module['ns3::WifiMacHeader'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::AddressType [enumeration]
module.add_enum('AddressType', ['ADDR1', 'ADDR2', 'ADDR3', 'ADDR4'], outer_class=root_module['ns3::WifiMacHeader'])
## wifi-mac-queue.h (module 'wifi'): ns3::WifiMacQueue [class]
module.add_class('WifiMacQueue', parent=root_module['ns3::Object'])
## wifi-phy.h (module 'wifi'): ns3::WifiPhy [class]
module.add_class('WifiPhy', parent=root_module['ns3::Object'])
## wifi-phy.h (module 'wifi'): ns3::WifiPhy::State [enumeration]
module.add_enum('State', ['IDLE', 'CCA_BUSY', 'TX', 'RX', 'SWITCHING'], outer_class=root_module['ns3::WifiPhy'])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationManager [class]
module.add_class('WifiRemoteStationManager', parent=root_module['ns3::Object'])
## yans-wifi-phy.h (module 'wifi'): ns3::YansWifiPhy [class]
module.add_class('YansWifiPhy', parent=root_module['ns3::WifiPhy'])
## aarf-wifi-manager.h (module 'wifi'): ns3::AarfWifiManager [class]
module.add_class('AarfWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## aarfcd-wifi-manager.h (module 'wifi'): ns3::AarfcdWifiManager [class]
module.add_class('AarfcdWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## amrr-wifi-manager.h (module 'wifi'): ns3::AmrrWifiManager [class]
module.add_class('AmrrWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## amsdu-subframe-header.h (module 'wifi'): ns3::AmsduSubframeHeader [class]
module.add_class('AmsduSubframeHeader', parent=root_module['ns3::Header'])
## arf-wifi-manager.h (module 'wifi'): ns3::ArfWifiManager [class]
module.add_class('ArfWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## athstats-helper.h (module 'wifi'): ns3::AthstatsWifiTraceSink [class]
module.add_class('AthstatsWifiTraceSink', parent=root_module['ns3::Object'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## cara-wifi-manager.h (module 'wifi'): ns3::CaraWifiManager [class]
module.add_class('CaraWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## channel.h (module 'network'): ns3::Channel [class]
module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## constant-rate-wifi-manager.h (module 'wifi'): ns3::ConstantRateWifiManager [class]
module.add_class('ConstantRateWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel [class]
module.add_class('ConstantSpeedPropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationDelayModel'])
## cost231-propagation-loss-model.h (module 'propagation'): ns3::Cost231PropagationLossModel [class]
module.add_class('Cost231PropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## cost231-propagation-loss-model.h (module 'propagation'): ns3::Cost231PropagationLossModel::Environment [enumeration]
module.add_enum('Environment', ['SubUrban', 'MediumCity', 'Metropolitan'], outer_class=root_module['ns3::Cost231PropagationLossModel'], import_from_module='ns.propagation')
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckRequestHeader [class]
module.add_class('CtrlBAckRequestHeader', parent=root_module['ns3::Header'])
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckResponseHeader [class]
module.add_class('CtrlBAckResponseHeader', parent=root_module['ns3::Header'])
## dcf.h (module 'wifi'): ns3::Dcf [class]
module.add_class('Dcf', 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'])
## edca-txop-n.h (module 'wifi'): ns3::EdcaTxopN [class]
module.add_class('EdcaTxopN', parent=root_module['ns3::Dcf'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## error-rate-model.h (module 'wifi'): ns3::ErrorRateModel [class]
module.add_class('ErrorRateModel', parent=root_module['ns3::Object'])
## 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> >'])
## supported-rates.h (module 'wifi'): ns3::ExtendedSupportedRatesIE [class]
module.add_class('ExtendedSupportedRatesIE', parent=root_module['ns3::WifiInformationElement'])
## propagation-loss-model.h (module 'propagation'): ns3::FixedRssLossModel [class]
module.add_class('FixedRssLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## propagation-loss-model.h (module 'propagation'): ns3::FriisPropagationLossModel [class]
module.add_class('FriisPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## ideal-wifi-manager.h (module 'wifi'): ns3::IdealWifiManager [class]
module.add_class('IdealWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## 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'])
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): ns3::ItuR1411LosPropagationLossModel [class]
module.add_class('ItuR1411LosPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): ns3::ItuR1411NlosOverRooftopPropagationLossModel [class]
module.add_class('ItuR1411NlosOverRooftopPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## jakes-process.h (module 'propagation'): ns3::JakesProcess [class]
module.add_class('JakesProcess', import_from_module='ns.propagation', parent=root_module['ns3::Object'])
## jakes-propagation-loss-model.h (module 'propagation'): ns3::JakesPropagationLossModel [class]
module.add_class('JakesPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): ns3::Kun2600MhzPropagationLossModel [class]
module.add_class('Kun2600MhzPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## propagation-loss-model.h (module 'propagation'): ns3::LogDistancePropagationLossModel [class]
module.add_class('LogDistancePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## 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'])
## mac-low.h (module 'wifi'): ns3::MacLow [class]
module.add_class('MacLow', parent=root_module['ns3::Object'])
## propagation-loss-model.h (module 'propagation'): ns3::MatrixPropagationLossModel [class]
module.add_class('MatrixPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## mgt-headers.h (module 'wifi'): ns3::MgtBeaconHeader [class]
module.add_class('MgtBeaconHeader', parent=root_module['ns3::MgtProbeResponseHeader'])
## minstrel-wifi-manager.h (module 'wifi'): ns3::MinstrelWifiManager [class]
module.add_class('MinstrelWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## mobility-model.h (module 'mobility'): ns3::MobilityModel [class]
module.add_class('MobilityModel', import_from_module='ns.mobility', parent=root_module['ns3::Object'])
## msdu-aggregator.h (module 'wifi'): ns3::MsduAggregator [class]
module.add_class('MsduAggregator', parent=root_module['ns3::Object'])
## propagation-loss-model.h (module 'propagation'): ns3::NakagamiPropagationLossModel [class]
module.add_class('NakagamiPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## 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')
## nist-error-rate-model.h (module 'wifi'): ns3::NistErrorRateModel [class]
module.add_class('NistErrorRateModel', parent=root_module['ns3::ErrorRateModel'])
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## okumura-hata-propagation-loss-model.h (module 'propagation'): ns3::OkumuraHataPropagationLossModel [class]
module.add_class('OkumuraHataPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## onoe-wifi-manager.h (module 'wifi'): ns3::OnoeWifiManager [class]
module.add_class('OnoeWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class]
module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## random-variable.h (module 'core'): ns3::RandomVariableChecker [class]
module.add_class('RandomVariableChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## random-variable.h (module 'core'): ns3::RandomVariableValue [class]
module.add_class('RandomVariableValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## regular-wifi-mac.h (module 'wifi'): ns3::RegularWifiMac [class]
module.add_class('RegularWifiMac', parent=root_module['ns3::WifiMac'])
## rraa-wifi-manager.h (module 'wifi'): ns3::RraaWifiManager [class]
module.add_class('RraaWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## ssid.h (module 'wifi'): ns3::Ssid [class]
module.add_class('Ssid', parent=root_module['ns3::WifiInformationElement'])
## ssid.h (module 'wifi'): ns3::SsidChecker [class]
module.add_class('SsidChecker', parent=root_module['ns3::AttributeChecker'])
## ssid.h (module 'wifi'): ns3::SsidValue [class]
module.add_class('SsidValue', parent=root_module['ns3::AttributeValue'])
## sta-wifi-mac.h (module 'wifi'): ns3::StaWifiMac [class]
module.add_class('StaWifiMac', parent=root_module['ns3::RegularWifiMac'])
## supported-rates.h (module 'wifi'): ns3::SupportedRates [class]
module.add_class('SupportedRates', parent=root_module['ns3::WifiInformationElement'])
## nstime.h (module 'core'): ns3::TimeChecker [class]
module.add_class('TimeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## nstime.h (module 'core'): ns3::TimeValue [class]
module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## type-id.h (module 'core'): ns3::TypeIdChecker [class]
module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## type-id.h (module 'core'): ns3::TypeIdValue [class]
module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## 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'])
## wifi-channel.h (module 'wifi'): ns3::WifiChannel [class]
module.add_class('WifiChannel', parent=root_module['ns3::Channel'])
## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker [class]
module.add_class('WifiModeChecker', parent=root_module['ns3::AttributeChecker'])
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue [class]
module.add_class('WifiModeValue', parent=root_module['ns3::AttributeValue'])
## wifi-net-device.h (module 'wifi'): ns3::WifiNetDevice [class]
module.add_class('WifiNetDevice', parent=root_module['ns3::NetDevice'])
## yans-error-rate-model.h (module 'wifi'): ns3::YansErrorRateModel [class]
module.add_class('YansErrorRateModel', parent=root_module['ns3::ErrorRateModel'])
## yans-wifi-channel.h (module 'wifi'): ns3::YansWifiChannel [class]
module.add_class('YansWifiChannel', parent=root_module['ns3::WifiChannel'])
## 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'])
## adhoc-wifi-mac.h (module 'wifi'): ns3::AdhocWifiMac [class]
module.add_class('AdhocWifiMac', parent=root_module['ns3::RegularWifiMac'])
## ap-wifi-mac.h (module 'wifi'): ns3::ApWifiMac [class]
module.add_class('ApWifiMac', parent=root_module['ns3::RegularWifiMac'])
## dca-txop.h (module 'wifi'): ns3::DcaTxop [class]
module.add_class('DcaTxop', parent=root_module['ns3::Dcf'])
module.add_container('ns3::WifiModeList', 'ns3::WifiMode', container_type='vector')
module.add_container('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::AmsduSubframeHeader > >', 'std::pair< ns3::Ptr< ns3::Packet >, ns3::AmsduSubframeHeader >', container_type='list')
typehandlers.add_type_alias('uint8_t', 'ns3::WifiInformationElementId')
typehandlers.add_type_alias('uint8_t*', 'ns3::WifiInformationElementId*')
typehandlers.add_type_alias('uint8_t&', 'ns3::WifiInformationElementId&')
typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >', 'ns3::WifiModeListIterator')
typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >*', 'ns3::WifiModeListIterator*')
typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >&', 'ns3::WifiModeListIterator&')
typehandlers.add_type_alias('ns3::Vector3D', 'ns3::Vector')
typehandlers.add_type_alias('ns3::Vector3D*', 'ns3::Vector*')
typehandlers.add_type_alias('ns3::Vector3D&', 'ns3::Vector&')
module.add_typedef(root_module['ns3::Vector3D'], 'Vector')
typehandlers.add_type_alias('std::vector< ns3::RateInfo, std::allocator< ns3::RateInfo > >', 'ns3::MinstrelRate')
typehandlers.add_type_alias('std::vector< ns3::RateInfo, std::allocator< ns3::RateInfo > >*', 'ns3::MinstrelRate*')
typehandlers.add_type_alias('std::vector< ns3::RateInfo, std::allocator< ns3::RateInfo > >&', 'ns3::MinstrelRate&')
typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >', 'ns3::WifiModeList')
typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >*', 'ns3::WifiModeList*')
typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >&', 'ns3::WifiModeList&')
typehandlers.add_type_alias('ns3::Vector3DValue', 'ns3::VectorValue')
typehandlers.add_type_alias('ns3::Vector3DValue*', 'ns3::VectorValue*')
typehandlers.add_type_alias('ns3::Vector3DValue&', 'ns3::VectorValue&')
module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue')
typehandlers.add_type_alias('std::vector< std::vector< unsigned int, std::allocator< unsigned int > >, std::allocator< std::vector< unsigned int, std::allocator< unsigned int > > > >', 'ns3::SampleRate')
typehandlers.add_type_alias('std::vector< std::vector< unsigned int, std::allocator< unsigned int > >, std::allocator< std::vector< unsigned int, std::allocator< unsigned int > > > >*', 'ns3::SampleRate*')
typehandlers.add_type_alias('std::vector< std::vector< unsigned int, std::allocator< unsigned int > >, std::allocator< std::vector< unsigned int, std::allocator< unsigned int > > > >&', 'ns3::SampleRate&')
typehandlers.add_type_alias('ns3::Vector3DChecker', 'ns3::VectorChecker')
typehandlers.add_type_alias('ns3::Vector3DChecker*', 'ns3::VectorChecker*')
typehandlers.add_type_alias('ns3::Vector3DChecker&', '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 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_internal(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper'])
register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice'])
register_Ns3AthstatsHelper_methods(root_module, root_module['ns3::AthstatsHelper'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3Bar_methods(root_module, root_module['ns3::Bar'])
register_Ns3BlockAckAgreement_methods(root_module, root_module['ns3::BlockAckAgreement'])
register_Ns3BlockAckCache_methods(root_module, root_module['ns3::BlockAckCache'])
register_Ns3BlockAckManager_methods(root_module, root_module['ns3::BlockAckManager'])
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_Ns3CapabilityInformation_methods(root_module, root_module['ns3::CapabilityInformation'])
register_Ns3DcfManager_methods(root_module, root_module['ns3::DcfManager'])
register_Ns3DcfState_methods(root_module, root_module['ns3::DcfState'])
register_Ns3DsssErrorRateModel_methods(root_module, root_module['ns3::DsssErrorRateModel'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3InterferenceHelper_methods(root_module, root_module['ns3::InterferenceHelper'])
register_Ns3InterferenceHelperSnrPer_methods(root_module, root_module['ns3::InterferenceHelper::SnrPer'])
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_Ns3MacLowBlockAckEventListener_methods(root_module, root_module['ns3::MacLowBlockAckEventListener'])
register_Ns3MacLowDcfListener_methods(root_module, root_module['ns3::MacLowDcfListener'])
register_Ns3MacLowTransmissionListener_methods(root_module, root_module['ns3::MacLowTransmissionListener'])
register_Ns3MacLowTransmissionParameters_methods(root_module, root_module['ns3::MacLowTransmissionParameters'])
register_Ns3MacRxMiddle_methods(root_module, root_module['ns3::MacRxMiddle'])
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_Ns3OriginatorBlockAckAgreement_methods(root_module, root_module['ns3::OriginatorBlockAckAgreement'])
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_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile'])
register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper'])
register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice'])
register_Ns3PropagationCache__Ns3JakesProcess_methods(root_module, root_module['ns3::PropagationCache< ns3::JakesProcess >'])
register_Ns3RandomVariable_methods(root_module, root_module['ns3::RandomVariable'])
register_Ns3RateInfo_methods(root_module, root_module['ns3::RateInfo'])
register_Ns3SeedManager_methods(root_module, root_module['ns3::SeedManager'])
register_Ns3SequentialVariable_methods(root_module, root_module['ns3::SequentialVariable'])
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_Ns3StatusCode_methods(root_module, root_module['ns3::StatusCode'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3TriangularVariable_methods(root_module, root_module['ns3::TriangularVariable'])
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_Ns3UniformVariable_methods(root_module, root_module['ns3::UniformVariable'])
register_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D'])
register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D'])
register_Ns3WeibullVariable_methods(root_module, root_module['ns3::WeibullVariable'])
register_Ns3WifiHelper_methods(root_module, root_module['ns3::WifiHelper'])
register_Ns3WifiMacHelper_methods(root_module, root_module['ns3::WifiMacHelper'])
register_Ns3WifiMode_methods(root_module, root_module['ns3::WifiMode'])
register_Ns3WifiModeFactory_methods(root_module, root_module['ns3::WifiModeFactory'])
register_Ns3WifiPhyHelper_methods(root_module, root_module['ns3::WifiPhyHelper'])
register_Ns3WifiPhyListener_methods(root_module, root_module['ns3::WifiPhyListener'])
register_Ns3WifiRemoteStation_methods(root_module, root_module['ns3::WifiRemoteStation'])
register_Ns3WifiRemoteStationInfo_methods(root_module, root_module['ns3::WifiRemoteStationInfo'])
register_Ns3WifiRemoteStationState_methods(root_module, root_module['ns3::WifiRemoteStationState'])
register_Ns3YansWifiChannelHelper_methods(root_module, root_module['ns3::YansWifiChannelHelper'])
register_Ns3YansWifiPhyHelper_methods(root_module, root_module['ns3::YansWifiPhyHelper'])
register_Ns3ZetaVariable_methods(root_module, root_module['ns3::ZetaVariable'])
register_Ns3ZipfVariable_methods(root_module, root_module['ns3::ZipfVariable'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3ConstantVariable_methods(root_module, root_module['ns3::ConstantVariable'])
register_Ns3DeterministicVariable_methods(root_module, root_module['ns3::DeterministicVariable'])
register_Ns3EmpiricalVariable_methods(root_module, root_module['ns3::EmpiricalVariable'])
register_Ns3ErlangVariable_methods(root_module, root_module['ns3::ErlangVariable'])
register_Ns3ExponentialVariable_methods(root_module, root_module['ns3::ExponentialVariable'])
register_Ns3GammaVariable_methods(root_module, root_module['ns3::GammaVariable'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3IntEmpiricalVariable_methods(root_module, root_module['ns3::IntEmpiricalVariable'])
register_Ns3LogNormalVariable_methods(root_module, root_module['ns3::LogNormalVariable'])
register_Ns3MgtAddBaRequestHeader_methods(root_module, root_module['ns3::MgtAddBaRequestHeader'])
register_Ns3MgtAddBaResponseHeader_methods(root_module, root_module['ns3::MgtAddBaResponseHeader'])
register_Ns3MgtAssocRequestHeader_methods(root_module, root_module['ns3::MgtAssocRequestHeader'])
register_Ns3MgtAssocResponseHeader_methods(root_module, root_module['ns3::MgtAssocResponseHeader'])
register_Ns3MgtDelBaHeader_methods(root_module, root_module['ns3::MgtDelBaHeader'])
register_Ns3MgtProbeRequestHeader_methods(root_module, root_module['ns3::MgtProbeRequestHeader'])
register_Ns3MgtProbeResponseHeader_methods(root_module, root_module['ns3::MgtProbeResponseHeader'])
register_Ns3NormalVariable_methods(root_module, root_module['ns3::NormalVariable'])
register_Ns3NqosWifiMacHelper_methods(root_module, root_module['ns3::NqosWifiMacHelper'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3ParetoVariable_methods(root_module, root_module['ns3::ParetoVariable'])
register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper'])
register_Ns3PropagationDelayModel_methods(root_module, root_module['ns3::PropagationDelayModel'])
register_Ns3PropagationLossModel_methods(root_module, root_module['ns3::PropagationLossModel'])
register_Ns3QosTag_methods(root_module, root_module['ns3::QosTag'])
register_Ns3QosWifiMacHelper_methods(root_module, root_module['ns3::QosWifiMacHelper'])
register_Ns3RandomPropagationDelayModel_methods(root_module, root_module['ns3::RandomPropagationDelayModel'])
register_Ns3RandomPropagationLossModel_methods(root_module, root_module['ns3::RandomPropagationLossModel'])
register_Ns3RangePropagationLossModel_methods(root_module, root_module['ns3::RangePropagationLossModel'])
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__Ns3InterferenceHelperEvent_Ns3Empty_Ns3DefaultDeleter__lt__ns3InterferenceHelperEvent__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> >'])
register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3SimpleRefCount__Ns3WifiInformationElement_Ns3Empty_Ns3DefaultDeleter__lt__ns3WifiInformationElement__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >'])
register_Ns3ThreeLogDistancePropagationLossModel_methods(root_module, root_module['ns3::ThreeLogDistancePropagationLossModel'])
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_Ns3TwoRayGroundPropagationLossModel_methods(root_module, root_module['ns3::TwoRayGroundPropagationLossModel'])
register_Ns3WifiActionHeader_methods(root_module, root_module['ns3::WifiActionHeader'])
register_Ns3WifiActionHeaderActionValue_methods(root_module, root_module['ns3::WifiActionHeader::ActionValue'])
register_Ns3WifiInformationElement_methods(root_module, root_module['ns3::WifiInformationElement'])
register_Ns3WifiInformationElementVector_methods(root_module, root_module['ns3::WifiInformationElementVector'])
register_Ns3WifiMac_methods(root_module, root_module['ns3::WifiMac'])
register_Ns3WifiMacHeader_methods(root_module, root_module['ns3::WifiMacHeader'])
register_Ns3WifiMacQueue_methods(root_module, root_module['ns3::WifiMacQueue'])
register_Ns3WifiPhy_methods(root_module, root_module['ns3::WifiPhy'])
register_Ns3WifiRemoteStationManager_methods(root_module, root_module['ns3::WifiRemoteStationManager'])
register_Ns3YansWifiPhy_methods(root_module, root_module['ns3::YansWifiPhy'])
register_Ns3AarfWifiManager_methods(root_module, root_module['ns3::AarfWifiManager'])
register_Ns3AarfcdWifiManager_methods(root_module, root_module['ns3::AarfcdWifiManager'])
register_Ns3AmrrWifiManager_methods(root_module, root_module['ns3::AmrrWifiManager'])
register_Ns3AmsduSubframeHeader_methods(root_module, root_module['ns3::AmsduSubframeHeader'])
register_Ns3ArfWifiManager_methods(root_module, root_module['ns3::ArfWifiManager'])
register_Ns3AthstatsWifiTraceSink_methods(root_module, root_module['ns3::AthstatsWifiTraceSink'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3CaraWifiManager_methods(root_module, root_module['ns3::CaraWifiManager'])
register_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3ConstantRateWifiManager_methods(root_module, root_module['ns3::ConstantRateWifiManager'])
register_Ns3ConstantSpeedPropagationDelayModel_methods(root_module, root_module['ns3::ConstantSpeedPropagationDelayModel'])
register_Ns3Cost231PropagationLossModel_methods(root_module, root_module['ns3::Cost231PropagationLossModel'])
register_Ns3CtrlBAckRequestHeader_methods(root_module, root_module['ns3::CtrlBAckRequestHeader'])
register_Ns3CtrlBAckResponseHeader_methods(root_module, root_module['ns3::CtrlBAckResponseHeader'])
register_Ns3Dcf_methods(root_module, root_module['ns3::Dcf'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3EdcaTxopN_methods(root_module, root_module['ns3::EdcaTxopN'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3ErrorRateModel_methods(root_module, root_module['ns3::ErrorRateModel'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3ExtendedSupportedRatesIE_methods(root_module, root_module['ns3::ExtendedSupportedRatesIE'])
register_Ns3FixedRssLossModel_methods(root_module, root_module['ns3::FixedRssLossModel'])
register_Ns3FriisPropagationLossModel_methods(root_module, root_module['ns3::FriisPropagationLossModel'])
register_Ns3IdealWifiManager_methods(root_module, root_module['ns3::IdealWifiManager'])
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_Ns3ItuR1411LosPropagationLossModel_methods(root_module, root_module['ns3::ItuR1411LosPropagationLossModel'])
register_Ns3ItuR1411NlosOverRooftopPropagationLossModel_methods(root_module, root_module['ns3::ItuR1411NlosOverRooftopPropagationLossModel'])
register_Ns3JakesProcess_methods(root_module, root_module['ns3::JakesProcess'])
register_Ns3JakesPropagationLossModel_methods(root_module, root_module['ns3::JakesPropagationLossModel'])
register_Ns3Kun2600MhzPropagationLossModel_methods(root_module, root_module['ns3::Kun2600MhzPropagationLossModel'])
register_Ns3LogDistancePropagationLossModel_methods(root_module, root_module['ns3::LogDistancePropagationLossModel'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3MacLow_methods(root_module, root_module['ns3::MacLow'])
register_Ns3MatrixPropagationLossModel_methods(root_module, root_module['ns3::MatrixPropagationLossModel'])
register_Ns3MgtBeaconHeader_methods(root_module, root_module['ns3::MgtBeaconHeader'])
register_Ns3MinstrelWifiManager_methods(root_module, root_module['ns3::MinstrelWifiManager'])
register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel'])
register_Ns3MsduAggregator_methods(root_module, root_module['ns3::MsduAggregator'])
register_Ns3NakagamiPropagationLossModel_methods(root_module, root_module['ns3::NakagamiPropagationLossModel'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NistErrorRateModel_methods(root_module, root_module['ns3::NistErrorRateModel'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3OkumuraHataPropagationLossModel_methods(root_module, root_module['ns3::OkumuraHataPropagationLossModel'])
register_Ns3OnoeWifiManager_methods(root_module, root_module['ns3::OnoeWifiManager'])
register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3RandomVariableChecker_methods(root_module, root_module['ns3::RandomVariableChecker'])
register_Ns3RandomVariableValue_methods(root_module, root_module['ns3::RandomVariableValue'])
register_Ns3RegularWifiMac_methods(root_module, root_module['ns3::RegularWifiMac'])
register_Ns3RraaWifiManager_methods(root_module, root_module['ns3::RraaWifiManager'])
register_Ns3Ssid_methods(root_module, root_module['ns3::Ssid'])
register_Ns3SsidChecker_methods(root_module, root_module['ns3::SsidChecker'])
register_Ns3SsidValue_methods(root_module, root_module['ns3::SsidValue'])
register_Ns3StaWifiMac_methods(root_module, root_module['ns3::StaWifiMac'])
register_Ns3SupportedRates_methods(root_module, root_module['ns3::SupportedRates'])
register_Ns3TimeChecker_methods(root_module, root_module['ns3::TimeChecker'])
register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue'])
register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker'])
register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue'])
register_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_Ns3WifiChannel_methods(root_module, root_module['ns3::WifiChannel'])
register_Ns3WifiModeChecker_methods(root_module, root_module['ns3::WifiModeChecker'])
register_Ns3WifiModeValue_methods(root_module, root_module['ns3::WifiModeValue'])
register_Ns3WifiNetDevice_methods(root_module, root_module['ns3::WifiNetDevice'])
register_Ns3YansErrorRateModel_methods(root_module, root_module['ns3::YansErrorRateModel'])
register_Ns3YansWifiChannel_methods(root_module, root_module['ns3::YansWifiChannel'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3AdhocWifiMac_methods(root_module, root_module['ns3::AdhocWifiMac'])
register_Ns3ApWifiMac_methods(root_module, root_module['ns3::ApWifiMac'])
register_Ns3DcaTxop_methods(root_module, root_module['ns3::DcaTxop'])
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_Ns3AsciiTraceHelper_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::_Ios_Openmode filemode=std::ios_base::out) [member function]
cls.add_method('CreateFileStream',
'ns3::Ptr< ns3::OutputStreamWrapper >',
[param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode', default_value='std::ios_base::out')])
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDequeueSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDequeueSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDropSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDropSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultEnqueueSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultEnqueueSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultReceiveSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultReceiveSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromDevice',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')])
## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromInterfacePair',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')])
return
def register_Ns3AsciiTraceHelperForDevice_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice(ns3::AsciiTraceHelperForDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AsciiTraceHelperForDevice const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename=false) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::NetDevice> nd) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::NetDevice >', 'nd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, std::string ndName, bool explicitFilename=false) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ndName) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ndName')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NetDeviceContainer', 'd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t deviceid) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(std::string prefix) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('std::string', 'prefix')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function]
cls.add_method('EnableAsciiInternal',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3AthstatsHelper_methods(root_module, cls):
## athstats-helper.h (module 'wifi'): ns3::AthstatsHelper::AthstatsHelper(ns3::AthstatsHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AthstatsHelper const &', 'arg0')])
## athstats-helper.h (module 'wifi'): ns3::AthstatsHelper::AthstatsHelper() [constructor]
cls.add_constructor([])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsHelper::EnableAthstats(std::string filename, uint32_t nodeid, uint32_t deviceid) [member function]
cls.add_method('EnableAthstats',
'void',
[param('std::string', 'filename'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsHelper::EnableAthstats(std::string filename, ns3::Ptr<ns3::NetDevice> nd) [member function]
cls.add_method('EnableAthstats',
'void',
[param('std::string', 'filename'), param('ns3::Ptr< ns3::NetDevice >', 'nd')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsHelper::EnableAthstats(std::string filename, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAthstats',
'void',
[param('std::string', 'filename'), param('ns3::NetDeviceContainer', 'd')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsHelper::EnableAthstats(std::string filename, ns3::NodeContainer n) [member function]
cls.add_method('EnableAthstats',
'void',
[param('std::string', 'filename'), param('ns3::NodeContainer', 'n')])
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_Ns3Bar_methods(root_module, cls):
## block-ack-manager.h (module 'wifi'): ns3::Bar::Bar(ns3::Bar const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Bar const &', 'arg0')])
## block-ack-manager.h (module 'wifi'): ns3::Bar::Bar() [constructor]
cls.add_constructor([])
## block-ack-manager.h (module 'wifi'): ns3::Bar::Bar(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address recipient, uint8_t tid, bool immediate) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('bool', 'immediate')])
## block-ack-manager.h (module 'wifi'): ns3::Bar::bar [variable]
cls.add_instance_attribute('bar', 'ns3::Ptr< ns3::Packet const >', is_const=False)
## block-ack-manager.h (module 'wifi'): ns3::Bar::immediate [variable]
cls.add_instance_attribute('immediate', 'bool', is_const=False)
## block-ack-manager.h (module 'wifi'): ns3::Bar::recipient [variable]
cls.add_instance_attribute('recipient', 'ns3::Mac48Address', is_const=False)
## block-ack-manager.h (module 'wifi'): ns3::Bar::tid [variable]
cls.add_instance_attribute('tid', 'uint8_t', is_const=False)
return
def register_Ns3BlockAckAgreement_methods(root_module, cls):
## block-ack-agreement.h (module 'wifi'): ns3::BlockAckAgreement::BlockAckAgreement(ns3::BlockAckAgreement const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BlockAckAgreement const &', 'arg0')])
## block-ack-agreement.h (module 'wifi'): ns3::BlockAckAgreement::BlockAckAgreement() [constructor]
cls.add_constructor([])
## block-ack-agreement.h (module 'wifi'): ns3::BlockAckAgreement::BlockAckAgreement(ns3::Mac48Address peer, uint8_t tid) [constructor]
cls.add_constructor([param('ns3::Mac48Address', 'peer'), param('uint8_t', 'tid')])
## block-ack-agreement.h (module 'wifi'): uint16_t ns3::BlockAckAgreement::GetBufferSize() const [member function]
cls.add_method('GetBufferSize',
'uint16_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): ns3::Mac48Address ns3::BlockAckAgreement::GetPeer() const [member function]
cls.add_method('GetPeer',
'ns3::Mac48Address',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): uint16_t ns3::BlockAckAgreement::GetStartingSequence() const [member function]
cls.add_method('GetStartingSequence',
'uint16_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): uint16_t ns3::BlockAckAgreement::GetStartingSequenceControl() const [member function]
cls.add_method('GetStartingSequenceControl',
'uint16_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): uint8_t ns3::BlockAckAgreement::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): uint16_t ns3::BlockAckAgreement::GetTimeout() const [member function]
cls.add_method('GetTimeout',
'uint16_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): bool ns3::BlockAckAgreement::IsAmsduSupported() const [member function]
cls.add_method('IsAmsduSupported',
'bool',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): bool ns3::BlockAckAgreement::IsImmediateBlockAck() const [member function]
cls.add_method('IsImmediateBlockAck',
'bool',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetAmsduSupport(bool supported) [member function]
cls.add_method('SetAmsduSupport',
'void',
[param('bool', 'supported')])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetBufferSize(uint16_t bufferSize) [member function]
cls.add_method('SetBufferSize',
'void',
[param('uint16_t', 'bufferSize')])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetDelayedBlockAck() [member function]
cls.add_method('SetDelayedBlockAck',
'void',
[])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetImmediateBlockAck() [member function]
cls.add_method('SetImmediateBlockAck',
'void',
[])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetStartingSequence(uint16_t seq) [member function]
cls.add_method('SetStartingSequence',
'void',
[param('uint16_t', 'seq')])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetTimeout(uint16_t timeout) [member function]
cls.add_method('SetTimeout',
'void',
[param('uint16_t', 'timeout')])
return
def register_Ns3BlockAckCache_methods(root_module, cls):
## block-ack-cache.h (module 'wifi'): ns3::BlockAckCache::BlockAckCache() [constructor]
cls.add_constructor([])
## block-ack-cache.h (module 'wifi'): ns3::BlockAckCache::BlockAckCache(ns3::BlockAckCache const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BlockAckCache const &', 'arg0')])
## block-ack-cache.h (module 'wifi'): void ns3::BlockAckCache::FillBlockAckBitmap(ns3::CtrlBAckResponseHeader * blockAckHeader) [member function]
cls.add_method('FillBlockAckBitmap',
'void',
[param('ns3::CtrlBAckResponseHeader *', 'blockAckHeader')])
## block-ack-cache.h (module 'wifi'): void ns3::BlockAckCache::Init(uint16_t winStart, uint16_t winSize) [member function]
cls.add_method('Init',
'void',
[param('uint16_t', 'winStart'), param('uint16_t', 'winSize')])
## block-ack-cache.h (module 'wifi'): void ns3::BlockAckCache::UpdateWithBlockAckReq(uint16_t startingSeq) [member function]
cls.add_method('UpdateWithBlockAckReq',
'void',
[param('uint16_t', 'startingSeq')])
## block-ack-cache.h (module 'wifi'): void ns3::BlockAckCache::UpdateWithMpdu(ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('UpdateWithMpdu',
'void',
[param('ns3::WifiMacHeader const *', 'hdr')])
return
def register_Ns3BlockAckManager_methods(root_module, cls):
## block-ack-manager.h (module 'wifi'): ns3::BlockAckManager::BlockAckManager() [constructor]
cls.add_constructor([])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::CreateAgreement(ns3::MgtAddBaRequestHeader const * reqHdr, ns3::Mac48Address recipient) [member function]
cls.add_method('CreateAgreement',
'void',
[param('ns3::MgtAddBaRequestHeader const *', 'reqHdr'), param('ns3::Mac48Address', 'recipient')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::DestroyAgreement(ns3::Mac48Address recipient, uint8_t tid) [member function]
cls.add_method('DestroyAgreement',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')])
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::ExistsAgreement(ns3::Mac48Address recipient, uint8_t tid) const [member function]
cls.add_method('ExistsAgreement',
'bool',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')],
is_const=True)
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::ExistsAgreementInState(ns3::Mac48Address recipient, uint8_t tid, ns3::OriginatorBlockAckAgreement::State state) const [member function]
cls.add_method('ExistsAgreementInState',
'bool',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('ns3::OriginatorBlockAckAgreement::State', 'state')],
is_const=True)
## block-ack-manager.h (module 'wifi'): uint32_t ns3::BlockAckManager::GetNBufferedPackets(ns3::Mac48Address recipient, uint8_t tid) const [member function]
cls.add_method('GetNBufferedPackets',
'uint32_t',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')],
is_const=True)
## block-ack-manager.h (module 'wifi'): uint32_t ns3::BlockAckManager::GetNRetryNeededPackets(ns3::Mac48Address recipient, uint8_t tid) const [member function]
cls.add_method('GetNRetryNeededPackets',
'uint32_t',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')],
is_const=True)
## block-ack-manager.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::BlockAckManager::GetNextPacket(ns3::WifiMacHeader & hdr) [member function]
cls.add_method('GetNextPacket',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader &', 'hdr')])
## block-ack-manager.h (module 'wifi'): uint32_t ns3::BlockAckManager::GetNextPacketSize() const [member function]
cls.add_method('GetNextPacketSize',
'uint32_t',
[],
is_const=True)
## block-ack-manager.h (module 'wifi'): uint16_t ns3::BlockAckManager::GetSeqNumOfNextRetryPacket(ns3::Mac48Address recipient, uint8_t tid) const [member function]
cls.add_method('GetSeqNumOfNextRetryPacket',
'uint16_t',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')],
is_const=True)
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::HasBar(ns3::Bar & bar) [member function]
cls.add_method('HasBar',
'bool',
[param('ns3::Bar &', 'bar')])
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::HasOtherFragments(uint16_t sequenceNumber) const [member function]
cls.add_method('HasOtherFragments',
'bool',
[param('uint16_t', 'sequenceNumber')],
is_const=True)
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::HasPackets() const [member function]
cls.add_method('HasPackets',
'bool',
[],
is_const=True)
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::NotifyAgreementEstablished(ns3::Mac48Address recipient, uint8_t tid, uint16_t startingSeq) [member function]
cls.add_method('NotifyAgreementEstablished',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('uint16_t', 'startingSeq')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::NotifyAgreementUnsuccessful(ns3::Mac48Address recipient, uint8_t tid) [member function]
cls.add_method('NotifyAgreementUnsuccessful',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::NotifyGotBlockAck(ns3::CtrlBAckResponseHeader const * blockAck, ns3::Mac48Address recipient) [member function]
cls.add_method('NotifyGotBlockAck',
'void',
[param('ns3::CtrlBAckResponseHeader const *', 'blockAck'), param('ns3::Mac48Address', 'recipient')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::NotifyMpduTransmission(ns3::Mac48Address recipient, uint8_t tid, uint16_t nextSeqNumber) [member function]
cls.add_method('NotifyMpduTransmission',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('uint16_t', 'nextSeqNumber')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetBlockAckInactivityCallback(ns3::Callback<void, ns3::Mac48Address, unsigned char, bool, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetBlockAckInactivityCallback',
'void',
[param('ns3::Callback< void, ns3::Mac48Address, unsigned char, bool, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetBlockAckThreshold(uint8_t nPackets) [member function]
cls.add_method('SetBlockAckThreshold',
'void',
[param('uint8_t', 'nPackets')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetBlockAckType(ns3::BlockAckType bAckType) [member function]
cls.add_method('SetBlockAckType',
'void',
[param('ns3::BlockAckType', 'bAckType')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetBlockDestinationCallback(ns3::Callback<void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetBlockDestinationCallback',
'void',
[param('ns3::Callback< void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetMaxPacketDelay(ns3::Time maxDelay) [member function]
cls.add_method('SetMaxPacketDelay',
'void',
[param('ns3::Time', 'maxDelay')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetQueue(ns3::Ptr<ns3::WifiMacQueue> queue) [member function]
cls.add_method('SetQueue',
'void',
[param('ns3::Ptr< ns3::WifiMacQueue >', 'queue')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetTxMiddle(ns3::MacTxMiddle * txMiddle) [member function]
cls.add_method('SetTxMiddle',
'void',
[param('ns3::MacTxMiddle *', 'txMiddle')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetUnblockDestinationCallback(ns3::Callback<void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetUnblockDestinationCallback',
'void',
[param('ns3::Callback< void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::StorePacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr, ns3::Time tStamp) [member function]
cls.add_method('StorePacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr'), param('ns3::Time', 'tStamp')])
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::SwitchToBlockAckIfNeeded(ns3::Mac48Address recipient, uint8_t tid, uint16_t startingSeq) [member function]
cls.add_method('SwitchToBlockAckIfNeeded',
'bool',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('uint16_t', 'startingSeq')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::TearDownBlockAck(ns3::Mac48Address recipient, uint8_t tid) [member function]
cls.add_method('TearDownBlockAck',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::UpdateAgreement(ns3::MgtAddBaResponseHeader const * respHdr, ns3::Mac48Address recipient) [member function]
cls.add_method('UpdateAgreement',
'void',
[param('ns3::MgtAddBaResponseHeader const *', 'respHdr'), param('ns3::Mac48Address', 'recipient')])
return
def register_Ns3Buffer_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor]
cls.add_constructor([param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'bool',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'bool',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function]
cls.add_method('Begin',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Buffer',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function]
cls.add_method('CreateFullCopy',
'ns3::Buffer',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function]
cls.add_method('End',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function]
cls.add_method('GetCurrentEndOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function]
cls.add_method('GetCurrentStartOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3BufferIterator_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')])
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function]
cls.add_method('GetDistanceFrom',
'uint32_t',
[param('ns3::Buffer::Iterator const &', 'o')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function]
cls.add_method('IsEnd',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function]
cls.add_method('IsStart',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function]
cls.add_method('Next',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function]
cls.add_method('Next',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function]
cls.add_method('Prev',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function]
cls.add_method('Prev',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function]
cls.add_method('ReadLsbtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function]
cls.add_method('ReadLsbtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function]
cls.add_method('ReadLsbtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function]
cls.add_method('ReadNtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function]
cls.add_method('ReadNtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function]
cls.add_method('ReadNtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Write',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function]
cls.add_method('WriteHtolsbU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function]
cls.add_method('WriteHtolsbU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function]
cls.add_method('WriteHtolsbU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function]
cls.add_method('WriteHtonU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function]
cls.add_method('WriteHtonU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function]
cls.add_method('WriteHtonU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data'), param('uint32_t', 'len')])
return
def register_Ns3ByteTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagIterator::Item',
[])
return
def register_Ns3ByteTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function]
cls.add_method('GetEnd',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function]
cls.add_method('GetStart',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3ByteTagList_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor]
cls.add_constructor([])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function]
cls.add_method('Add',
'ns3::TagBuffer',
[param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function]
cls.add_method('Add',
'void',
[param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function]
cls.add_method('AddAtEnd',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function]
cls.add_method('AddAtStart',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function]
cls.add_method('Begin',
'ns3::ByteTagList::Iterator',
[param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')],
is_const=True)
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3ByteTagListIterator_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')])
## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function]
cls.add_method('GetOffsetStart',
'uint32_t',
[],
is_const=True)
## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagList::Iterator::Item',
[])
return
def register_Ns3ByteTagListIteratorItem_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor]
cls.add_constructor([param('ns3::TagBuffer', 'buf')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable]
cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable]
cls.add_instance_attribute('end', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable]
cls.add_instance_attribute('size', 'uint32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable]
cls.add_instance_attribute('start', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3CallbackBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function]
cls.add_method('GetImpl',
'ns3::Ptr< ns3::CallbackImplBase >',
[],
is_const=True)
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')],
visibility='protected')
## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3CapabilityInformation_methods(root_module, cls):
## capability-information.h (module 'wifi'): ns3::CapabilityInformation::CapabilityInformation(ns3::CapabilityInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CapabilityInformation const &', 'arg0')])
## capability-information.h (module 'wifi'): ns3::CapabilityInformation::CapabilityInformation() [constructor]
cls.add_constructor([])
## capability-information.h (module 'wifi'): ns3::Buffer::Iterator ns3::CapabilityInformation::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')])
## capability-information.h (module 'wifi'): uint32_t ns3::CapabilityInformation::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## capability-information.h (module 'wifi'): bool ns3::CapabilityInformation::IsEss() const [member function]
cls.add_method('IsEss',
'bool',
[],
is_const=True)
## capability-information.h (module 'wifi'): bool ns3::CapabilityInformation::IsIbss() const [member function]
cls.add_method('IsIbss',
'bool',
[],
is_const=True)
## capability-information.h (module 'wifi'): ns3::Buffer::Iterator ns3::CapabilityInformation::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## capability-information.h (module 'wifi'): void ns3::CapabilityInformation::SetEss() [member function]
cls.add_method('SetEss',
'void',
[])
## capability-information.h (module 'wifi'): void ns3::CapabilityInformation::SetIbss() [member function]
cls.add_method('SetIbss',
'void',
[])
return
def register_Ns3DcfManager_methods(root_module, cls):
## dcf-manager.h (module 'wifi'): ns3::DcfManager::DcfManager(ns3::DcfManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DcfManager const &', 'arg0')])
## dcf-manager.h (module 'wifi'): ns3::DcfManager::DcfManager() [constructor]
cls.add_constructor([])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::Add(ns3::DcfState * dcf) [member function]
cls.add_method('Add',
'void',
[param('ns3::DcfState *', 'dcf')])
## dcf-manager.h (module 'wifi'): ns3::Time ns3::DcfManager::GetEifsNoDifs() const [member function]
cls.add_method('GetEifsNoDifs',
'ns3::Time',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyAckTimeoutResetNow() [member function]
cls.add_method('NotifyAckTimeoutResetNow',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyAckTimeoutStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyAckTimeoutStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyCtsTimeoutResetNow() [member function]
cls.add_method('NotifyCtsTimeoutResetNow',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyCtsTimeoutStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyCtsTimeoutStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyMaybeCcaBusyStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyMaybeCcaBusyStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyNavResetNow(ns3::Time duration) [member function]
cls.add_method('NotifyNavResetNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyNavStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyNavStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyRxEndErrorNow() [member function]
cls.add_method('NotifyRxEndErrorNow',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyRxEndOkNow() [member function]
cls.add_method('NotifyRxEndOkNow',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyRxStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyRxStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifySwitchingStartNow(ns3::Time duration) [member function]
cls.add_method('NotifySwitchingStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyTxStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyTxStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::RequestAccess(ns3::DcfState * state) [member function]
cls.add_method('RequestAccess',
'void',
[param('ns3::DcfState *', 'state')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function]
cls.add_method('SetEifsNoDifs',
'void',
[param('ns3::Time', 'eifsNoDifs')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetSifs(ns3::Time sifs) [member function]
cls.add_method('SetSifs',
'void',
[param('ns3::Time', 'sifs')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetSlot(ns3::Time slotTime) [member function]
cls.add_method('SetSlot',
'void',
[param('ns3::Time', 'slotTime')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetupLowListener(ns3::Ptr<ns3::MacLow> low) [member function]
cls.add_method('SetupLowListener',
'void',
[param('ns3::Ptr< ns3::MacLow >', 'low')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetupPhyListener(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetupPhyListener',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')])
return
def register_Ns3DcfState_methods(root_module, cls):
## dcf-manager.h (module 'wifi'): ns3::DcfState::DcfState(ns3::DcfState const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DcfState const &', 'arg0')])
## dcf-manager.h (module 'wifi'): ns3::DcfState::DcfState() [constructor]
cls.add_constructor([])
## dcf-manager.h (module 'wifi'): uint32_t ns3::DcfState::GetAifsn() const [member function]
cls.add_method('GetAifsn',
'uint32_t',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): uint32_t ns3::DcfState::GetCw() const [member function]
cls.add_method('GetCw',
'uint32_t',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): uint32_t ns3::DcfState::GetCwMax() const [member function]
cls.add_method('GetCwMax',
'uint32_t',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): uint32_t ns3::DcfState::GetCwMin() const [member function]
cls.add_method('GetCwMin',
'uint32_t',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): bool ns3::DcfState::IsAccessRequested() const [member function]
cls.add_method('IsAccessRequested',
'bool',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfState::ResetCw() [member function]
cls.add_method('ResetCw',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::SetAifsn(uint32_t aifsn) [member function]
cls.add_method('SetAifsn',
'void',
[param('uint32_t', 'aifsn')])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::SetCwMax(uint32_t maxCw) [member function]
cls.add_method('SetCwMax',
'void',
[param('uint32_t', 'maxCw')])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::SetCwMin(uint32_t minCw) [member function]
cls.add_method('SetCwMin',
'void',
[param('uint32_t', 'minCw')])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::StartBackoffNow(uint32_t nSlots) [member function]
cls.add_method('StartBackoffNow',
'void',
[param('uint32_t', 'nSlots')])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::UpdateFailedCw() [member function]
cls.add_method('UpdateFailedCw',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::DoNotifyAccessGranted() [member function]
cls.add_method('DoNotifyAccessGranted',
'void',
[],
is_pure_virtual=True, visibility='private', is_virtual=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfState::DoNotifyChannelSwitching() [member function]
cls.add_method('DoNotifyChannelSwitching',
'void',
[],
is_pure_virtual=True, visibility='private', is_virtual=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfState::DoNotifyCollision() [member function]
cls.add_method('DoNotifyCollision',
'void',
[],
is_pure_virtual=True, visibility='private', is_virtual=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfState::DoNotifyInternalCollision() [member function]
cls.add_method('DoNotifyInternalCollision',
'void',
[],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3DsssErrorRateModel_methods(root_module, cls):
## dsss-error-rate-model.h (module 'wifi'): ns3::DsssErrorRateModel::DsssErrorRateModel() [constructor]
cls.add_constructor([])
## dsss-error-rate-model.h (module 'wifi'): ns3::DsssErrorRateModel::DsssErrorRateModel(ns3::DsssErrorRateModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DsssErrorRateModel const &', 'arg0')])
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::DqpskFunction(double x) [member function]
cls.add_method('DqpskFunction',
'double',
[param('double', 'x')],
is_static=True)
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::GetDsssDbpskSuccessRate(double sinr, uint32_t nbits) [member function]
cls.add_method('GetDsssDbpskSuccessRate',
'double',
[param('double', 'sinr'), param('uint32_t', 'nbits')],
is_static=True)
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::GetDsssDqpskCck11SuccessRate(double sinr, uint32_t nbits) [member function]
cls.add_method('GetDsssDqpskCck11SuccessRate',
'double',
[param('double', 'sinr'), param('uint32_t', 'nbits')],
is_static=True)
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::GetDsssDqpskCck5_5SuccessRate(double sinr, uint32_t nbits) [member function]
cls.add_method('GetDsssDqpskCck5_5SuccessRate',
'double',
[param('double', 'sinr'), param('uint32_t', 'nbits')],
is_static=True)
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::GetDsssDqpskSuccessRate(double sinr, uint32_t nbits) [member function]
cls.add_method('GetDsssDqpskSuccessRate',
'double',
[param('double', 'sinr'), param('uint32_t', 'nbits')],
is_static=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_Ns3InterferenceHelper_methods(root_module, cls):
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::InterferenceHelper() [constructor]
cls.add_constructor([])
## interference-helper.h (module 'wifi'): ns3::Ptr<ns3::InterferenceHelper::Event> ns3::InterferenceHelper::Add(uint32_t size, ns3::WifiMode payloadMode, ns3::WifiPreamble preamble, ns3::Time duration, double rxPower) [member function]
cls.add_method('Add',
'ns3::Ptr< ns3::InterferenceHelper::Event >',
[param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble'), param('ns3::Time', 'duration'), param('double', 'rxPower')])
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer ns3::InterferenceHelper::CalculateSnrPer(ns3::Ptr<ns3::InterferenceHelper::Event> event) [member function]
cls.add_method('CalculateSnrPer',
'ns3::InterferenceHelper::SnrPer',
[param('ns3::Ptr< ns3::InterferenceHelper::Event >', 'event')])
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::EraseEvents() [member function]
cls.add_method('EraseEvents',
'void',
[])
## interference-helper.h (module 'wifi'): ns3::Time ns3::InterferenceHelper::GetEnergyDuration(double energyW) [member function]
cls.add_method('GetEnergyDuration',
'ns3::Time',
[param('double', 'energyW')])
## interference-helper.h (module 'wifi'): ns3::Ptr<ns3::ErrorRateModel> ns3::InterferenceHelper::GetErrorRateModel() const [member function]
cls.add_method('GetErrorRateModel',
'ns3::Ptr< ns3::ErrorRateModel >',
[],
is_const=True)
## interference-helper.h (module 'wifi'): double ns3::InterferenceHelper::GetNoiseFigure() const [member function]
cls.add_method('GetNoiseFigure',
'double',
[],
is_const=True)
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::NotifyRxEnd() [member function]
cls.add_method('NotifyRxEnd',
'void',
[])
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::NotifyRxStart() [member function]
cls.add_method('NotifyRxStart',
'void',
[])
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::SetErrorRateModel(ns3::Ptr<ns3::ErrorRateModel> rate) [member function]
cls.add_method('SetErrorRateModel',
'void',
[param('ns3::Ptr< ns3::ErrorRateModel >', 'rate')])
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::SetNoiseFigure(double value) [member function]
cls.add_method('SetNoiseFigure',
'void',
[param('double', 'value')])
return
def register_Ns3InterferenceHelperSnrPer_methods(root_module, cls):
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer::SnrPer() [constructor]
cls.add_constructor([])
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer::SnrPer(ns3::InterferenceHelper::SnrPer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::InterferenceHelper::SnrPer const &', 'arg0')])
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer::per [variable]
cls.add_instance_attribute('per', 'double', is_const=False)
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer::snr [variable]
cls.add_instance_attribute('snr', 'double', is_const=False)
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor]
cls.add_constructor([param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('CombineMask',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv4Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv4Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('GetSubnetDirectedBroadcast',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Address const &', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function]
cls.add_method('IsLocalMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('IsSubnetDirectedBroadcast',
'bool',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
return
def register_Ns3Ipv4Mask_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor]
cls.add_constructor([param('uint32_t', 'mask')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor]
cls.add_constructor([param('char const *', 'mask')])
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function]
cls.add_method('GetInverse',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint16_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Mask', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'mask')])
return
def register_Ns3Ipv6Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor]
cls.add_constructor([param('uint8_t *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function]
cls.add_method('CombinePrefix',
'ns3::Ipv6Address',
[param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv6Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv6Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function]
cls.add_method('GetAllHostsMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function]
cls.add_method('GetAllNodesMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function]
cls.add_method('GetAllRoutersMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function]
cls.add_method('GetIpv4MappedAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function]
cls.add_method('IsAllHostsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function]
cls.add_method('IsAllNodesMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function]
cls.add_method('IsAllRoutersMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function]
cls.add_method('IsAny',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Address const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function]
cls.add_method('IsIpv4MappedAddress',
'bool',
[])
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function]
cls.add_method('IsLinkLocal',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function]
cls.add_method('IsLinkLocalMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function]
cls.add_method('IsSolicitedMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('MakeIpv4MappedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv4Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function]
cls.add_method('MakeSolicitedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv6Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function]
cls.add_method('Set',
'void',
[param('uint8_t *', 'address')])
return
def register_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_Ns3MacLowBlockAckEventListener_methods(root_module, cls):
## mac-low.h (module 'wifi'): ns3::MacLowBlockAckEventListener::MacLowBlockAckEventListener(ns3::MacLowBlockAckEventListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLowBlockAckEventListener const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLowBlockAckEventListener::MacLowBlockAckEventListener() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): void ns3::MacLowBlockAckEventListener::BlockAckInactivityTimeout(ns3::Mac48Address originator, uint8_t tid) [member function]
cls.add_method('BlockAckInactivityTimeout',
'void',
[param('ns3::Mac48Address', 'originator'), param('uint8_t', 'tid')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3MacLowDcfListener_methods(root_module, cls):
## mac-low.h (module 'wifi'): ns3::MacLowDcfListener::MacLowDcfListener(ns3::MacLowDcfListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLowDcfListener const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLowDcfListener::MacLowDcfListener() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::AckTimeoutReset() [member function]
cls.add_method('AckTimeoutReset',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::AckTimeoutStart(ns3::Time duration) [member function]
cls.add_method('AckTimeoutStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::CtsTimeoutReset() [member function]
cls.add_method('CtsTimeoutReset',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::CtsTimeoutStart(ns3::Time duration) [member function]
cls.add_method('CtsTimeoutStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::NavReset(ns3::Time duration) [member function]
cls.add_method('NavReset',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::NavStart(ns3::Time duration) [member function]
cls.add_method('NavStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3MacLowTransmissionListener_methods(root_module, cls):
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionListener::MacLowTransmissionListener(ns3::MacLowTransmissionListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLowTransmissionListener const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionListener::MacLowTransmissionListener() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::Cancel() [member function]
cls.add_method('Cancel',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::GotAck(double snr, ns3::WifiMode txMode) [member function]
cls.add_method('GotAck',
'void',
[param('double', 'snr'), param('ns3::WifiMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::GotBlockAck(ns3::CtrlBAckResponseHeader const * blockAck, ns3::Mac48Address source) [member function]
cls.add_method('GotBlockAck',
'void',
[param('ns3::CtrlBAckResponseHeader const *', 'blockAck'), param('ns3::Mac48Address', 'source')],
is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::GotCts(double snr, ns3::WifiMode txMode) [member function]
cls.add_method('GotCts',
'void',
[param('double', 'snr'), param('ns3::WifiMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::MissedAck() [member function]
cls.add_method('MissedAck',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::MissedBlockAck() [member function]
cls.add_method('MissedBlockAck',
'void',
[],
is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::MissedCts() [member function]
cls.add_method('MissedCts',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::StartNext() [member function]
cls.add_method('StartNext',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3MacLowTransmissionParameters_methods(root_module, cls):
cls.add_output_stream_operator()
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionParameters::MacLowTransmissionParameters(ns3::MacLowTransmissionParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLowTransmissionParameters const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionParameters::MacLowTransmissionParameters() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::DisableAck() [member function]
cls.add_method('DisableAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::DisableNextData() [member function]
cls.add_method('DisableNextData',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::DisableOverrideDurationId() [member function]
cls.add_method('DisableOverrideDurationId',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::DisableRts() [member function]
cls.add_method('DisableRts',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableAck() [member function]
cls.add_method('EnableAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableBasicBlockAck() [member function]
cls.add_method('EnableBasicBlockAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableCompressedBlockAck() [member function]
cls.add_method('EnableCompressedBlockAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableFastAck() [member function]
cls.add_method('EnableFastAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableMultiTidBlockAck() [member function]
cls.add_method('EnableMultiTidBlockAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableNextData(uint32_t size) [member function]
cls.add_method('EnableNextData',
'void',
[param('uint32_t', 'size')])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableOverrideDurationId(ns3::Time durationId) [member function]
cls.add_method('EnableOverrideDurationId',
'void',
[param('ns3::Time', 'durationId')])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableRts() [member function]
cls.add_method('EnableRts',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableSuperFastAck() [member function]
cls.add_method('EnableSuperFastAck',
'void',
[])
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLowTransmissionParameters::GetDurationId() const [member function]
cls.add_method('GetDurationId',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): uint32_t ns3::MacLowTransmissionParameters::GetNextPacketSize() const [member function]
cls.add_method('GetNextPacketSize',
'uint32_t',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::HasDurationId() const [member function]
cls.add_method('HasDurationId',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::HasNextPacket() const [member function]
cls.add_method('HasNextPacket',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustSendRts() const [member function]
cls.add_method('MustSendRts',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitAck() const [member function]
cls.add_method('MustWaitAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitBasicBlockAck() const [member function]
cls.add_method('MustWaitBasicBlockAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitCompressedBlockAck() const [member function]
cls.add_method('MustWaitCompressedBlockAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitFastAck() const [member function]
cls.add_method('MustWaitFastAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitMultiTidBlockAck() const [member function]
cls.add_method('MustWaitMultiTidBlockAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitNormalAck() const [member function]
cls.add_method('MustWaitNormalAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitSuperFastAck() const [member function]
cls.add_method('MustWaitSuperFastAck',
'bool',
[],
is_const=True)
return
def register_Ns3MacRxMiddle_methods(root_module, cls):
## mac-rx-middle.h (module 'wifi'): ns3::MacRxMiddle::MacRxMiddle(ns3::MacRxMiddle const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacRxMiddle const &', 'arg0')])
## mac-rx-middle.h (module 'wifi'): ns3::MacRxMiddle::MacRxMiddle() [constructor]
cls.add_constructor([])
## mac-rx-middle.h (module 'wifi'): void ns3::MacRxMiddle::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')])
## mac-rx-middle.h (module 'wifi'): void ns3::MacRxMiddle::SetForwardCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::WifiMacHeader const*, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetForwardCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::WifiMacHeader const *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
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 & attribute) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')],
is_const=True)
## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function]
cls.add_method('ConstructSelf',
'void',
[param('ns3::AttributeConstructionList const &', 'attributes')],
visibility='protected')
## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function]
cls.add_method('NotifyConstructionCompleted',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectDeleter_methods(root_module, cls):
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor]
cls.add_constructor([])
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')])
## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Object *', 'object')],
is_static=True)
return
def register_Ns3ObjectFactory_methods(root_module, cls):
cls.add_output_stream_operator()
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor]
cls.add_constructor([param('std::string', 'typeId')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('ns3::TypeId', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('char const *', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('std::string', 'tid')])
return
def register_Ns3OriginatorBlockAckAgreement_methods(root_module, cls):
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement::OriginatorBlockAckAgreement(ns3::OriginatorBlockAckAgreement const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OriginatorBlockAckAgreement const &', 'arg0')])
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement::OriginatorBlockAckAgreement() [constructor]
cls.add_constructor([])
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement::OriginatorBlockAckAgreement(ns3::Mac48Address recipient, uint8_t tid) [constructor]
cls.add_constructor([param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')])
## originator-block-ack-agreement.h (module 'wifi'): void ns3::OriginatorBlockAckAgreement::CompleteExchange() [member function]
cls.add_method('CompleteExchange',
'void',
[])
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsBlockAckRequestNeeded() const [member function]
cls.add_method('IsBlockAckRequestNeeded',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsEstablished() const [member function]
cls.add_method('IsEstablished',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsInactive() const [member function]
cls.add_method('IsInactive',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsPending() const [member function]
cls.add_method('IsPending',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsUnsuccessful() const [member function]
cls.add_method('IsUnsuccessful',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): void ns3::OriginatorBlockAckAgreement::NotifyMpduTransmission(uint16_t nextSeqNumber) [member function]
cls.add_method('NotifyMpduTransmission',
'void',
[param('uint16_t', 'nextSeqNumber')])
## originator-block-ack-agreement.h (module 'wifi'): void ns3::OriginatorBlockAckAgreement::SetState(ns3::OriginatorBlockAckAgreement::State state) [member function]
cls.add_method('SetState',
'void',
[param('ns3::OriginatorBlockAckAgreement::State', 'state')])
return
def register_Ns3PacketMetadata_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor]
cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[param('ns3::Buffer', 'buffer')],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function]
cls.add_method('CreateFragment',
'ns3::PacketMetadata',
[param('uint32_t', 'start'), param('uint32_t', 'end')],
is_const=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function]
cls.add_method('Enable',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('RemoveTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3PacketMetadataItem_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor]
cls.add_constructor([])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable]
cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable]
cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable]
cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable]
cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable]
cls.add_instance_attribute('isFragment', 'bool', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor]
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketMetadata::Item',
[])
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3PacketTagListTagData_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable]
cls.add_instance_attribute('count', 'uint32_t', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable]
cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable]
cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PcapFile_methods(root_module, cls):
## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor]
cls.add_constructor([])
## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT) [member function]
cls.add_method('Diff',
'bool',
[param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint32_t &', 'sec'), param('uint32_t &', 'usec'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT')],
is_static=True)
## pcap-file.h (module 'network'): bool ns3::PcapFile::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## pcap-file.h (module 'network'): bool ns3::PcapFile::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetDataLinkType() [member function]
cls.add_method('GetDataLinkType',
'uint32_t',
[])
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetMagic() [member function]
cls.add_method('GetMagic',
'uint32_t',
[])
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSigFigs() [member function]
cls.add_method('GetSigFigs',
'uint32_t',
[])
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSnapLen() [member function]
cls.add_method('GetSnapLen',
'uint32_t',
[])
## pcap-file.h (module 'network'): bool ns3::PcapFile::GetSwapMode() [member function]
cls.add_method('GetSwapMode',
'bool',
[])
## pcap-file.h (module 'network'): int32_t ns3::PcapFile::GetTimeZoneOffset() [member function]
cls.add_method('GetTimeZoneOffset',
'int32_t',
[])
## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMajor() [member function]
cls.add_method('GetVersionMajor',
'uint16_t',
[])
## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMinor() [member function]
cls.add_method('GetVersionMinor',
'uint16_t',
[])
## pcap-file.h (module 'network'): void ns3::PcapFile::Init(uint32_t dataLinkType, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT, int32_t timeZoneCorrection=ns3::PcapFile::ZONE_DEFAULT, bool swapMode=false) [member function]
cls.add_method('Init',
'void',
[param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT'), param('int32_t', 'timeZoneCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT'), param('bool', 'swapMode', default_value='false')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Read(uint8_t * const data, uint32_t maxBytes, uint32_t & tsSec, uint32_t & tsUsec, uint32_t & inclLen, uint32_t & origLen, uint32_t & readLen) [member function]
cls.add_method('Read',
'void',
[param('uint8_t * const', 'data'), param('uint32_t', 'maxBytes'), param('uint32_t &', 'tsSec'), param('uint32_t &', 'tsUsec'), param('uint32_t &', 'inclLen'), param('uint32_t &', 'origLen'), param('uint32_t &', 'readLen')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, uint8_t const * const data, uint32_t totalLen) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('uint8_t const * const', 'data'), param('uint32_t', 'totalLen')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Header & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file.h (module 'network'): ns3::PcapFile::SNAPLEN_DEFAULT [variable]
cls.add_static_attribute('SNAPLEN_DEFAULT', 'uint32_t const', is_const=True)
## pcap-file.h (module 'network'): ns3::PcapFile::ZONE_DEFAULT [variable]
cls.add_static_attribute('ZONE_DEFAULT', 'int32_t const', is_const=True)
return
def register_Ns3PcapHelper_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper(ns3::PcapHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PcapHelper const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): ns3::Ptr<ns3::PcapFileWrapper> ns3::PcapHelper::CreateFile(std::string filename, std::_Ios_Openmode filemode, uint32_t dataLinkType, uint32_t snapLen=65535, int32_t tzCorrection=0) [member function]
cls.add_method('CreateFile',
'ns3::Ptr< ns3::PcapFileWrapper >',
[param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode'), param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='65535'), param('int32_t', 'tzCorrection', default_value='0')])
## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromDevice',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')])
## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromInterfacePair',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')])
return
def register_Ns3PcapHelperForDevice_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function]
cls.add_method('EnablePcapAll',
'void',
[param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function]
cls.add_method('EnablePcapInternal',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3PropagationCache__Ns3JakesProcess_methods(root_module, cls):
## propagation-cache.h (module 'propagation'): ns3::PropagationCache<ns3::JakesProcess>::PropagationCache(ns3::PropagationCache<ns3::JakesProcess> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PropagationCache< ns3::JakesProcess > const &', 'arg0')])
## propagation-cache.h (module 'propagation'): ns3::PropagationCache<ns3::JakesProcess>::PropagationCache() [constructor]
cls.add_constructor([])
## propagation-cache.h (module 'propagation'): ns3::Ptr<ns3::JakesProcess> ns3::PropagationCache<ns3::JakesProcess>::GetPathData(ns3::Ptr<ns3::MobilityModel const> a, ns3::Ptr<ns3::MobilityModel const> b, uint32_t modelUid) [member function]
cls.add_method('GetPathData',
'ns3::Ptr< ns3::JakesProcess >',
[param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b'), param('uint32_t', 'modelUid')])
return
def register_Ns3RandomVariable_methods(root_module, cls):
cls.add_output_stream_operator()
## random-variable.h (module 'core'): ns3::RandomVariable::RandomVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::RandomVariable::RandomVariable(ns3::RandomVariable const & o) [copy constructor]
cls.add_constructor([param('ns3::RandomVariable const &', 'o')])
## random-variable.h (module 'core'): uint32_t ns3::RandomVariable::GetInteger() const [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_const=True)
## random-variable.h (module 'core'): double ns3::RandomVariable::GetValue() const [member function]
cls.add_method('GetValue',
'double',
[],
is_const=True)
return
def register_Ns3RateInfo_methods(root_module, cls):
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::RateInfo() [constructor]
cls.add_constructor([])
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::RateInfo(ns3::RateInfo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RateInfo const &', 'arg0')])
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::adjustedRetryCount [variable]
cls.add_instance_attribute('adjustedRetryCount', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::attemptHist [variable]
cls.add_instance_attribute('attemptHist', 'uint64_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::ewmaProb [variable]
cls.add_instance_attribute('ewmaProb', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::numRateAttempt [variable]
cls.add_instance_attribute('numRateAttempt', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::numRateSuccess [variable]
cls.add_instance_attribute('numRateSuccess', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::perfectTxTime [variable]
cls.add_instance_attribute('perfectTxTime', 'ns3::Time', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::prevNumRateAttempt [variable]
cls.add_instance_attribute('prevNumRateAttempt', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::prevNumRateSuccess [variable]
cls.add_instance_attribute('prevNumRateSuccess', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::prob [variable]
cls.add_instance_attribute('prob', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::retryCount [variable]
cls.add_instance_attribute('retryCount', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::successHist [variable]
cls.add_instance_attribute('successHist', 'uint64_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::throughput [variable]
cls.add_instance_attribute('throughput', 'uint32_t', is_const=False)
return
def register_Ns3SeedManager_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::SeedManager::SeedManager() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::SeedManager::SeedManager(ns3::SeedManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SeedManager const &', 'arg0')])
## random-variable.h (module 'core'): static bool ns3::SeedManager::CheckSeed(uint32_t seed) [member function]
cls.add_method('CheckSeed',
'bool',
[param('uint32_t', 'seed')],
is_static=True)
## random-variable.h (module 'core'): static uint32_t ns3::SeedManager::GetRun() [member function]
cls.add_method('GetRun',
'uint32_t',
[],
is_static=True)
## random-variable.h (module 'core'): static uint32_t ns3::SeedManager::GetSeed() [member function]
cls.add_method('GetSeed',
'uint32_t',
[],
is_static=True)
## random-variable.h (module 'core'): static void ns3::SeedManager::SetRun(uint32_t run) [member function]
cls.add_method('SetRun',
'void',
[param('uint32_t', 'run')],
is_static=True)
## random-variable.h (module 'core'): static void ns3::SeedManager::SetSeed(uint32_t seed) [member function]
cls.add_method('SetSeed',
'void',
[param('uint32_t', 'seed')],
is_static=True)
return
def register_Ns3SequentialVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::SequentialVariable::SequentialVariable(ns3::SequentialVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SequentialVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::SequentialVariable::SequentialVariable(double f, double l, double i=1, uint32_t c=1) [constructor]
cls.add_constructor([param('double', 'f'), param('double', 'l'), param('double', 'i', default_value='1'), param('uint32_t', 'c', default_value='1')])
## random-variable.h (module 'core'): ns3::SequentialVariable::SequentialVariable(double f, double l, ns3::RandomVariable const & i, uint32_t c=1) [constructor]
cls.add_constructor([param('double', 'f'), param('double', 'l'), param('ns3::RandomVariable const &', 'i'), param('uint32_t', 'c', default_value='1')])
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function]
cls.add_method('SetImplementation',
'void',
[param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'time')],
is_static=True)
return
def register_Ns3StatusCode_methods(root_module, cls):
cls.add_output_stream_operator()
## status-code.h (module 'wifi'): ns3::StatusCode::StatusCode(ns3::StatusCode const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StatusCode const &', 'arg0')])
## status-code.h (module 'wifi'): ns3::StatusCode::StatusCode() [constructor]
cls.add_constructor([])
## status-code.h (module 'wifi'): ns3::Buffer::Iterator ns3::StatusCode::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')])
## status-code.h (module 'wifi'): uint32_t ns3::StatusCode::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## status-code.h (module 'wifi'): bool ns3::StatusCode::IsSuccess() const [member function]
cls.add_method('IsSuccess',
'bool',
[],
is_const=True)
## status-code.h (module 'wifi'): ns3::Buffer::Iterator ns3::StatusCode::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## status-code.h (module 'wifi'): void ns3::StatusCode::SetFailure() [member function]
cls.add_method('SetFailure',
'void',
[])
## status-code.h (module 'wifi'): void ns3::StatusCode::SetSuccess() [member function]
cls.add_method('SetSuccess',
'void',
[])
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_Ns3TriangularVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::TriangularVariable::TriangularVariable(ns3::TriangularVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TriangularVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::TriangularVariable::TriangularVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::TriangularVariable::TriangularVariable(double s, double l, double mean) [constructor]
cls.add_constructor([param('double', 's'), param('double', 'l'), param('double', 'mean')])
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function]
cls.add_method('GetParent',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint32_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint32_t',
[],
is_static=True)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function]
cls.add_method('GetUid',
'uint16_t',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function]
cls.add_method('HasConstructor',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function]
cls.add_method('HasParent',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function]
cls.add_method('HideFromDocumentation',
'ns3::TypeId',
[])
## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function]
cls.add_method('IsChildOf',
'bool',
[param('ns3::TypeId', 'other')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function]
cls.add_method('LookupAttributeByName',
'bool',
[param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function]
cls.add_method('MustHideFromDocumentation',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function]
cls.add_method('SetGroupName',
'ns3::TypeId',
[param('std::string', 'groupName')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[param('ns3::TypeId', 'tid')])
## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'tid')])
return
def register_Ns3TypeIdAttributeInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable]
cls.add_instance_attribute('flags', 'uint32_t', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable]
cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable]
cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
return
def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
return
def register_Ns3UniformVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::UniformVariable::UniformVariable(ns3::UniformVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UniformVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::UniformVariable::UniformVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::UniformVariable::UniformVariable(double s, double l) [constructor]
cls.add_constructor([param('double', 's'), param('double', 'l')])
## random-variable.h (module 'core'): uint32_t ns3::UniformVariable::GetInteger(uint32_t s, uint32_t l) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 's'), param('uint32_t', 'l')])
## random-variable.h (module 'core'): double ns3::UniformVariable::GetValue() const [member function]
cls.add_method('GetValue',
'double',
[],
is_const=True)
## random-variable.h (module 'core'): double ns3::UniformVariable::GetValue(double s, double l) [member function]
cls.add_method('GetValue',
'double',
[param('double', 's'), param('double', 'l')])
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_Ns3WeibullVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable(ns3::WeibullVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WeibullVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable(double m) [constructor]
cls.add_constructor([param('double', 'm')])
## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable(double m, double s) [constructor]
cls.add_constructor([param('double', 'm'), param('double', 's')])
## random-variable.h (module 'core'): ns3::WeibullVariable::WeibullVariable(double m, double s, double b) [constructor]
cls.add_constructor([param('double', 'm'), param('double', 's'), param('double', 'b')])
return
def register_Ns3WifiHelper_methods(root_module, cls):
## wifi-helper.h (module 'wifi'): ns3::WifiHelper::WifiHelper(ns3::WifiHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiHelper const &', 'arg0')])
## wifi-helper.h (module 'wifi'): ns3::WifiHelper::WifiHelper() [constructor]
cls.add_constructor([])
## wifi-helper.h (module 'wifi'): static ns3::WifiHelper ns3::WifiHelper::Default() [member function]
cls.add_method('Default',
'ns3::WifiHelper',
[],
is_static=True)
## wifi-helper.h (module 'wifi'): static void ns3::WifiHelper::EnableLogComponents() [member function]
cls.add_method('EnableLogComponents',
'void',
[],
is_static=True)
## wifi-helper.h (module 'wifi'): ns3::NetDeviceContainer ns3::WifiHelper::Install(ns3::WifiPhyHelper const & phy, ns3::WifiMacHelper const & mac, ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::WifiPhyHelper const &', 'phy'), param('ns3::WifiMacHelper const &', 'mac'), param('ns3::NodeContainer', 'c')],
is_const=True)
## wifi-helper.h (module 'wifi'): ns3::NetDeviceContainer ns3::WifiHelper::Install(ns3::WifiPhyHelper const & phy, ns3::WifiMacHelper const & mac, ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::WifiPhyHelper const &', 'phy'), param('ns3::WifiMacHelper const &', 'mac'), param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## wifi-helper.h (module 'wifi'): ns3::NetDeviceContainer ns3::WifiHelper::Install(ns3::WifiPhyHelper const & phy, ns3::WifiMacHelper const & mac, std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::WifiPhyHelper const &', 'phy'), param('ns3::WifiMacHelper const &', 'mac'), param('std::string', 'nodeName')],
is_const=True)
## wifi-helper.h (module 'wifi'): void ns3::WifiHelper::SetRemoteStationManager(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('SetRemoteStationManager',
'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()')])
## wifi-helper.h (module 'wifi'): void ns3::WifiHelper::SetStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('SetStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')])
return
def register_Ns3WifiMacHelper_methods(root_module, cls):
## wifi-helper.h (module 'wifi'): ns3::WifiMacHelper::WifiMacHelper() [constructor]
cls.add_constructor([])
## wifi-helper.h (module 'wifi'): ns3::WifiMacHelper::WifiMacHelper(ns3::WifiMacHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMacHelper const &', 'arg0')])
## wifi-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiMac> ns3::WifiMacHelper::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiMac >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3WifiMode_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode(ns3::WifiMode const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMode const &', 'arg0')])
## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode() [constructor]
cls.add_constructor([])
## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode(std::string name) [constructor]
cls.add_constructor([param('std::string', 'name')])
## wifi-mode.h (module 'wifi'): uint32_t ns3::WifiMode::GetBandwidth() const [member function]
cls.add_method('GetBandwidth',
'uint32_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): ns3::WifiCodeRate ns3::WifiMode::GetCodeRate() const [member function]
cls.add_method('GetCodeRate',
'ns3::WifiCodeRate',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint8_t ns3::WifiMode::GetConstellationSize() const [member function]
cls.add_method('GetConstellationSize',
'uint8_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint64_t ns3::WifiMode::GetDataRate() const [member function]
cls.add_method('GetDataRate',
'uint64_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): ns3::WifiModulationClass ns3::WifiMode::GetModulationClass() const [member function]
cls.add_method('GetModulationClass',
'ns3::WifiModulationClass',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint64_t ns3::WifiMode::GetPhyRate() const [member function]
cls.add_method('GetPhyRate',
'uint64_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint32_t ns3::WifiMode::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): std::string ns3::WifiMode::GetUniqueName() const [member function]
cls.add_method('GetUniqueName',
'std::string',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): bool ns3::WifiMode::IsMandatory() const [member function]
cls.add_method('IsMandatory',
'bool',
[],
is_const=True)
return
def register_Ns3WifiModeFactory_methods(root_module, cls):
## wifi-mode.h (module 'wifi'): ns3::WifiModeFactory::WifiModeFactory(ns3::WifiModeFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiModeFactory const &', 'arg0')])
## wifi-mode.h (module 'wifi'): static ns3::WifiMode ns3::WifiModeFactory::CreateWifiMode(std::string uniqueName, ns3::WifiModulationClass modClass, bool isMandatory, uint32_t bandwidth, uint32_t dataRate, ns3::WifiCodeRate codingRate, uint8_t constellationSize) [member function]
cls.add_method('CreateWifiMode',
'ns3::WifiMode',
[param('std::string', 'uniqueName'), param('ns3::WifiModulationClass', 'modClass'), param('bool', 'isMandatory'), param('uint32_t', 'bandwidth'), param('uint32_t', 'dataRate'), param('ns3::WifiCodeRate', 'codingRate'), param('uint8_t', 'constellationSize')],
is_static=True)
return
def register_Ns3WifiPhyHelper_methods(root_module, cls):
## wifi-helper.h (module 'wifi'): ns3::WifiPhyHelper::WifiPhyHelper() [constructor]
cls.add_constructor([])
## wifi-helper.h (module 'wifi'): ns3::WifiPhyHelper::WifiPhyHelper(ns3::WifiPhyHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiPhyHelper const &', 'arg0')])
## wifi-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiPhy> ns3::WifiPhyHelper::Create(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::WifiNetDevice> device) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiPhy >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::WifiNetDevice >', 'device')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3WifiPhyListener_methods(root_module, cls):
## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener::WifiPhyListener() [constructor]
cls.add_constructor([])
## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener::WifiPhyListener(ns3::WifiPhyListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiPhyListener const &', 'arg0')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyMaybeCcaBusyStart(ns3::Time duration) [member function]
cls.add_method('NotifyMaybeCcaBusyStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxEndError() [member function]
cls.add_method('NotifyRxEndError',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxEndOk() [member function]
cls.add_method('NotifyRxEndOk',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxStart(ns3::Time duration) [member function]
cls.add_method('NotifyRxStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifySwitchingStart(ns3::Time duration) [member function]
cls.add_method('NotifySwitchingStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyTxStart(ns3::Time duration) [member function]
cls.add_method('NotifyTxStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3WifiRemoteStation_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::WifiRemoteStation() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::WifiRemoteStation(ns3::WifiRemoteStation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStation const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_slrc [variable]
cls.add_instance_attribute('m_slrc', 'uint32_t', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_ssrc [variable]
cls.add_instance_attribute('m_ssrc', 'uint32_t', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_state [variable]
cls.add_instance_attribute('m_state', 'ns3::WifiRemoteStationState *', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_tid [variable]
cls.add_instance_attribute('m_tid', 'uint8_t', is_const=False)
return
def register_Ns3WifiRemoteStationInfo_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo::WifiRemoteStationInfo(ns3::WifiRemoteStationInfo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStationInfo const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo::WifiRemoteStationInfo() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): double ns3::WifiRemoteStationInfo::GetFrameErrorRate() const [member function]
cls.add_method('GetFrameErrorRate',
'double',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationInfo::NotifyTxFailed() [member function]
cls.add_method('NotifyTxFailed',
'void',
[])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationInfo::NotifyTxSuccess(uint32_t retryCounter) [member function]
cls.add_method('NotifyTxSuccess',
'void',
[param('uint32_t', 'retryCounter')])
return
def register_Ns3WifiRemoteStationState_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::WifiRemoteStationState() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::WifiRemoteStationState(ns3::WifiRemoteStationState const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStationState const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::m_address [variable]
cls.add_instance_attribute('m_address', 'ns3::Mac48Address', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::m_info [variable]
cls.add_instance_attribute('m_info', 'ns3::WifiRemoteStationInfo', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::m_operationalRateSet [variable]
cls.add_instance_attribute('m_operationalRateSet', 'ns3::WifiModeList', is_const=False)
return
def register_Ns3YansWifiChannelHelper_methods(root_module, cls):
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiChannelHelper::YansWifiChannelHelper(ns3::YansWifiChannelHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::YansWifiChannelHelper const &', 'arg0')])
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiChannelHelper::YansWifiChannelHelper() [constructor]
cls.add_constructor([])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiChannelHelper::AddPropagationLoss(std::string name, 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('AddPropagationLoss',
'void',
[param('std::string', 'name'), 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()')])
## yans-wifi-helper.h (module 'wifi'): ns3::Ptr<ns3::YansWifiChannel> ns3::YansWifiChannelHelper::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::YansWifiChannel >',
[],
is_const=True)
## yans-wifi-helper.h (module 'wifi'): static ns3::YansWifiChannelHelper ns3::YansWifiChannelHelper::Default() [member function]
cls.add_method('Default',
'ns3::YansWifiChannelHelper',
[],
is_static=True)
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiChannelHelper::SetPropagationDelay(std::string name, 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('SetPropagationDelay',
'void',
[param('std::string', 'name'), 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_Ns3YansWifiPhyHelper_methods(root_module, cls):
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiPhyHelper::YansWifiPhyHelper(ns3::YansWifiPhyHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::YansWifiPhyHelper const &', 'arg0')])
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiPhyHelper::YansWifiPhyHelper() [constructor]
cls.add_constructor([])
## yans-wifi-helper.h (module 'wifi'): static ns3::YansWifiPhyHelper ns3::YansWifiPhyHelper::Default() [member function]
cls.add_method('Default',
'ns3::YansWifiPhyHelper',
[],
is_static=True)
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::Set(std::string name, ns3::AttributeValue const & v) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::SetChannel(ns3::Ptr<ns3::YansWifiChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::YansWifiChannel >', 'channel')])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::SetChannel(std::string channelName) [member function]
cls.add_method('SetChannel',
'void',
[param('std::string', 'channelName')])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::SetErrorRateModel(std::string name, 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('SetErrorRateModel',
'void',
[param('std::string', 'name'), 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()')])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::SetPcapDataLinkType(ns3::YansWifiPhyHelper::SupportedPcapDataLinkTypes dlt) [member function]
cls.add_method('SetPcapDataLinkType',
'void',
[param('ns3::YansWifiPhyHelper::SupportedPcapDataLinkTypes', 'dlt')])
## yans-wifi-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiPhy> ns3::YansWifiPhyHelper::Create(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::WifiNetDevice> device) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiPhy >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::WifiNetDevice >', 'device')],
is_const=True, visibility='private', is_virtual=True)
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function]
cls.add_method('EnableAsciiInternal',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')],
visibility='private', is_virtual=True)
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function]
cls.add_method('EnablePcapInternal',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')],
visibility='private', is_virtual=True)
return
def register_Ns3ZetaVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::ZetaVariable::ZetaVariable(ns3::ZetaVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ZetaVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::ZetaVariable::ZetaVariable(double alpha) [constructor]
cls.add_constructor([param('double', 'alpha')])
## random-variable.h (module 'core'): ns3::ZetaVariable::ZetaVariable() [constructor]
cls.add_constructor([])
return
def register_Ns3ZipfVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::ZipfVariable::ZipfVariable(ns3::ZipfVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ZipfVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::ZipfVariable::ZipfVariable(long int N, double alpha) [constructor]
cls.add_constructor([param('long int', 'N'), param('double', 'alpha')])
## random-variable.h (module 'core'): ns3::ZipfVariable::ZipfVariable() [constructor]
cls.add_constructor([])
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_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right'))
cls.add_binary_comparison_operator('!=')
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor]
cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t', 'v')],
is_static=True)
## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function]
cls.add_method('MulByInvert',
'void',
[param('ns3::int64x64_t const &', 'o')])
return
def register_Ns3Chunk_methods(root_module, cls):
## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor]
cls.add_constructor([])
## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Chunk const &', 'arg0')])
## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3ConstantVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::ConstantVariable::ConstantVariable(ns3::ConstantVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ConstantVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::ConstantVariable::ConstantVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::ConstantVariable::ConstantVariable(double c) [constructor]
cls.add_constructor([param('double', 'c')])
## random-variable.h (module 'core'): void ns3::ConstantVariable::SetConstant(double c) [member function]
cls.add_method('SetConstant',
'void',
[param('double', 'c')])
return
def register_Ns3DeterministicVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::DeterministicVariable::DeterministicVariable(ns3::DeterministicVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeterministicVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::DeterministicVariable::DeterministicVariable(double * d, uint32_t c) [constructor]
cls.add_constructor([param('double *', 'd'), param('uint32_t', 'c')])
return
def register_Ns3EmpiricalVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::EmpiricalVariable::EmpiricalVariable(ns3::EmpiricalVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmpiricalVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::EmpiricalVariable::EmpiricalVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): void ns3::EmpiricalVariable::CDF(double v, double c) [member function]
cls.add_method('CDF',
'void',
[param('double', 'v'), param('double', 'c')])
return
def register_Ns3ErlangVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::ErlangVariable::ErlangVariable(ns3::ErlangVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ErlangVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::ErlangVariable::ErlangVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::ErlangVariable::ErlangVariable(unsigned int k, double lambda) [constructor]
cls.add_constructor([param('unsigned int', 'k'), param('double', 'lambda')])
## random-variable.h (module 'core'): double ns3::ErlangVariable::GetValue() const [member function]
cls.add_method('GetValue',
'double',
[],
is_const=True)
## random-variable.h (module 'core'): double ns3::ErlangVariable::GetValue(unsigned int k, double lambda) const [member function]
cls.add_method('GetValue',
'double',
[param('unsigned int', 'k'), param('double', 'lambda')],
is_const=True)
return
def register_Ns3ExponentialVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::ExponentialVariable::ExponentialVariable(ns3::ExponentialVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ExponentialVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::ExponentialVariable::ExponentialVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::ExponentialVariable::ExponentialVariable(double m) [constructor]
cls.add_constructor([param('double', 'm')])
## random-variable.h (module 'core'): ns3::ExponentialVariable::ExponentialVariable(double m, double b) [constructor]
cls.add_constructor([param('double', 'm'), param('double', 'b')])
return
def register_Ns3GammaVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::GammaVariable::GammaVariable(ns3::GammaVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::GammaVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::GammaVariable::GammaVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::GammaVariable::GammaVariable(double alpha, double beta) [constructor]
cls.add_constructor([param('double', 'alpha'), param('double', 'beta')])
## random-variable.h (module 'core'): double ns3::GammaVariable::GetValue() const [member function]
cls.add_method('GetValue',
'double',
[],
is_const=True)
## random-variable.h (module 'core'): double ns3::GammaVariable::GetValue(double alpha, double beta) const [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha'), param('double', 'beta')],
is_const=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_Ns3IntEmpiricalVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::IntEmpiricalVariable::IntEmpiricalVariable(ns3::IntEmpiricalVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntEmpiricalVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::IntEmpiricalVariable::IntEmpiricalVariable() [constructor]
cls.add_constructor([])
return
def register_Ns3LogNormalVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::LogNormalVariable::LogNormalVariable(ns3::LogNormalVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LogNormalVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::LogNormalVariable::LogNormalVariable(double mu, double sigma) [constructor]
cls.add_constructor([param('double', 'mu'), param('double', 'sigma')])
return
def register_Ns3MgtAddBaRequestHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaRequestHeader::MgtAddBaRequestHeader(ns3::MgtAddBaRequestHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtAddBaRequestHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaRequestHeader::MgtAddBaRequestHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAddBaRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaRequestHeader::GetBufferSize() const [member function]
cls.add_method('GetBufferSize',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtAddBaRequestHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAddBaRequestHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaRequestHeader::GetStartingSequence() const [member function]
cls.add_method('GetStartingSequence',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint8_t ns3::MgtAddBaRequestHeader::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaRequestHeader::GetTimeout() const [member function]
cls.add_method('GetTimeout',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtAddBaRequestHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtAddBaRequestHeader::IsAmsduSupported() const [member function]
cls.add_method('IsAmsduSupported',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtAddBaRequestHeader::IsImmediateBlockAck() const [member function]
cls.add_method('IsImmediateBlockAck',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetAmsduSupport(bool supported) [member function]
cls.add_method('SetAmsduSupport',
'void',
[param('bool', 'supported')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetBufferSize(uint16_t size) [member function]
cls.add_method('SetBufferSize',
'void',
[param('uint16_t', 'size')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetDelayedBlockAck() [member function]
cls.add_method('SetDelayedBlockAck',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetImmediateBlockAck() [member function]
cls.add_method('SetImmediateBlockAck',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetStartingSequence(uint16_t seq) [member function]
cls.add_method('SetStartingSequence',
'void',
[param('uint16_t', 'seq')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetTid(uint8_t tid) [member function]
cls.add_method('SetTid',
'void',
[param('uint8_t', 'tid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetTimeout(uint16_t timeout) [member function]
cls.add_method('SetTimeout',
'void',
[param('uint16_t', 'timeout')])
return
def register_Ns3MgtAddBaResponseHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaResponseHeader::MgtAddBaResponseHeader(ns3::MgtAddBaResponseHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtAddBaResponseHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaResponseHeader::MgtAddBaResponseHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAddBaResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaResponseHeader::GetBufferSize() const [member function]
cls.add_method('GetBufferSize',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtAddBaResponseHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAddBaResponseHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::StatusCode ns3::MgtAddBaResponseHeader::GetStatusCode() const [member function]
cls.add_method('GetStatusCode',
'ns3::StatusCode',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint8_t ns3::MgtAddBaResponseHeader::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaResponseHeader::GetTimeout() const [member function]
cls.add_method('GetTimeout',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtAddBaResponseHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtAddBaResponseHeader::IsAmsduSupported() const [member function]
cls.add_method('IsAmsduSupported',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtAddBaResponseHeader::IsImmediateBlockAck() const [member function]
cls.add_method('IsImmediateBlockAck',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetAmsduSupport(bool supported) [member function]
cls.add_method('SetAmsduSupport',
'void',
[param('bool', 'supported')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetBufferSize(uint16_t size) [member function]
cls.add_method('SetBufferSize',
'void',
[param('uint16_t', 'size')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetDelayedBlockAck() [member function]
cls.add_method('SetDelayedBlockAck',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetImmediateBlockAck() [member function]
cls.add_method('SetImmediateBlockAck',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetStatusCode(ns3::StatusCode code) [member function]
cls.add_method('SetStatusCode',
'void',
[param('ns3::StatusCode', 'code')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetTid(uint8_t tid) [member function]
cls.add_method('SetTid',
'void',
[param('uint8_t', 'tid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetTimeout(uint16_t timeout) [member function]
cls.add_method('SetTimeout',
'void',
[param('uint16_t', 'timeout')])
return
def register_Ns3MgtAssocRequestHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtAssocRequestHeader::MgtAssocRequestHeader(ns3::MgtAssocRequestHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtAssocRequestHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtAssocRequestHeader::MgtAssocRequestHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAssocRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtAssocRequestHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAssocRequestHeader::GetListenInterval() const [member function]
cls.add_method('GetListenInterval',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAssocRequestHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::Ssid ns3::MgtAssocRequestHeader::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::SupportedRates ns3::MgtAssocRequestHeader::GetSupportedRates() const [member function]
cls.add_method('GetSupportedRates',
'ns3::SupportedRates',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtAssocRequestHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::SetListenInterval(uint16_t interval) [member function]
cls.add_method('SetListenInterval',
'void',
[param('uint16_t', 'interval')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::SetSupportedRates(ns3::SupportedRates rates) [member function]
cls.add_method('SetSupportedRates',
'void',
[param('ns3::SupportedRates', 'rates')])
return
def register_Ns3MgtAssocResponseHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtAssocResponseHeader::MgtAssocResponseHeader(ns3::MgtAssocResponseHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtAssocResponseHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtAssocResponseHeader::MgtAssocResponseHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAssocResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtAssocResponseHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAssocResponseHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::StatusCode ns3::MgtAssocResponseHeader::GetStatusCode() [member function]
cls.add_method('GetStatusCode',
'ns3::StatusCode',
[])
## mgt-headers.h (module 'wifi'): ns3::SupportedRates ns3::MgtAssocResponseHeader::GetSupportedRates() [member function]
cls.add_method('GetSupportedRates',
'ns3::SupportedRates',
[])
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtAssocResponseHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocResponseHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocResponseHeader::SetStatusCode(ns3::StatusCode code) [member function]
cls.add_method('SetStatusCode',
'void',
[param('ns3::StatusCode', 'code')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocResponseHeader::SetSupportedRates(ns3::SupportedRates rates) [member function]
cls.add_method('SetSupportedRates',
'void',
[param('ns3::SupportedRates', 'rates')])
return
def register_Ns3MgtDelBaHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtDelBaHeader::MgtDelBaHeader(ns3::MgtDelBaHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtDelBaHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtDelBaHeader::MgtDelBaHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtDelBaHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtDelBaHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtDelBaHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint8_t ns3::MgtDelBaHeader::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtDelBaHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtDelBaHeader::IsByOriginator() const [member function]
cls.add_method('IsByOriginator',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::SetByOriginator() [member function]
cls.add_method('SetByOriginator',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::SetByRecipient() [member function]
cls.add_method('SetByRecipient',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::SetTid(uint8_t arg0) [member function]
cls.add_method('SetTid',
'void',
[param('uint8_t', 'arg0')])
return
def register_Ns3MgtProbeRequestHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtProbeRequestHeader::MgtProbeRequestHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): ns3::MgtProbeRequestHeader::MgtProbeRequestHeader(ns3::MgtProbeRequestHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtProbeRequestHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtProbeRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtProbeRequestHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtProbeRequestHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::Ssid ns3::MgtProbeRequestHeader::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::SupportedRates ns3::MgtProbeRequestHeader::GetSupportedRates() const [member function]
cls.add_method('GetSupportedRates',
'ns3::SupportedRates',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtProbeRequestHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeRequestHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeRequestHeader::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeRequestHeader::SetSupportedRates(ns3::SupportedRates rates) [member function]
cls.add_method('SetSupportedRates',
'void',
[param('ns3::SupportedRates', 'rates')])
return
def register_Ns3MgtProbeResponseHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtProbeResponseHeader::MgtProbeResponseHeader(ns3::MgtProbeResponseHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtProbeResponseHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtProbeResponseHeader::MgtProbeResponseHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtProbeResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): uint64_t ns3::MgtProbeResponseHeader::GetBeaconIntervalUs() const [member function]
cls.add_method('GetBeaconIntervalUs',
'uint64_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtProbeResponseHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtProbeResponseHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::Ssid ns3::MgtProbeResponseHeader::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::SupportedRates ns3::MgtProbeResponseHeader::GetSupportedRates() const [member function]
cls.add_method('GetSupportedRates',
'ns3::SupportedRates',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint64_t ns3::MgtProbeResponseHeader::GetTimestamp() [member function]
cls.add_method('GetTimestamp',
'uint64_t',
[])
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtProbeResponseHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::SetBeaconIntervalUs(uint64_t us) [member function]
cls.add_method('SetBeaconIntervalUs',
'void',
[param('uint64_t', 'us')])
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::SetSupportedRates(ns3::SupportedRates rates) [member function]
cls.add_method('SetSupportedRates',
'void',
[param('ns3::SupportedRates', 'rates')])
return
def register_Ns3NormalVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::NormalVariable::NormalVariable(ns3::NormalVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NormalVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::NormalVariable::NormalVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::NormalVariable::NormalVariable(double m, double v) [constructor]
cls.add_constructor([param('double', 'm'), param('double', 'v')])
## random-variable.h (module 'core'): ns3::NormalVariable::NormalVariable(double m, double v, double b) [constructor]
cls.add_constructor([param('double', 'm'), param('double', 'v'), param('double', 'b')])
return
def register_Ns3NqosWifiMacHelper_methods(root_module, cls):
## nqos-wifi-mac-helper.h (module 'wifi'): ns3::NqosWifiMacHelper::NqosWifiMacHelper(ns3::NqosWifiMacHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NqosWifiMacHelper const &', 'arg0')])
## nqos-wifi-mac-helper.h (module 'wifi'): ns3::NqosWifiMacHelper::NqosWifiMacHelper() [constructor]
cls.add_constructor([])
## nqos-wifi-mac-helper.h (module 'wifi'): static ns3::NqosWifiMacHelper ns3::NqosWifiMacHelper::Default() [member function]
cls.add_method('Default',
'ns3::NqosWifiMacHelper',
[],
is_static=True)
## nqos-wifi-mac-helper.h (module 'wifi'): void ns3::NqosWifiMacHelper::SetType(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('SetType',
'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()')])
## nqos-wifi-mac-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiMac> ns3::NqosWifiMacHelper::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiMac >',
[],
is_const=True, visibility='private', 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::Start() [member function]
cls.add_method('Start',
'void',
[])
## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor]
cls.add_constructor([param('ns3::Object const &', 'o')],
visibility='protected')
## object.h (module 'core'): void ns3::Object::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectAggregateIterator_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')])
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor]
cls.add_constructor([])
## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function]
cls.add_method('Next',
'ns3::Ptr< ns3::Object const >',
[])
return
def register_Ns3ParetoVariable_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(ns3::ParetoVariable const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ParetoVariable const &', 'arg0')])
## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(double m) [constructor]
cls.add_constructor([param('double', 'm')])
## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(double m, double s) [constructor]
cls.add_constructor([param('double', 'm'), param('double', 's')])
## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(double m, double s, double b) [constructor]
cls.add_constructor([param('double', 'm'), param('double', 's'), param('double', 'b')])
## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(std::pair<double,double> params) [constructor]
cls.add_constructor([param('std::pair< double, double >', 'params')])
## random-variable.h (module 'core'): ns3::ParetoVariable::ParetoVariable(std::pair<double,double> params, double b) [constructor]
cls.add_constructor([param('std::pair< double, double >', 'params'), param('double', 'b')])
return
def register_Ns3PcapFileWrapper_methods(root_module, cls):
## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor]
cls.add_constructor([])
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function]
cls.add_method('Init',
'void',
[param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Header & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function]
cls.add_method('GetMagic',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function]
cls.add_method('GetVersionMajor',
'uint16_t',
[])
## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function]
cls.add_method('GetVersionMinor',
'uint16_t',
[])
## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function]
cls.add_method('GetTimeZoneOffset',
'int32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function]
cls.add_method('GetSigFigs',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function]
cls.add_method('GetSnapLen',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function]
cls.add_method('GetDataLinkType',
'uint32_t',
[])
return
def register_Ns3PropagationDelayModel_methods(root_module, cls):
## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel::PropagationDelayModel() [constructor]
cls.add_constructor([])
## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel::PropagationDelayModel(ns3::PropagationDelayModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PropagationDelayModel const &', 'arg0')])
## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::PropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::PropagationDelayModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3PropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::PropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::PropagationLossModel::PropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::PropagationLossModel::SetNext(ns3::Ptr<ns3::PropagationLossModel> next) [member function]
cls.add_method('SetNext',
'void',
[param('ns3::Ptr< ns3::PropagationLossModel >', 'next')])
## propagation-loss-model.h (module 'propagation'): double ns3::PropagationLossModel::CalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('CalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::PropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3QosTag_methods(root_module, cls):
## qos-tag.h (module 'wifi'): ns3::QosTag::QosTag(ns3::QosTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::QosTag const &', 'arg0')])
## qos-tag.h (module 'wifi'): ns3::QosTag::QosTag() [constructor]
cls.add_constructor([])
## qos-tag.h (module 'wifi'): ns3::QosTag::QosTag(uint8_t tid) [constructor]
cls.add_constructor([param('uint8_t', 'tid')])
## qos-tag.h (module 'wifi'): void ns3::QosTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## qos-tag.h (module 'wifi'): ns3::TypeId ns3::QosTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## qos-tag.h (module 'wifi'): uint32_t ns3::QosTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## qos-tag.h (module 'wifi'): uint8_t ns3::QosTag::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## qos-tag.h (module 'wifi'): static ns3::TypeId ns3::QosTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## qos-tag.h (module 'wifi'): void ns3::QosTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## qos-tag.h (module 'wifi'): void ns3::QosTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## qos-tag.h (module 'wifi'): void ns3::QosTag::SetTid(uint8_t tid) [member function]
cls.add_method('SetTid',
'void',
[param('uint8_t', 'tid')])
## qos-tag.h (module 'wifi'): void ns3::QosTag::SetUserPriority(ns3::UserPriority up) [member function]
cls.add_method('SetUserPriority',
'void',
[param('ns3::UserPriority', 'up')])
return
def register_Ns3QosWifiMacHelper_methods(root_module, cls):
## qos-wifi-mac-helper.h (module 'wifi'): ns3::QosWifiMacHelper::QosWifiMacHelper(ns3::QosWifiMacHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::QosWifiMacHelper const &', 'arg0')])
## qos-wifi-mac-helper.h (module 'wifi'): ns3::QosWifiMacHelper::QosWifiMacHelper() [constructor]
cls.add_constructor([])
## qos-wifi-mac-helper.h (module 'wifi'): static ns3::QosWifiMacHelper ns3::QosWifiMacHelper::Default() [member function]
cls.add_method('Default',
'ns3::QosWifiMacHelper',
[],
is_static=True)
## qos-wifi-mac-helper.h (module 'wifi'): void ns3::QosWifiMacHelper::SetBlockAckInactivityTimeoutForAc(ns3::AcIndex ac, uint16_t timeout) [member function]
cls.add_method('SetBlockAckInactivityTimeoutForAc',
'void',
[param('ns3::AcIndex', 'ac'), param('uint16_t', 'timeout')])
## qos-wifi-mac-helper.h (module 'wifi'): void ns3::QosWifiMacHelper::SetBlockAckThresholdForAc(ns3::AcIndex ac, uint8_t threshold) [member function]
cls.add_method('SetBlockAckThresholdForAc',
'void',
[param('ns3::AcIndex', 'ac'), param('uint8_t', 'threshold')])
## qos-wifi-mac-helper.h (module 'wifi'): void ns3::QosWifiMacHelper::SetMsduAggregatorForAc(ns3::AcIndex ac, 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()) [member function]
cls.add_method('SetMsduAggregatorForAc',
'void',
[param('ns3::AcIndex', 'ac'), 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()')])
## qos-wifi-mac-helper.h (module 'wifi'): void ns3::QosWifiMacHelper::SetType(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('SetType',
'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()')])
## qos-wifi-mac-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiMac> ns3::QosWifiMacHelper::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiMac >',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3RandomPropagationDelayModel_methods(root_module, cls):
## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel::RandomPropagationDelayModel(ns3::RandomPropagationDelayModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RandomPropagationDelayModel const &', 'arg0')])
## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel::RandomPropagationDelayModel() [constructor]
cls.add_constructor([])
## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::RandomPropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, is_virtual=True)
## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::RandomPropagationDelayModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3RandomPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::RandomPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::RandomPropagationLossModel::RandomPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): double ns3::RandomPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3RangePropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::RangePropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::RangePropagationLossModel::RangePropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): double ns3::RangePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', 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__Ns3InterferenceHelperEvent_Ns3Empty_Ns3DefaultDeleter__lt__ns3InterferenceHelperEvent__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> >::SimpleRefCount(ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter< ns3::InterferenceHelper::Event > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3WifiInformationElement_Ns3Empty_Ns3DefaultDeleter__lt__ns3WifiInformationElement__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >::SimpleRefCount(ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter< ns3::WifiInformationElement > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3ThreeLogDistancePropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::ThreeLogDistancePropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::ThreeLogDistancePropagationLossModel::ThreeLogDistancePropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): double ns3::ThreeLogDistancePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Time_methods(root_module, cls):
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right'))
cls.add_binary_comparison_operator('!=')
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor]
cls.add_constructor([param('ns3::Time const &', 'o')])
## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'value')])
## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function]
cls.add_method('Compare',
'int',
[param('ns3::Time const &', 'o')],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function]
cls.add_method('GetFemtoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function]
cls.add_method('GetInteger',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function]
cls.add_method('GetMicroSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function]
cls.add_method('GetMilliSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function]
cls.add_method('GetNanoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function]
cls.add_method('GetPicoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function]
cls.add_method('GetResolution',
'ns3::Time::Unit',
[],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function]
cls.add_method('GetSeconds',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function]
cls.add_method('GetTimeStep',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function]
cls.add_method('IsNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function]
cls.add_method('IsPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function]
cls.add_method('IsStrictlyNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function]
cls.add_method('IsStrictlyPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function]
cls.add_method('IsZero',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function]
cls.add_method('SetResolution',
'void',
[param('ns3::Time::Unit', 'resolution')],
is_static=True)
## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
return
def register_Ns3TraceSourceAccessor_methods(root_module, cls):
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor]
cls.add_constructor([])
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Connect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('ConnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Disconnect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('DisconnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Trailer_methods(root_module, cls):
cls.add_output_stream_operator()
## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor]
cls.add_constructor([])
## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Trailer const &', 'arg0')])
## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'end')],
is_pure_virtual=True, is_virtual=True)
## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TwoRayGroundPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::TwoRayGroundPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::TwoRayGroundPropagationLossModel::TwoRayGroundPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetLambda(double frequency, double speed) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'frequency'), param('double', 'speed')])
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetLambda(double lambda) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'lambda')])
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetSystemLoss(double systemLoss) [member function]
cls.add_method('SetSystemLoss',
'void',
[param('double', 'systemLoss')])
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetMinDistance(double minDistance) [member function]
cls.add_method('SetMinDistance',
'void',
[param('double', 'minDistance')])
## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetMinDistance() const [member function]
cls.add_method('GetMinDistance',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetSystemLoss() const [member function]
cls.add_method('GetSystemLoss',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetHeightAboveZ(double heightAboveZ) [member function]
cls.add_method('SetHeightAboveZ',
'void',
[param('double', 'heightAboveZ')])
## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3WifiActionHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::WifiActionHeader(ns3::WifiActionHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiActionHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::WifiActionHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::WifiActionHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue ns3::WifiActionHeader::GetAction() [member function]
cls.add_method('GetAction',
'ns3::WifiActionHeader::ActionValue',
[])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::CategoryValue ns3::WifiActionHeader::GetCategory() [member function]
cls.add_method('GetCategory',
'ns3::WifiActionHeader::CategoryValue',
[])
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::WifiActionHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::WifiActionHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::WifiActionHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::WifiActionHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::WifiActionHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::WifiActionHeader::SetAction(ns3::WifiActionHeader::CategoryValue type, ns3::WifiActionHeader::ActionValue action) [member function]
cls.add_method('SetAction',
'void',
[param('ns3::WifiActionHeader::CategoryValue', 'type'), param('ns3::WifiActionHeader::ActionValue', 'action')])
return
def register_Ns3WifiActionHeaderActionValue_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::ActionValue() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::ActionValue(ns3::WifiActionHeader::ActionValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiActionHeader::ActionValue const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::blockAck [variable]
cls.add_instance_attribute('blockAck', 'ns3::WifiActionHeader::BlockAckActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::interwork [variable]
cls.add_instance_attribute('interwork', 'ns3::WifiActionHeader::InterworkActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::linkMetrtic [variable]
cls.add_instance_attribute('linkMetrtic', 'ns3::WifiActionHeader::LinkMetricActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::pathSelection [variable]
cls.add_instance_attribute('pathSelection', 'ns3::WifiActionHeader::PathSelectionActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::peerLink [variable]
cls.add_instance_attribute('peerLink', 'ns3::WifiActionHeader::PeerLinkMgtActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::resourceCoordination [variable]
cls.add_instance_attribute('resourceCoordination', 'ns3::WifiActionHeader::ResourceCoordinationActionValue', is_const=False)
return
def register_Ns3WifiInformationElement_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('==')
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElement::WifiInformationElement() [constructor]
cls.add_constructor([])
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElement::WifiInformationElement(ns3::WifiInformationElement const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiInformationElement const &', 'arg0')])
## wifi-information-element.h (module 'wifi'): ns3::Buffer::Iterator ns3::WifiInformationElement::Deserialize(ns3::Buffer::Iterator i) [member function]
cls.add_method('Deserialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'i')])
## wifi-information-element.h (module 'wifi'): ns3::Buffer::Iterator ns3::WifiInformationElement::DeserializeIfPresent(ns3::Buffer::Iterator i) [member function]
cls.add_method('DeserializeIfPresent',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'i')])
## wifi-information-element.h (module 'wifi'): uint8_t ns3::WifiInformationElement::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_pure_virtual=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElementId ns3::WifiInformationElement::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): uint8_t ns3::WifiInformationElement::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): uint16_t ns3::WifiInformationElement::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint16_t',
[],
is_const=True)
## wifi-information-element.h (module 'wifi'): void ns3::WifiInformationElement::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): ns3::Buffer::Iterator ns3::WifiInformationElement::Serialize(ns3::Buffer::Iterator i) const [member function]
cls.add_method('Serialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'i')],
is_const=True)
## wifi-information-element.h (module 'wifi'): void ns3::WifiInformationElement::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3WifiInformationElementVector_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## wifi-information-element-vector.h (module 'wifi'): ns3::WifiInformationElementVector::WifiInformationElementVector(ns3::WifiInformationElementVector const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiInformationElementVector const &', 'arg0')])
## wifi-information-element-vector.h (module 'wifi'): ns3::WifiInformationElementVector::WifiInformationElementVector() [constructor]
cls.add_constructor([])
## wifi-information-element-vector.h (module 'wifi'): bool ns3::WifiInformationElementVector::AddInformationElement(ns3::Ptr<ns3::WifiInformationElement> element) [member function]
cls.add_method('AddInformationElement',
'bool',
[param('ns3::Ptr< ns3::WifiInformationElement >', 'element')])
## wifi-information-element-vector.h (module 'wifi'): __gnu_cxx::__normal_iterator<ns3::Ptr<ns3::WifiInformationElement>*,std::vector<ns3::Ptr<ns3::WifiInformationElement>, std::allocator<ns3::Ptr<ns3::WifiInformationElement> > > > ns3::WifiInformationElementVector::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::WifiInformationElement >, std::vector< ns3::Ptr< ns3::WifiInformationElement > > >',
[])
## wifi-information-element-vector.h (module 'wifi'): uint32_t ns3::WifiInformationElementVector::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): uint32_t ns3::WifiInformationElementVector::DeserializeSingleIe(ns3::Buffer::Iterator start) [member function]
cls.add_method('DeserializeSingleIe',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): __gnu_cxx::__normal_iterator<ns3::Ptr<ns3::WifiInformationElement>*,std::vector<ns3::Ptr<ns3::WifiInformationElement>, std::allocator<ns3::Ptr<ns3::WifiInformationElement> > > > ns3::WifiInformationElementVector::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::WifiInformationElement >, std::vector< ns3::Ptr< ns3::WifiInformationElement > > >',
[])
## wifi-information-element-vector.h (module 'wifi'): ns3::Ptr<ns3::WifiInformationElement> ns3::WifiInformationElementVector::FindFirst(ns3::WifiInformationElementId id) const [member function]
cls.add_method('FindFirst',
'ns3::Ptr< ns3::WifiInformationElement >',
[param('ns3::WifiInformationElementId', 'id')],
is_const=True)
## wifi-information-element-vector.h (module 'wifi'): ns3::TypeId ns3::WifiInformationElementVector::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): uint32_t ns3::WifiInformationElementVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): static ns3::TypeId ns3::WifiInformationElementVector::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-information-element-vector.h (module 'wifi'): void ns3::WifiInformationElementVector::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): void ns3::WifiInformationElementVector::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): void ns3::WifiInformationElementVector::SetMaxSize(uint16_t size) [member function]
cls.add_method('SetMaxSize',
'void',
[param('uint16_t', 'size')])
## wifi-information-element-vector.h (module 'wifi'): uint32_t ns3::WifiInformationElementVector::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True, visibility='protected')
return
def register_Ns3WifiMac_methods(root_module, cls):
## wifi-mac.h (module 'wifi'): ns3::WifiMac::WifiMac() [constructor]
cls.add_constructor([])
## wifi-mac.h (module 'wifi'): ns3::WifiMac::WifiMac(ns3::WifiMac const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMac const &', 'arg0')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::ConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('ConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetAckTimeout() const [member function]
cls.add_method('GetAckTimeout',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::WifiMac::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Mac48Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetBasicBlockAckTimeout() const [member function]
cls.add_method('GetBasicBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::WifiMac::GetBssid() const [member function]
cls.add_method('GetBssid',
'ns3::Mac48Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetCompressedBlockAckTimeout() const [member function]
cls.add_method('GetCompressedBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetCtsTimeout() const [member function]
cls.add_method('GetCtsTimeout',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetEifsNoDifs() const [member function]
cls.add_method('GetEifsNoDifs',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetMaxPropagationDelay() const [member function]
cls.add_method('GetMaxPropagationDelay',
'ns3::Time',
[],
is_const=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetMsduLifetime() const [member function]
cls.add_method('GetMsduLifetime',
'ns3::Time',
[],
is_const=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetPifs() const [member function]
cls.add_method('GetPifs',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetSifs() const [member function]
cls.add_method('GetSifs',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetSlot() const [member function]
cls.add_method('GetSlot',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Ssid ns3::WifiMac::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::WifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyPromiscRx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyPromiscRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyRx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyRxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyTx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyTxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function]
cls.add_method('SetAckTimeout',
'void',
[param('ns3::Time', 'ackTimeout')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetAddress(ns3::Mac48Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetBasicBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetCompressedBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function]
cls.add_method('SetCtsTimeout',
'void',
[param('ns3::Time', 'ctsTimeout')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function]
cls.add_method('SetEifsNoDifs',
'void',
[param('ns3::Time', 'eifsNoDifs')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function]
cls.add_method('SetForwardUpCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function]
cls.add_method('SetLinkDownCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function]
cls.add_method('SetLinkUpCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetMaxPropagationDelay(ns3::Time delay) [member function]
cls.add_method('SetMaxPropagationDelay',
'void',
[param('ns3::Time', 'delay')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetPifs(ns3::Time pifs) [member function]
cls.add_method('SetPifs',
'void',
[param('ns3::Time', 'pifs')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetPromisc() [member function]
cls.add_method('SetPromisc',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetSifs(ns3::Time sifs) [member function]
cls.add_method('SetSifs',
'void',
[param('ns3::Time', 'sifs')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetSlot(ns3::Time slotTime) [member function]
cls.add_method('SetSlot',
'void',
[param('ns3::Time', 'slotTime')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetWifiPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): bool ns3::WifiMac::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::ConfigureCCHDcf(ns3::Ptr<ns3::Dcf> dcf, uint32_t cwmin, uint32_t cwmax, ns3::AcIndex ac) [member function]
cls.add_method('ConfigureCCHDcf',
'void',
[param('ns3::Ptr< ns3::Dcf >', 'dcf'), param('uint32_t', 'cwmin'), param('uint32_t', 'cwmax'), param('ns3::AcIndex', 'ac')],
visibility='protected')
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::ConfigureDcf(ns3::Ptr<ns3::Dcf> dcf, uint32_t cwmin, uint32_t cwmax, ns3::AcIndex ac) [member function]
cls.add_method('ConfigureDcf',
'void',
[param('ns3::Ptr< ns3::Dcf >', 'dcf'), param('uint32_t', 'cwmin'), param('uint32_t', 'cwmax'), param('ns3::AcIndex', 'ac')],
visibility='protected')
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('FinishConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3WifiMacHeader_methods(root_module, cls):
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::WifiMacHeader(ns3::WifiMacHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMacHeader const &', 'arg0')])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::WifiMacHeader() [constructor]
cls.add_constructor([])
## wifi-mac-header.h (module 'wifi'): uint32_t ns3::WifiMacHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr1() const [member function]
cls.add_method('GetAddr1',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr2() const [member function]
cls.add_method('GetAddr2',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr3() const [member function]
cls.add_method('GetAddr3',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr4() const [member function]
cls.add_method('GetAddr4',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Time ns3::WifiMacHeader::GetDuration() const [member function]
cls.add_method('GetDuration',
'ns3::Time',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetFragmentNumber() const [member function]
cls.add_method('GetFragmentNumber',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::TypeId ns3::WifiMacHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::QosAckPolicy ns3::WifiMacHeader::GetQosAckPolicy() const [member function]
cls.add_method('GetQosAckPolicy',
'ns3::WifiMacHeader::QosAckPolicy',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint8_t ns3::WifiMacHeader::GetQosTid() const [member function]
cls.add_method('GetQosTid',
'uint8_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint8_t ns3::WifiMacHeader::GetQosTxopLimit() const [member function]
cls.add_method('GetQosTxopLimit',
'uint8_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetRawDuration() const [member function]
cls.add_method('GetRawDuration',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetSequenceControl() const [member function]
cls.add_method('GetSequenceControl',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint32_t ns3::WifiMacHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): uint32_t ns3::WifiMacHeader::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacType ns3::WifiMacHeader::GetType() const [member function]
cls.add_method('GetType',
'ns3::WifiMacType',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): static ns3::TypeId ns3::WifiMacHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-mac-header.h (module 'wifi'): char const * ns3::WifiMacHeader::GetTypeString() const [member function]
cls.add_method('GetTypeString',
'char const *',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAck() const [member function]
cls.add_method('IsAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAction() const [member function]
cls.add_method('IsAction',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAssocReq() const [member function]
cls.add_method('IsAssocReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAssocResp() const [member function]
cls.add_method('IsAssocResp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAuthentication() const [member function]
cls.add_method('IsAuthentication',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsBeacon() const [member function]
cls.add_method('IsBeacon',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsBlockAck() const [member function]
cls.add_method('IsBlockAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsBlockAckReq() const [member function]
cls.add_method('IsBlockAckReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsCfpoll() const [member function]
cls.add_method('IsCfpoll',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsCtl() const [member function]
cls.add_method('IsCtl',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsCts() const [member function]
cls.add_method('IsCts',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsData() const [member function]
cls.add_method('IsData',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsDeauthentication() const [member function]
cls.add_method('IsDeauthentication',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsDisassociation() const [member function]
cls.add_method('IsDisassociation',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsFromDs() const [member function]
cls.add_method('IsFromDs',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsMgt() const [member function]
cls.add_method('IsMgt',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsMoreFragments() const [member function]
cls.add_method('IsMoreFragments',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsMultihopAction() const [member function]
cls.add_method('IsMultihopAction',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsProbeReq() const [member function]
cls.add_method('IsProbeReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsProbeResp() const [member function]
cls.add_method('IsProbeResp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosAck() const [member function]
cls.add_method('IsQosAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosAmsdu() const [member function]
cls.add_method('IsQosAmsdu',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosBlockAck() const [member function]
cls.add_method('IsQosBlockAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosData() const [member function]
cls.add_method('IsQosData',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosEosp() const [member function]
cls.add_method('IsQosEosp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosNoAck() const [member function]
cls.add_method('IsQosNoAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsReassocReq() const [member function]
cls.add_method('IsReassocReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsReassocResp() const [member function]
cls.add_method('IsReassocResp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsRetry() const [member function]
cls.add_method('IsRetry',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsRts() const [member function]
cls.add_method('IsRts',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsToDs() const [member function]
cls.add_method('IsToDs',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAction() [member function]
cls.add_method('SetAction',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr1(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr1',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr2(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr2',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr3(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr3',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr4(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr4',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAssocReq() [member function]
cls.add_method('SetAssocReq',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAssocResp() [member function]
cls.add_method('SetAssocResp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetBeacon() [member function]
cls.add_method('SetBeacon',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetBlockAck() [member function]
cls.add_method('SetBlockAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetBlockAckReq() [member function]
cls.add_method('SetBlockAckReq',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsFrom() [member function]
cls.add_method('SetDsFrom',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsNotFrom() [member function]
cls.add_method('SetDsNotFrom',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsNotTo() [member function]
cls.add_method('SetDsNotTo',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsTo() [member function]
cls.add_method('SetDsTo',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDuration(ns3::Time duration) [member function]
cls.add_method('SetDuration',
'void',
[param('ns3::Time', 'duration')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetFragmentNumber(uint8_t frag) [member function]
cls.add_method('SetFragmentNumber',
'void',
[param('uint8_t', 'frag')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetId(uint16_t id) [member function]
cls.add_method('SetId',
'void',
[param('uint16_t', 'id')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetMoreFragments() [member function]
cls.add_method('SetMoreFragments',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetMultihopAction() [member function]
cls.add_method('SetMultihopAction',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetNoMoreFragments() [member function]
cls.add_method('SetNoMoreFragments',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetNoRetry() [member function]
cls.add_method('SetNoRetry',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetProbeReq() [member function]
cls.add_method('SetProbeReq',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetProbeResp() [member function]
cls.add_method('SetProbeResp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosAckPolicy(ns3::WifiMacHeader::QosAckPolicy arg0) [member function]
cls.add_method('SetQosAckPolicy',
'void',
[param('ns3::WifiMacHeader::QosAckPolicy', 'arg0')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosAmsdu() [member function]
cls.add_method('SetQosAmsdu',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosBlockAck() [member function]
cls.add_method('SetQosBlockAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosEosp() [member function]
cls.add_method('SetQosEosp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNoAck() [member function]
cls.add_method('SetQosNoAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNoAmsdu() [member function]
cls.add_method('SetQosNoAmsdu',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNoEosp() [member function]
cls.add_method('SetQosNoEosp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNormalAck() [member function]
cls.add_method('SetQosNormalAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosTid(uint8_t tid) [member function]
cls.add_method('SetQosTid',
'void',
[param('uint8_t', 'tid')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosTxopLimit(uint8_t txop) [member function]
cls.add_method('SetQosTxopLimit',
'void',
[param('uint8_t', 'txop')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetRawDuration(uint16_t duration) [member function]
cls.add_method('SetRawDuration',
'void',
[param('uint16_t', 'duration')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetRetry() [member function]
cls.add_method('SetRetry',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetSequenceNumber(uint16_t seq) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'seq')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetType(ns3::WifiMacType type) [member function]
cls.add_method('SetType',
'void',
[param('ns3::WifiMacType', 'type')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetTypeData() [member function]
cls.add_method('SetTypeData',
'void',
[])
return
def register_Ns3WifiMacQueue_methods(root_module, cls):
## wifi-mac-queue.h (module 'wifi'): ns3::WifiMacQueue::WifiMacQueue(ns3::WifiMacQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMacQueue const &', 'arg0')])
## wifi-mac-queue.h (module 'wifi'): ns3::WifiMacQueue::WifiMacQueue() [constructor]
cls.add_constructor([])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::Dequeue(ns3::WifiMacHeader * hdr) [member function]
cls.add_method('Dequeue',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr')])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::DequeueByTidAndAddress(ns3::WifiMacHeader * hdr, uint8_t tid, ns3::WifiMacHeader::AddressType type, ns3::Mac48Address addr) [member function]
cls.add_method('DequeueByTidAndAddress',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr'), param('uint8_t', 'tid'), param('ns3::WifiMacHeader::AddressType', 'type'), param('ns3::Mac48Address', 'addr')])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::DequeueFirstAvailable(ns3::WifiMacHeader * hdr, ns3::Time & tStamp, ns3::QosBlockedDestinations const * blockedPackets) [member function]
cls.add_method('DequeueFirstAvailable',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr'), param('ns3::Time &', 'tStamp'), param('ns3::QosBlockedDestinations const *', 'blockedPackets')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::Flush() [member function]
cls.add_method('Flush',
'void',
[])
## wifi-mac-queue.h (module 'wifi'): ns3::Time ns3::WifiMacQueue::GetMaxDelay() const [member function]
cls.add_method('GetMaxDelay',
'ns3::Time',
[],
is_const=True)
## wifi-mac-queue.h (module 'wifi'): uint32_t ns3::WifiMacQueue::GetMaxSize() const [member function]
cls.add_method('GetMaxSize',
'uint32_t',
[],
is_const=True)
## wifi-mac-queue.h (module 'wifi'): uint32_t ns3::WifiMacQueue::GetNPacketsByTidAndAddress(uint8_t tid, ns3::WifiMacHeader::AddressType type, ns3::Mac48Address addr) [member function]
cls.add_method('GetNPacketsByTidAndAddress',
'uint32_t',
[param('uint8_t', 'tid'), param('ns3::WifiMacHeader::AddressType', 'type'), param('ns3::Mac48Address', 'addr')])
## wifi-mac-queue.h (module 'wifi'): uint32_t ns3::WifiMacQueue::GetSize() [member function]
cls.add_method('GetSize',
'uint32_t',
[])
## wifi-mac-queue.h (module 'wifi'): static ns3::TypeId ns3::WifiMacQueue::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-mac-queue.h (module 'wifi'): bool ns3::WifiMacQueue::IsEmpty() [member function]
cls.add_method('IsEmpty',
'bool',
[])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::Peek(ns3::WifiMacHeader * hdr) [member function]
cls.add_method('Peek',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr')])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::PeekByTidAndAddress(ns3::WifiMacHeader * hdr, uint8_t tid, ns3::WifiMacHeader::AddressType type, ns3::Mac48Address addr) [member function]
cls.add_method('PeekByTidAndAddress',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr'), param('uint8_t', 'tid'), param('ns3::WifiMacHeader::AddressType', 'type'), param('ns3::Mac48Address', 'addr')])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::PeekFirstAvailable(ns3::WifiMacHeader * hdr, ns3::Time & tStamp, ns3::QosBlockedDestinations const * blockedPackets) [member function]
cls.add_method('PeekFirstAvailable',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr'), param('ns3::Time &', 'tStamp'), param('ns3::QosBlockedDestinations const *', 'blockedPackets')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::PushFront(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## wifi-mac-queue.h (module 'wifi'): bool ns3::WifiMacQueue::Remove(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::SetMaxDelay(ns3::Time delay) [member function]
cls.add_method('SetMaxDelay',
'void',
[param('ns3::Time', 'delay')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::SetMaxSize(uint32_t maxSize) [member function]
cls.add_method('SetMaxSize',
'void',
[param('uint32_t', 'maxSize')])
return
def register_Ns3WifiPhy_methods(root_module, cls):
## wifi-phy.h (module 'wifi'): ns3::WifiPhy::WifiPhy(ns3::WifiPhy const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiPhy const &', 'arg0')])
## wifi-phy.h (module 'wifi'): ns3::WifiPhy::WifiPhy() [constructor]
cls.add_constructor([])
## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function]
cls.add_method('CalculateSnr',
'double',
[param('ns3::WifiMode', 'txMode'), param('double', 'ber')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::Time ns3::WifiPhy::CalculateTxDuration(uint32_t size, ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('CalculateTxDuration',
'ns3::Time',
[param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::ConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('ConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::WifiChannel> ns3::WifiPhy::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::WifiChannel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): uint16_t ns3::WifiPhy::GetChannelNumber() const [member function]
cls.add_method('GetChannelNumber',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetDelayUntilIdle() [member function]
cls.add_method('GetDelayUntilIdle',
'ns3::Time',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate11Mbps() [member function]
cls.add_method('GetDsssRate11Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate1Mbps() [member function]
cls.add_method('GetDsssRate1Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate2Mbps() [member function]
cls.add_method('GetDsssRate2Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate5_5Mbps() [member function]
cls.add_method('GetDsssRate5_5Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate12Mbps() [member function]
cls.add_method('GetErpOfdmRate12Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate18Mbps() [member function]
cls.add_method('GetErpOfdmRate18Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate24Mbps() [member function]
cls.add_method('GetErpOfdmRate24Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate36Mbps() [member function]
cls.add_method('GetErpOfdmRate36Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate48Mbps() [member function]
cls.add_method('GetErpOfdmRate48Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate54Mbps() [member function]
cls.add_method('GetErpOfdmRate54Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate6Mbps() [member function]
cls.add_method('GetErpOfdmRate6Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate9Mbps() [member function]
cls.add_method('GetErpOfdmRate9Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetLastRxStartTime() const [member function]
cls.add_method('GetLastRxStartTime',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): ns3::WifiMode ns3::WifiPhy::GetMode(uint32_t mode) const [member function]
cls.add_method('GetMode',
'ns3::WifiMode',
[param('uint32_t', 'mode')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNModes() const [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNTxPower() const [member function]
cls.add_method('GetNTxPower',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12Mbps() [member function]
cls.add_method('GetOfdmRate12Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate12MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate12MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate13_5MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate13_5MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18Mbps() [member function]
cls.add_method('GetOfdmRate18Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate18MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate1_5MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate1_5MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24Mbps() [member function]
cls.add_method('GetOfdmRate24Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate24MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate27MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate27MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate2_25MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate2_25MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate36Mbps() [member function]
cls.add_method('GetOfdmRate36Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate3MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate3MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate48Mbps() [member function]
cls.add_method('GetOfdmRate48Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate4_5MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate4_5MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate54Mbps() [member function]
cls.add_method('GetOfdmRate54Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6Mbps() [member function]
cls.add_method('GetOfdmRate6Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate6MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate6MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9Mbps() [member function]
cls.add_method('GetOfdmRate9Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate9MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate9MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPayloadDurationMicroSeconds(uint32_t size, ns3::WifiMode payloadMode) [member function]
cls.add_method('GetPayloadDurationMicroSeconds',
'uint32_t',
[param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode')],
is_static=True)
## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpHeaderDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('GetPlcpHeaderDurationMicroSeconds',
'uint32_t',
[param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetPlcpHeaderMode(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('GetPlcpHeaderMode',
'ns3::WifiMode',
[param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpPreambleDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('GetPlcpPreambleDurationMicroSeconds',
'uint32_t',
[param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetStateDuration() [member function]
cls.add_method('GetStateDuration',
'ns3::Time',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::GetTxPowerEnd() const [member function]
cls.add_method('GetTxPowerEnd',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::GetTxPowerStart() const [member function]
cls.add_method('GetTxPowerStart',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::TypeId ns3::WifiPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateSwitching() [member function]
cls.add_method('IsStateSwitching',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyMonitorSniffRx(ns3::Ptr<ns3::Packet const> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble, double signalDbm, double noiseDbm) [member function]
cls.add_method('NotifyMonitorSniffRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble'), param('double', 'signalDbm'), param('double', 'noiseDbm')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyMonitorSniffTx(ns3::Ptr<ns3::Packet const> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble) [member function]
cls.add_method('NotifyMonitorSniffTx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxBegin(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxBegin',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxEnd(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxBegin(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxBegin',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxEnd(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::RegisterListener(ns3::WifiPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::WifiPhyListener *', 'listener')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SendPacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, uint8_t txPowerLevel) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('uint8_t', 'txPowerLevel')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetChannelNumber(uint16_t id) [member function]
cls.add_method('SetChannelNumber',
'void',
[param('uint16_t', 'id')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetReceiveErrorCallback(ns3::Callback<void,ns3::Ptr<const ns3::Packet>,double,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetReceiveOkCallback(ns3::Callback<void,ns3::Ptr<ns3::Packet>,double,ns3::WifiMode,ns3::WifiPreamble,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::WifiMode, ns3::WifiPreamble, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3WifiRemoteStationManager_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationManager::WifiRemoteStationManager(ns3::WifiRemoteStationManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStationManager const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationManager::WifiRemoteStationManager() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::AddBasicMode(ns3::WifiMode mode) [member function]
cls.add_method('AddBasicMode',
'void',
[param('ns3::WifiMode', 'mode')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::AddSupportedMode(ns3::Mac48Address address, ns3::WifiMode mode) [member function]
cls.add_method('AddSupportedMode',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'mode')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetAckMode(ns3::Mac48Address address, ns3::WifiMode dataMode) [member function]
cls.add_method('GetAckMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'dataMode')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetBasicMode(uint32_t i) const [member function]
cls.add_method('GetBasicMode',
'ns3::WifiMode',
[param('uint32_t', 'i')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetCtsMode(ns3::Mac48Address address, ns3::WifiMode rtsMode) [member function]
cls.add_method('GetCtsMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'rtsMode')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetDataMode(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fullPacketSize) [member function]
cls.add_method('GetDataMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fullPacketSize')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetDefaultMode() const [member function]
cls.add_method('GetDefaultMode',
'ns3::WifiMode',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetFragmentOffset(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function]
cls.add_method('GetFragmentOffset',
'uint32_t',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')])
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetFragmentSize(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function]
cls.add_method('GetFragmentSize',
'uint32_t',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')])
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetFragmentationThreshold() const [member function]
cls.add_method('GetFragmentationThreshold',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo ns3::WifiRemoteStationManager::GetInfo(ns3::Mac48Address address) [member function]
cls.add_method('GetInfo',
'ns3::WifiRemoteStationInfo',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetMaxSlrc() const [member function]
cls.add_method('GetMaxSlrc',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetMaxSsrc() const [member function]
cls.add_method('GetMaxSsrc',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetNBasicModes() const [member function]
cls.add_method('GetNBasicModes',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetNonUnicastMode() const [member function]
cls.add_method('GetNonUnicastMode',
'ns3::WifiMode',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetRtsCtsThreshold() const [member function]
cls.add_method('GetRtsCtsThreshold',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetRtsMode(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('GetRtsMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): static ns3::TypeId ns3::WifiRemoteStationManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsAssociated(ns3::Mac48Address address) const [member function]
cls.add_method('IsAssociated',
'bool',
[param('ns3::Mac48Address', 'address')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsBrandNew(ns3::Mac48Address address) const [member function]
cls.add_method('IsBrandNew',
'bool',
[param('ns3::Mac48Address', 'address')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsLastFragment(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function]
cls.add_method('IsLastFragment',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsWaitAssocTxOk(ns3::Mac48Address address) const [member function]
cls.add_method('IsWaitAssocTxOk',
'bool',
[param('ns3::Mac48Address', 'address')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedDataRetransmission(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedDataRetransmission',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedFragmentation(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedFragmentation',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedRts(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedRts',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedRtsRetransmission(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedRtsRetransmission',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::PrepareForQueue(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fullPacketSize) [member function]
cls.add_method('PrepareForQueue',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fullPacketSize')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordDisassociated(ns3::Mac48Address address) [member function]
cls.add_method('RecordDisassociated',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordGotAssocTxFailed(ns3::Mac48Address address) [member function]
cls.add_method('RecordGotAssocTxFailed',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordGotAssocTxOk(ns3::Mac48Address address) [member function]
cls.add_method('RecordGotAssocTxOk',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordWaitAssocTxOk(ns3::Mac48Address address) [member function]
cls.add_method('RecordWaitAssocTxOk',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportDataFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportDataFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportDataOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('ReportDataOk',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportFinalDataFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportFinalDataFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportFinalRtsFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportFinalRtsFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportRtsFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportRtsFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportRtsOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('ReportRtsOk',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportRxOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('ReportRxOk',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::Reset() [member function]
cls.add_method('Reset',
'void',
[])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::Reset(ns3::Mac48Address address) [member function]
cls.add_method('Reset',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetFragmentationThreshold(uint32_t threshold) [member function]
cls.add_method('SetFragmentationThreshold',
'void',
[param('uint32_t', 'threshold')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetMaxSlrc(uint32_t maxSlrc) [member function]
cls.add_method('SetMaxSlrc',
'void',
[param('uint32_t', 'maxSlrc')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetMaxSsrc(uint32_t maxSsrc) [member function]
cls.add_method('SetMaxSsrc',
'void',
[param('uint32_t', 'maxSsrc')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetRtsCtsThreshold(uint32_t threshold) [member function]
cls.add_method('SetRtsCtsThreshold',
'void',
[param('uint32_t', 'threshold')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetupPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetNSupported(ns3::WifiRemoteStation const * station) const [member function]
cls.add_method('GetNSupported',
'uint32_t',
[param('ns3::WifiRemoteStation const *', 'station')],
is_const=True, visibility='protected')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetSupported(ns3::WifiRemoteStation const * station, uint32_t i) const [member function]
cls.add_method('GetSupported',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation const *', 'station'), param('uint32_t', 'i')],
is_const=True, visibility='protected')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::WifiRemoteStationManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedDataRetransmission(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedDataRetransmission',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedFragmentation(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedFragmentation',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRts',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedRtsRetransmission(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRtsRetransmission',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3YansWifiPhy_methods(root_module, cls):
## yans-wifi-phy.h (module 'wifi'): static ns3::TypeId ns3::YansWifiPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## yans-wifi-phy.h (module 'wifi'): ns3::YansWifiPhy::YansWifiPhy() [constructor]
cls.add_constructor([])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetChannel(ns3::Ptr<ns3::YansWifiChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::YansWifiChannel >', 'channel')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetChannelNumber(uint16_t id) [member function]
cls.add_method('SetChannelNumber',
'void',
[param('uint16_t', 'id')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): uint16_t ns3::YansWifiPhy::GetChannelNumber() const [member function]
cls.add_method('GetChannelNumber',
'uint16_t',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetChannelFrequencyMhz() const [member function]
cls.add_method('GetChannelFrequencyMhz',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::StartReceivePacket(ns3::Ptr<ns3::Packet> packet, double rxPowerDbm, ns3::WifiMode mode, ns3::WifiPreamble preamble) [member function]
cls.add_method('StartReceivePacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDbm'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetRxNoiseFigure(double noiseFigureDb) [member function]
cls.add_method('SetRxNoiseFigure',
'void',
[param('double', 'noiseFigureDb')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetTxPowerStart(double start) [member function]
cls.add_method('SetTxPowerStart',
'void',
[param('double', 'start')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetTxPowerEnd(double end) [member function]
cls.add_method('SetTxPowerEnd',
'void',
[param('double', 'end')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetNTxPower(uint32_t n) [member function]
cls.add_method('SetNTxPower',
'void',
[param('uint32_t', 'n')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetTxGain(double gain) [member function]
cls.add_method('SetTxGain',
'void',
[param('double', 'gain')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetRxGain(double gain) [member function]
cls.add_method('SetRxGain',
'void',
[param('double', 'gain')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetEdThreshold(double threshold) [member function]
cls.add_method('SetEdThreshold',
'void',
[param('double', 'threshold')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetCcaMode1Threshold(double threshold) [member function]
cls.add_method('SetCcaMode1Threshold',
'void',
[param('double', 'threshold')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetErrorRateModel(ns3::Ptr<ns3::ErrorRateModel> rate) [member function]
cls.add_method('SetErrorRateModel',
'void',
[param('ns3::Ptr< ns3::ErrorRateModel >', 'rate')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetDevice(ns3::Ptr<ns3::Object> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::Object >', 'device')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetMobility(ns3::Ptr<ns3::Object> mobility) [member function]
cls.add_method('SetMobility',
'void',
[param('ns3::Ptr< ns3::Object >', 'mobility')])
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetRxNoiseFigure() const [member function]
cls.add_method('GetRxNoiseFigure',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetTxGain() const [member function]
cls.add_method('GetTxGain',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetRxGain() const [member function]
cls.add_method('GetRxGain',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetEdThreshold() const [member function]
cls.add_method('GetEdThreshold',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetCcaMode1Threshold() const [member function]
cls.add_method('GetCcaMode1Threshold',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::ErrorRateModel> ns3::YansWifiPhy::GetErrorRateModel() const [member function]
cls.add_method('GetErrorRateModel',
'ns3::Ptr< ns3::ErrorRateModel >',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::Object> ns3::YansWifiPhy::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::Object> ns3::YansWifiPhy::GetMobility() [member function]
cls.add_method('GetMobility',
'ns3::Ptr< ns3::Object >',
[])
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetTxPowerStart() const [member function]
cls.add_method('GetTxPowerStart',
'double',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetTxPowerEnd() const [member function]
cls.add_method('GetTxPowerEnd',
'double',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): uint32_t ns3::YansWifiPhy::GetNTxPower() const [member function]
cls.add_method('GetNTxPower',
'uint32_t',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetReceiveOkCallback(ns3::Callback<void,ns3::Ptr<ns3::Packet>,double,ns3::WifiMode,ns3::WifiPreamble,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::WifiMode, ns3::WifiPreamble, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetReceiveErrorCallback(ns3::Callback<void,ns3::Ptr<const ns3::Packet>,double,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SendPacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, uint8_t txPowerLevel) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('uint8_t', 'txPowerLevel')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::RegisterListener(ns3::WifiPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::WifiPhyListener *', 'listener')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateSwitching() [member function]
cls.add_method('IsStateSwitching',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Time ns3::YansWifiPhy::GetStateDuration() [member function]
cls.add_method('GetStateDuration',
'ns3::Time',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Time ns3::YansWifiPhy::GetDelayUntilIdle() [member function]
cls.add_method('GetDelayUntilIdle',
'ns3::Time',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Time ns3::YansWifiPhy::GetLastRxStartTime() const [member function]
cls.add_method('GetLastRxStartTime',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): uint32_t ns3::YansWifiPhy::GetNModes() const [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::WifiMode ns3::YansWifiPhy::GetMode(uint32_t mode) const [member function]
cls.add_method('GetMode',
'ns3::WifiMode',
[param('uint32_t', 'mode')],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function]
cls.add_method('CalculateSnr',
'double',
[param('ns3::WifiMode', 'txMode'), param('double', 'ber')],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::WifiChannel> ns3::YansWifiPhy::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::WifiChannel >',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::ConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('ConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3AarfWifiManager_methods(root_module, cls):
## aarf-wifi-manager.h (module 'wifi'): ns3::AarfWifiManager::AarfWifiManager(ns3::AarfWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AarfWifiManager const &', 'arg0')])
## aarf-wifi-manager.h (module 'wifi'): ns3::AarfWifiManager::AarfWifiManager() [constructor]
cls.add_constructor([])
## aarf-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::AarfWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aarf-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::AarfWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AarfWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AarfWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): bool ns3::AarfWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AarfcdWifiManager_methods(root_module, cls):
## aarfcd-wifi-manager.h (module 'wifi'): ns3::AarfcdWifiManager::AarfcdWifiManager(ns3::AarfcdWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AarfcdWifiManager const &', 'arg0')])
## aarfcd-wifi-manager.h (module 'wifi'): ns3::AarfcdWifiManager::AarfcdWifiManager() [constructor]
cls.add_constructor([])
## aarfcd-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::AarfcdWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aarfcd-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::AarfcdWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AarfcdWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AarfcdWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): bool ns3::AarfcdWifiManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRts',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): bool ns3::AarfcdWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AmrrWifiManager_methods(root_module, cls):
## amrr-wifi-manager.h (module 'wifi'): ns3::AmrrWifiManager::AmrrWifiManager(ns3::AmrrWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AmrrWifiManager const &', 'arg0')])
## amrr-wifi-manager.h (module 'wifi'): ns3::AmrrWifiManager::AmrrWifiManager() [constructor]
cls.add_constructor([])
## amrr-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::AmrrWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## amrr-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::AmrrWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AmrrWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AmrrWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): bool ns3::AmrrWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AmsduSubframeHeader_methods(root_module, cls):
## amsdu-subframe-header.h (module 'wifi'): ns3::AmsduSubframeHeader::AmsduSubframeHeader(ns3::AmsduSubframeHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AmsduSubframeHeader const &', 'arg0')])
## amsdu-subframe-header.h (module 'wifi'): ns3::AmsduSubframeHeader::AmsduSubframeHeader() [constructor]
cls.add_constructor([])
## amsdu-subframe-header.h (module 'wifi'): uint32_t ns3::AmsduSubframeHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): ns3::Mac48Address ns3::AmsduSubframeHeader::GetDestinationAddr() const [member function]
cls.add_method('GetDestinationAddr',
'ns3::Mac48Address',
[],
is_const=True)
## amsdu-subframe-header.h (module 'wifi'): ns3::TypeId ns3::AmsduSubframeHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): uint16_t ns3::AmsduSubframeHeader::GetLength() const [member function]
cls.add_method('GetLength',
'uint16_t',
[],
is_const=True)
## amsdu-subframe-header.h (module 'wifi'): uint32_t ns3::AmsduSubframeHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): ns3::Mac48Address ns3::AmsduSubframeHeader::GetSourceAddr() const [member function]
cls.add_method('GetSourceAddr',
'ns3::Mac48Address',
[],
is_const=True)
## amsdu-subframe-header.h (module 'wifi'): static ns3::TypeId ns3::AmsduSubframeHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::SetDestinationAddr(ns3::Mac48Address to) [member function]
cls.add_method('SetDestinationAddr',
'void',
[param('ns3::Mac48Address', 'to')])
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::SetLength(uint16_t arg0) [member function]
cls.add_method('SetLength',
'void',
[param('uint16_t', 'arg0')])
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::SetSourceAddr(ns3::Mac48Address to) [member function]
cls.add_method('SetSourceAddr',
'void',
[param('ns3::Mac48Address', 'to')])
return
def register_Ns3ArfWifiManager_methods(root_module, cls):
## arf-wifi-manager.h (module 'wifi'): ns3::ArfWifiManager::ArfWifiManager(ns3::ArfWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ArfWifiManager const &', 'arg0')])
## arf-wifi-manager.h (module 'wifi'): ns3::ArfWifiManager::ArfWifiManager() [constructor]
cls.add_constructor([])
## arf-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::ArfWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## arf-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::ArfWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::ArfWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::ArfWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): bool ns3::ArfWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AthstatsWifiTraceSink_methods(root_module, cls):
## athstats-helper.h (module 'wifi'): ns3::AthstatsWifiTraceSink::AthstatsWifiTraceSink(ns3::AthstatsWifiTraceSink const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AthstatsWifiTraceSink const &', 'arg0')])
## athstats-helper.h (module 'wifi'): ns3::AthstatsWifiTraceSink::AthstatsWifiTraceSink() [constructor]
cls.add_constructor([])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::DevRxTrace(std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DevRxTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::DevTxTrace(std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DevTxTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## athstats-helper.h (module 'wifi'): static ns3::TypeId ns3::AthstatsWifiTraceSink::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::Open(std::string const & name) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'name')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::PhyRxErrorTrace(std::string context, ns3::Ptr<ns3::Packet const> packet, double snr) [member function]
cls.add_method('PhyRxErrorTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'snr')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::PhyRxOkTrace(std::string context, ns3::Ptr<ns3::Packet const> packet, double snr, ns3::WifiMode mode, ns3::WifiPreamble preamble) [member function]
cls.add_method('PhyRxOkTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'snr'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::PhyStateTrace(std::string context, ns3::Time start, ns3::Time duration, ns3::WifiPhy::State state) [member function]
cls.add_method('PhyStateTrace',
'void',
[param('std::string', 'context'), param('ns3::Time', 'start'), param('ns3::Time', 'duration'), param('ns3::WifiPhy::State', 'state')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::PhyTxTrace(std::string context, ns3::Ptr<ns3::Packet const> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, uint8_t txPower) [member function]
cls.add_method('PhyTxTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('uint8_t', 'txPower')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::TxDataFailedTrace(std::string context, ns3::Mac48Address address) [member function]
cls.add_method('TxDataFailedTrace',
'void',
[param('std::string', 'context'), param('ns3::Mac48Address', 'address')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::TxFinalDataFailedTrace(std::string context, ns3::Mac48Address address) [member function]
cls.add_method('TxFinalDataFailedTrace',
'void',
[param('std::string', 'context'), param('ns3::Mac48Address', 'address')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::TxFinalRtsFailedTrace(std::string context, ns3::Mac48Address address) [member function]
cls.add_method('TxFinalRtsFailedTrace',
'void',
[param('std::string', 'context'), param('ns3::Mac48Address', 'address')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::TxRtsFailedTrace(std::string context, ns3::Mac48Address address) [member function]
cls.add_method('TxRtsFailedTrace',
'void',
[param('std::string', 'context'), param('ns3::Mac48Address', 'address')])
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_Ns3CaraWifiManager_methods(root_module, cls):
## cara-wifi-manager.h (module 'wifi'): ns3::CaraWifiManager::CaraWifiManager(ns3::CaraWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CaraWifiManager const &', 'arg0')])
## cara-wifi-manager.h (module 'wifi'): ns3::CaraWifiManager::CaraWifiManager() [constructor]
cls.add_constructor([])
## cara-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::CaraWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## cara-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::CaraWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::CaraWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::CaraWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): bool ns3::CaraWifiManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRts',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): bool ns3::CaraWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
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_Ns3ConstantRateWifiManager_methods(root_module, cls):
## constant-rate-wifi-manager.h (module 'wifi'): ns3::ConstantRateWifiManager::ConstantRateWifiManager(ns3::ConstantRateWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ConstantRateWifiManager const &', 'arg0')])
## constant-rate-wifi-manager.h (module 'wifi'): ns3::ConstantRateWifiManager::ConstantRateWifiManager() [constructor]
cls.add_constructor([])
## constant-rate-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::ConstantRateWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## constant-rate-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::ConstantRateWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::ConstantRateWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::ConstantRateWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): bool ns3::ConstantRateWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3ConstantSpeedPropagationDelayModel_methods(root_module, cls):
## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel::ConstantSpeedPropagationDelayModel(ns3::ConstantSpeedPropagationDelayModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ConstantSpeedPropagationDelayModel const &', 'arg0')])
## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel::ConstantSpeedPropagationDelayModel() [constructor]
cls.add_constructor([])
## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::ConstantSpeedPropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, is_virtual=True)
## propagation-delay-model.h (module 'propagation'): double ns3::ConstantSpeedPropagationDelayModel::GetSpeed() const [member function]
cls.add_method('GetSpeed',
'double',
[],
is_const=True)
## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::ConstantSpeedPropagationDelayModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-delay-model.h (module 'propagation'): void ns3::ConstantSpeedPropagationDelayModel::SetSpeed(double speed) [member function]
cls.add_method('SetSpeed',
'void',
[param('double', 'speed')])
return
def register_Ns3Cost231PropagationLossModel_methods(root_module, cls):
## cost231-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::Cost231PropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## cost231-propagation-loss-model.h (module 'propagation'): ns3::Cost231PropagationLossModel::Cost231PropagationLossModel() [constructor]
cls.add_constructor([])
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetBSAntennaHeight(double height) [member function]
cls.add_method('SetBSAntennaHeight',
'void',
[param('double', 'height')])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetSSAntennaHeight(double height) [member function]
cls.add_method('SetSSAntennaHeight',
'void',
[param('double', 'height')])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetEnvironment(ns3::Cost231PropagationLossModel::Environment env) [member function]
cls.add_method('SetEnvironment',
'void',
[param('ns3::Cost231PropagationLossModel::Environment', 'env')])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetLambda(double lambda) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'lambda')])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetMinDistance(double minDistance) [member function]
cls.add_method('SetMinDistance',
'void',
[param('double', 'minDistance')])
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetBSAntennaHeight() const [member function]
cls.add_method('GetBSAntennaHeight',
'double',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetSSAntennaHeight() const [member function]
cls.add_method('GetSSAntennaHeight',
'double',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): ns3::Cost231PropagationLossModel::Environment ns3::Cost231PropagationLossModel::GetEnvironment() const [member function]
cls.add_method('GetEnvironment',
'ns3::Cost231PropagationLossModel::Environment',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetMinDistance() const [member function]
cls.add_method('GetMinDistance',
'double',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetLambda(double frequency, double speed) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'frequency'), param('double', 'speed')])
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetShadowing() [member function]
cls.add_method('GetShadowing',
'double',
[])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetShadowing(double shadowing) [member function]
cls.add_method('SetShadowing',
'void',
[param('double', 'shadowing')])
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3CtrlBAckRequestHeader_methods(root_module, cls):
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckRequestHeader::CtrlBAckRequestHeader(ns3::CtrlBAckRequestHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CtrlBAckRequestHeader const &', 'arg0')])
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckRequestHeader::CtrlBAckRequestHeader() [constructor]
cls.add_constructor([])
## ctrl-headers.h (module 'wifi'): uint32_t ns3::CtrlBAckRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ctrl-headers.h (module 'wifi'): ns3::TypeId ns3::CtrlBAckRequestHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint32_t ns3::CtrlBAckRequestHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint16_t ns3::CtrlBAckRequestHeader::GetStartingSequence() const [member function]
cls.add_method('GetStartingSequence',
'uint16_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint16_t ns3::CtrlBAckRequestHeader::GetStartingSequenceControl() const [member function]
cls.add_method('GetStartingSequenceControl',
'uint16_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint8_t ns3::CtrlBAckRequestHeader::GetTidInfo() const [member function]
cls.add_method('GetTidInfo',
'uint8_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): static ns3::TypeId ns3::CtrlBAckRequestHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckRequestHeader::IsBasic() const [member function]
cls.add_method('IsBasic',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckRequestHeader::IsCompressed() const [member function]
cls.add_method('IsCompressed',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckRequestHeader::IsMultiTid() const [member function]
cls.add_method('IsMultiTid',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckRequestHeader::MustSendHtImmediateAck() const [member function]
cls.add_method('MustSendHtImmediateAck',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::SetHtImmediateAck(bool immediateAck) [member function]
cls.add_method('SetHtImmediateAck',
'void',
[param('bool', 'immediateAck')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::SetStartingSequence(uint16_t seq) [member function]
cls.add_method('SetStartingSequence',
'void',
[param('uint16_t', 'seq')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::SetTidInfo(uint8_t tid) [member function]
cls.add_method('SetTidInfo',
'void',
[param('uint8_t', 'tid')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::SetType(ns3::BlockAckType type) [member function]
cls.add_method('SetType',
'void',
[param('ns3::BlockAckType', 'type')])
return
def register_Ns3CtrlBAckResponseHeader_methods(root_module, cls):
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckResponseHeader::CtrlBAckResponseHeader(ns3::CtrlBAckResponseHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CtrlBAckResponseHeader const &', 'arg0')])
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckResponseHeader::CtrlBAckResponseHeader() [constructor]
cls.add_constructor([])
## ctrl-headers.h (module 'wifi'): uint32_t ns3::CtrlBAckResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint16_t const * ns3::CtrlBAckResponseHeader::GetBitmap() const [member function]
cls.add_method('GetBitmap',
'uint16_t const *',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint64_t ns3::CtrlBAckResponseHeader::GetCompressedBitmap() const [member function]
cls.add_method('GetCompressedBitmap',
'uint64_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): ns3::TypeId ns3::CtrlBAckResponseHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint32_t ns3::CtrlBAckResponseHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint16_t ns3::CtrlBAckResponseHeader::GetStartingSequence() const [member function]
cls.add_method('GetStartingSequence',
'uint16_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint16_t ns3::CtrlBAckResponseHeader::GetStartingSequenceControl() const [member function]
cls.add_method('GetStartingSequenceControl',
'uint16_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint8_t ns3::CtrlBAckResponseHeader::GetTidInfo() const [member function]
cls.add_method('GetTidInfo',
'uint8_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): static ns3::TypeId ns3::CtrlBAckResponseHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsBasic() const [member function]
cls.add_method('IsBasic',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsCompressed() const [member function]
cls.add_method('IsCompressed',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsFragmentReceived(uint16_t seq, uint8_t frag) const [member function]
cls.add_method('IsFragmentReceived',
'bool',
[param('uint16_t', 'seq'), param('uint8_t', 'frag')],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsMultiTid() const [member function]
cls.add_method('IsMultiTid',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsPacketReceived(uint16_t seq) const [member function]
cls.add_method('IsPacketReceived',
'bool',
[param('uint16_t', 'seq')],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::MustSendHtImmediateAck() const [member function]
cls.add_method('MustSendHtImmediateAck',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::ResetBitmap() [member function]
cls.add_method('ResetBitmap',
'void',
[])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetHtImmediateAck(bool immeadiateAck) [member function]
cls.add_method('SetHtImmediateAck',
'void',
[param('bool', 'immeadiateAck')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetReceivedFragment(uint16_t seq, uint8_t frag) [member function]
cls.add_method('SetReceivedFragment',
'void',
[param('uint16_t', 'seq'), param('uint8_t', 'frag')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetReceivedPacket(uint16_t seq) [member function]
cls.add_method('SetReceivedPacket',
'void',
[param('uint16_t', 'seq')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetStartingSequence(uint16_t seq) [member function]
cls.add_method('SetStartingSequence',
'void',
[param('uint16_t', 'seq')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetStartingSequenceControl(uint16_t seqControl) [member function]
cls.add_method('SetStartingSequenceControl',
'void',
[param('uint16_t', 'seqControl')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetTidInfo(uint8_t tid) [member function]
cls.add_method('SetTidInfo',
'void',
[param('uint8_t', 'tid')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetType(ns3::BlockAckType type) [member function]
cls.add_method('SetType',
'void',
[param('ns3::BlockAckType', 'type')])
return
def register_Ns3Dcf_methods(root_module, cls):
## dcf.h (module 'wifi'): ns3::Dcf::Dcf() [constructor]
cls.add_constructor([])
## dcf.h (module 'wifi'): ns3::Dcf::Dcf(ns3::Dcf const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Dcf const &', 'arg0')])
## dcf.h (module 'wifi'): uint32_t ns3::Dcf::GetAifsn() const [member function]
cls.add_method('GetAifsn',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## dcf.h (module 'wifi'): uint32_t ns3::Dcf::GetMaxCw() const [member function]
cls.add_method('GetMaxCw',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## dcf.h (module 'wifi'): uint32_t ns3::Dcf::GetMinCw() const [member function]
cls.add_method('GetMinCw',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## dcf.h (module 'wifi'): static ns3::TypeId ns3::Dcf::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dcf.h (module 'wifi'): void ns3::Dcf::SetAifsn(uint32_t aifsn) [member function]
cls.add_method('SetAifsn',
'void',
[param('uint32_t', 'aifsn')],
is_pure_virtual=True, is_virtual=True)
## dcf.h (module 'wifi'): void ns3::Dcf::SetMaxCw(uint32_t maxCw) [member function]
cls.add_method('SetMaxCw',
'void',
[param('uint32_t', 'maxCw')],
is_pure_virtual=True, is_virtual=True)
## dcf.h (module 'wifi'): void ns3::Dcf::SetMinCw(uint32_t minCw) [member function]
cls.add_method('SetMinCw',
'void',
[param('uint32_t', 'minCw')],
is_pure_virtual=True, 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_Ns3EdcaTxopN_methods(root_module, cls):
## edca-txop-n.h (module 'wifi'): static ns3::TypeId ns3::EdcaTxopN::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## edca-txop-n.h (module 'wifi'): ns3::EdcaTxopN::EdcaTxopN() [constructor]
cls.add_constructor([])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetLow(ns3::Ptr<ns3::MacLow> low) [member function]
cls.add_method('SetLow',
'void',
[param('ns3::Ptr< ns3::MacLow >', 'low')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetTxMiddle(ns3::MacTxMiddle * txMiddle) [member function]
cls.add_method('SetTxMiddle',
'void',
[param('ns3::MacTxMiddle *', 'txMiddle')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetManager(ns3::DcfManager * manager) [member function]
cls.add_method('SetManager',
'void',
[param('ns3::DcfManager *', 'manager')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetTxOkCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetTxOkCallback',
'void',
[param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetTxFailedCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetTxFailedCallback',
'void',
[param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> remoteManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'remoteManager')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetTypeOfStation(ns3::TypeOfStation type) [member function]
cls.add_method('SetTypeOfStation',
'void',
[param('ns3::TypeOfStation', 'type')])
## edca-txop-n.h (module 'wifi'): ns3::TypeOfStation ns3::EdcaTxopN::GetTypeOfStation() const [member function]
cls.add_method('GetTypeOfStation',
'ns3::TypeOfStation',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): ns3::Ptr<ns3::WifiMacQueue> ns3::EdcaTxopN::GetQueue() const [member function]
cls.add_method('GetQueue',
'ns3::Ptr< ns3::WifiMacQueue >',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetMinCw(uint32_t minCw) [member function]
cls.add_method('SetMinCw',
'void',
[param('uint32_t', 'minCw')],
is_virtual=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetMaxCw(uint32_t maxCw) [member function]
cls.add_method('SetMaxCw',
'void',
[param('uint32_t', 'maxCw')],
is_virtual=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetAifsn(uint32_t aifsn) [member function]
cls.add_method('SetAifsn',
'void',
[param('uint32_t', 'aifsn')],
is_virtual=True)
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetMinCw() const [member function]
cls.add_method('GetMinCw',
'uint32_t',
[],
is_const=True, is_virtual=True)
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetMaxCw() const [member function]
cls.add_method('GetMaxCw',
'uint32_t',
[],
is_const=True, is_virtual=True)
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetAifsn() const [member function]
cls.add_method('GetAifsn',
'uint32_t',
[],
is_const=True, is_virtual=True)
## edca-txop-n.h (module 'wifi'): ns3::Ptr<ns3::MacLow> ns3::EdcaTxopN::Low() [member function]
cls.add_method('Low',
'ns3::Ptr< ns3::MacLow >',
[])
## edca-txop-n.h (module 'wifi'): ns3::Ptr<ns3::MsduAggregator> ns3::EdcaTxopN::GetMsduAggregator() const [member function]
cls.add_method('GetMsduAggregator',
'ns3::Ptr< ns3::MsduAggregator >',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedsAccess() const [member function]
cls.add_method('NeedsAccess',
'bool',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NotifyAccessGranted() [member function]
cls.add_method('NotifyAccessGranted',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NotifyInternalCollision() [member function]
cls.add_method('NotifyInternalCollision',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NotifyCollision() [member function]
cls.add_method('NotifyCollision',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NotifyChannelSwitching() [member function]
cls.add_method('NotifyChannelSwitching',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotCts(double snr, ns3::WifiMode txMode) [member function]
cls.add_method('GotCts',
'void',
[param('double', 'snr'), param('ns3::WifiMode', 'txMode')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::MissedCts() [member function]
cls.add_method('MissedCts',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotAck(double snr, ns3::WifiMode txMode) [member function]
cls.add_method('GotAck',
'void',
[param('double', 'snr'), param('ns3::WifiMode', 'txMode')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotBlockAck(ns3::CtrlBAckResponseHeader const * blockAck, ns3::Mac48Address recipient) [member function]
cls.add_method('GotBlockAck',
'void',
[param('ns3::CtrlBAckResponseHeader const *', 'blockAck'), param('ns3::Mac48Address', 'recipient')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::MissedBlockAck() [member function]
cls.add_method('MissedBlockAck',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotAddBaResponse(ns3::MgtAddBaResponseHeader const * respHdr, ns3::Mac48Address recipient) [member function]
cls.add_method('GotAddBaResponse',
'void',
[param('ns3::MgtAddBaResponseHeader const *', 'respHdr'), param('ns3::Mac48Address', 'recipient')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotDelBaFrame(ns3::MgtDelBaHeader const * delBaHdr, ns3::Mac48Address recipient) [member function]
cls.add_method('GotDelBaFrame',
'void',
[param('ns3::MgtDelBaHeader const *', 'delBaHdr'), param('ns3::Mac48Address', 'recipient')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::MissedAck() [member function]
cls.add_method('MissedAck',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::StartNext() [member function]
cls.add_method('StartNext',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::RestartAccessIfNeeded() [member function]
cls.add_method('RestartAccessIfNeeded',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::StartAccessIfNeeded() [member function]
cls.add_method('StartAccessIfNeeded',
'void',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedRts() [member function]
cls.add_method('NeedRts',
'bool',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedRtsRetransmission() [member function]
cls.add_method('NeedRtsRetransmission',
'bool',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedDataRetransmission() [member function]
cls.add_method('NeedDataRetransmission',
'bool',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedFragmentation() const [member function]
cls.add_method('NeedFragmentation',
'bool',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetNextFragmentSize() [member function]
cls.add_method('GetNextFragmentSize',
'uint32_t',
[])
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetFragmentSize() [member function]
cls.add_method('GetFragmentSize',
'uint32_t',
[])
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetFragmentOffset() [member function]
cls.add_method('GetFragmentOffset',
'uint32_t',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::IsLastFragment() const [member function]
cls.add_method('IsLastFragment',
'bool',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NextFragment() [member function]
cls.add_method('NextFragment',
'void',
[])
## edca-txop-n.h (module 'wifi'): ns3::Ptr<ns3::Packet> ns3::EdcaTxopN::GetFragmentPacket(ns3::WifiMacHeader * hdr) [member function]
cls.add_method('GetFragmentPacket',
'ns3::Ptr< ns3::Packet >',
[param('ns3::WifiMacHeader *', 'hdr')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetAccessCategory(ns3::AcIndex ac) [member function]
cls.add_method('SetAccessCategory',
'void',
[param('ns3::AcIndex', 'ac')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::Queue(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('Queue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetMsduAggregator(ns3::Ptr<ns3::MsduAggregator> aggr) [member function]
cls.add_method('SetMsduAggregator',
'void',
[param('ns3::Ptr< ns3::MsduAggregator >', 'aggr')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::PushFront(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::CompleteConfig() [member function]
cls.add_method('CompleteConfig',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetBlockAckThreshold(uint8_t threshold) [member function]
cls.add_method('SetBlockAckThreshold',
'void',
[param('uint8_t', 'threshold')])
## edca-txop-n.h (module 'wifi'): uint8_t ns3::EdcaTxopN::GetBlockAckThreshold() const [member function]
cls.add_method('GetBlockAckThreshold',
'uint8_t',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetBlockAckInactivityTimeout(uint16_t timeout) [member function]
cls.add_method('SetBlockAckInactivityTimeout',
'void',
[param('uint16_t', 'timeout')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SendDelbaFrame(ns3::Mac48Address addr, uint8_t tid, bool byOriginator) [member function]
cls.add_method('SendDelbaFrame',
'void',
[param('ns3::Mac48Address', 'addr'), param('uint8_t', 'tid'), param('bool', 'byOriginator')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, visibility='private', is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
visibility='private', is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3ErrorRateModel_methods(root_module, cls):
## error-rate-model.h (module 'wifi'): ns3::ErrorRateModel::ErrorRateModel() [constructor]
cls.add_constructor([])
## error-rate-model.h (module 'wifi'): ns3::ErrorRateModel::ErrorRateModel(ns3::ErrorRateModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ErrorRateModel const &', 'arg0')])
## error-rate-model.h (module 'wifi'): double ns3::ErrorRateModel::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function]
cls.add_method('CalculateSnr',
'double',
[param('ns3::WifiMode', 'txMode'), param('double', 'ber')],
is_const=True)
## error-rate-model.h (module 'wifi'): double ns3::ErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function]
cls.add_method('GetChunkSuccessRate',
'double',
[param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## error-rate-model.h (module 'wifi'): static ns3::TypeId ns3::ErrorRateModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=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_Ns3ExtendedSupportedRatesIE_methods(root_module, cls):
## supported-rates.h (module 'wifi'): ns3::ExtendedSupportedRatesIE::ExtendedSupportedRatesIE(ns3::ExtendedSupportedRatesIE const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ExtendedSupportedRatesIE const &', 'arg0')])
## supported-rates.h (module 'wifi'): ns3::ExtendedSupportedRatesIE::ExtendedSupportedRatesIE() [constructor]
cls.add_constructor([])
## supported-rates.h (module 'wifi'): ns3::ExtendedSupportedRatesIE::ExtendedSupportedRatesIE(ns3::SupportedRates * rates) [constructor]
cls.add_constructor([param('ns3::SupportedRates *', 'rates')])
## supported-rates.h (module 'wifi'): uint8_t ns3::ExtendedSupportedRatesIE::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_virtual=True)
## supported-rates.h (module 'wifi'): ns3::WifiInformationElementId ns3::ExtendedSupportedRatesIE::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): uint8_t ns3::ExtendedSupportedRatesIE::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): uint16_t ns3::ExtendedSupportedRatesIE::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint16_t',
[],
is_const=True)
## supported-rates.h (module 'wifi'): ns3::Buffer::Iterator ns3::ExtendedSupportedRatesIE::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## supported-rates.h (module 'wifi'): void ns3::ExtendedSupportedRatesIE::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
return
def register_Ns3FixedRssLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::FixedRssLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::FixedRssLossModel::FixedRssLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::FixedRssLossModel::SetRss(double rss) [member function]
cls.add_method('SetRss',
'void',
[param('double', 'rss')])
## propagation-loss-model.h (module 'propagation'): double ns3::FixedRssLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3FriisPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::FriisPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::FriisPropagationLossModel::FriisPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetLambda(double frequency, double speed) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'frequency'), param('double', 'speed')])
## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetLambda(double lambda) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'lambda')])
## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetSystemLoss(double systemLoss) [member function]
cls.add_method('SetSystemLoss',
'void',
[param('double', 'systemLoss')])
## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetMinDistance(double minDistance) [member function]
cls.add_method('SetMinDistance',
'void',
[param('double', 'minDistance')])
## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetMinDistance() const [member function]
cls.add_method('GetMinDistance',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetSystemLoss() const [member function]
cls.add_method('GetSystemLoss',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3IdealWifiManager_methods(root_module, cls):
## ideal-wifi-manager.h (module 'wifi'): ns3::IdealWifiManager::IdealWifiManager(ns3::IdealWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IdealWifiManager const &', 'arg0')])
## ideal-wifi-manager.h (module 'wifi'): ns3::IdealWifiManager::IdealWifiManager() [constructor]
cls.add_constructor([])
## ideal-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::IdealWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetupPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::IdealWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::IdealWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::IdealWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): bool ns3::IdealWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Ipv4AddressChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv4AddressValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Address const &', 'value')])
return
def register_Ns3Ipv4MaskChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')])
return
def register_Ns3Ipv4MaskValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Mask const &', 'value')])
return
def register_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_Ns3ItuR1411LosPropagationLossModel_methods(root_module, cls):
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): ns3::ItuR1411LosPropagationLossModel::ItuR1411LosPropagationLossModel() [constructor]
cls.add_constructor([])
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::ItuR1411LosPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): void ns3::ItuR1411LosPropagationLossModel::SetFrequency(double freq) [member function]
cls.add_method('SetFrequency',
'void',
[param('double', 'freq')])
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): double ns3::ItuR1411LosPropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): double ns3::ItuR1411LosPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3ItuR1411NlosOverRooftopPropagationLossModel_methods(root_module, cls):
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): ns3::ItuR1411NlosOverRooftopPropagationLossModel::ItuR1411NlosOverRooftopPropagationLossModel() [constructor]
cls.add_constructor([])
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::ItuR1411NlosOverRooftopPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): void ns3::ItuR1411NlosOverRooftopPropagationLossModel::SetFrequency(double freq) [member function]
cls.add_method('SetFrequency',
'void',
[param('double', 'freq')])
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): double ns3::ItuR1411NlosOverRooftopPropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): double ns3::ItuR1411NlosOverRooftopPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3JakesProcess_methods(root_module, cls):
## jakes-process.h (module 'propagation'): ns3::JakesProcess::JakesProcess(ns3::JakesProcess const & arg0) [copy constructor]
cls.add_constructor([param('ns3::JakesProcess const &', 'arg0')])
## jakes-process.h (module 'propagation'): ns3::JakesProcess::JakesProcess() [constructor]
cls.add_constructor([])
## jakes-process.h (module 'propagation'): double ns3::JakesProcess::GetChannelGainDb() const [member function]
cls.add_method('GetChannelGainDb',
'double',
[],
is_const=True)
## jakes-process.h (module 'propagation'): std::complex<double> ns3::JakesProcess::GetComplexGain() const [member function]
cls.add_method('GetComplexGain',
'std::complex< double >',
[],
is_const=True)
## jakes-process.h (module 'propagation'): static ns3::TypeId ns3::JakesProcess::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3JakesPropagationLossModel_methods(root_module, cls):
## jakes-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::JakesPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## jakes-propagation-loss-model.h (module 'propagation'): ns3::JakesPropagationLossModel::JakesPropagationLossModel() [constructor]
cls.add_constructor([])
## jakes-propagation-loss-model.h (module 'propagation'): double ns3::JakesPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Kun2600MhzPropagationLossModel_methods(root_module, cls):
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): ns3::Kun2600MhzPropagationLossModel::Kun2600MhzPropagationLossModel() [constructor]
cls.add_constructor([])
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::Kun2600MhzPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): double ns3::Kun2600MhzPropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): double ns3::Kun2600MhzPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3LogDistancePropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::LogDistancePropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::LogDistancePropagationLossModel::LogDistancePropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::LogDistancePropagationLossModel::SetPathLossExponent(double n) [member function]
cls.add_method('SetPathLossExponent',
'void',
[param('double', 'n')])
## propagation-loss-model.h (module 'propagation'): double ns3::LogDistancePropagationLossModel::GetPathLossExponent() const [member function]
cls.add_method('GetPathLossExponent',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): void ns3::LogDistancePropagationLossModel::SetReference(double referenceDistance, double referenceLoss) [member function]
cls.add_method('SetReference',
'void',
[param('double', 'referenceDistance'), param('double', 'referenceLoss')])
## propagation-loss-model.h (module 'propagation'): double ns3::LogDistancePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', 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_Ns3MacLow_methods(root_module, cls):
## mac-low.h (module 'wifi'): ns3::MacLow::MacLow(ns3::MacLow const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLow const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLow::MacLow() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::CalculateTransmissionTime(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const * hdr, ns3::MacLowTransmissionParameters const & parameters) const [member function]
cls.add_method('CalculateTransmissionTime',
'ns3::Time',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr'), param('ns3::MacLowTransmissionParameters const &', 'parameters')],
is_const=True)
## mac-low.h (module 'wifi'): void ns3::MacLow::CreateBlockAckAgreement(ns3::MgtAddBaResponseHeader const * respHdr, ns3::Mac48Address originator, uint16_t startingSeq) [member function]
cls.add_method('CreateBlockAckAgreement',
'void',
[param('ns3::MgtAddBaResponseHeader const *', 'respHdr'), param('ns3::Mac48Address', 'originator'), param('uint16_t', 'startingSeq')])
## mac-low.h (module 'wifi'): void ns3::MacLow::DestroyBlockAckAgreement(ns3::Mac48Address originator, uint8_t tid) [member function]
cls.add_method('DestroyBlockAckAgreement',
'void',
[param('ns3::Mac48Address', 'originator'), param('uint8_t', 'tid')])
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetAckTimeout() const [member function]
cls.add_method('GetAckTimeout',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Mac48Address ns3::MacLow::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Mac48Address',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetBasicBlockAckTimeout() const [member function]
cls.add_method('GetBasicBlockAckTimeout',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Mac48Address ns3::MacLow::GetBssid() const [member function]
cls.add_method('GetBssid',
'ns3::Mac48Address',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetCompressedBlockAckTimeout() const [member function]
cls.add_method('GetCompressedBlockAckTimeout',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetCtsTimeout() const [member function]
cls.add_method('GetCtsTimeout',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetPifs() const [member function]
cls.add_method('GetPifs',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetSifs() const [member function]
cls.add_method('GetSifs',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetSlotTime() const [member function]
cls.add_method('GetSlotTime',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): void ns3::MacLow::NotifySwitchingStartNow(ns3::Time duration) [member function]
cls.add_method('NotifySwitchingStartNow',
'void',
[param('ns3::Time', 'duration')])
## mac-low.h (module 'wifi'): void ns3::MacLow::ReceiveError(ns3::Ptr<ns3::Packet const> packet, double rxSnr) [member function]
cls.add_method('ReceiveError',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'rxSnr')])
## mac-low.h (module 'wifi'): void ns3::MacLow::ReceiveOk(ns3::Ptr<ns3::Packet> packet, double rxSnr, ns3::WifiMode txMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('ReceiveOk',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode'), param('ns3::WifiPreamble', 'preamble')])
## mac-low.h (module 'wifi'): void ns3::MacLow::RegisterBlockAckListenerForAc(ns3::AcIndex ac, ns3::MacLowBlockAckEventListener * listener) [member function]
cls.add_method('RegisterBlockAckListenerForAc',
'void',
[param('ns3::AcIndex', 'ac'), param('ns3::MacLowBlockAckEventListener *', 'listener')])
## mac-low.h (module 'wifi'): void ns3::MacLow::RegisterDcfListener(ns3::MacLowDcfListener * listener) [member function]
cls.add_method('RegisterDcfListener',
'void',
[param('ns3::MacLowDcfListener *', 'listener')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetAckTimeout(ns3::Time ackTimeout) [member function]
cls.add_method('SetAckTimeout',
'void',
[param('ns3::Time', 'ackTimeout')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetAddress(ns3::Mac48Address ad) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'ad')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetBasicBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetBssid(ns3::Mac48Address ad) [member function]
cls.add_method('SetBssid',
'void',
[param('ns3::Mac48Address', 'ad')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetCompressedBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetCtsTimeout(ns3::Time ctsTimeout) [member function]
cls.add_method('SetCtsTimeout',
'void',
[param('ns3::Time', 'ctsTimeout')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetPifs(ns3::Time pifs) [member function]
cls.add_method('SetPifs',
'void',
[param('ns3::Time', 'pifs')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetPromisc() [member function]
cls.add_method('SetPromisc',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetRxCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::WifiMacHeader const*, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetRxCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::WifiMacHeader const *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetSifs(ns3::Time sifs) [member function]
cls.add_method('SetSifs',
'void',
[param('ns3::Time', 'sifs')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetSlotTime(ns3::Time slotTime) [member function]
cls.add_method('SetSlotTime',
'void',
[param('ns3::Time', 'slotTime')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> manager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'manager')])
## mac-low.h (module 'wifi'): void ns3::MacLow::StartTransmission(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const * hdr, ns3::MacLowTransmissionParameters parameters, ns3::MacLowTransmissionListener * listener) [member function]
cls.add_method('StartTransmission',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr'), param('ns3::MacLowTransmissionParameters', 'parameters'), param('ns3::MacLowTransmissionListener *', 'listener')])
## mac-low.h (module 'wifi'): void ns3::MacLow::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3MatrixPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::MatrixPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::MatrixPropagationLossModel::MatrixPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::MatrixPropagationLossModel::SetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, double loss, bool symmetric=true) [member function]
cls.add_method('SetLoss',
'void',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('double', 'loss'), param('bool', 'symmetric', default_value='true')])
## propagation-loss-model.h (module 'propagation'): void ns3::MatrixPropagationLossModel::SetDefaultLoss(double arg0) [member function]
cls.add_method('SetDefaultLoss',
'void',
[param('double', 'arg0')])
## propagation-loss-model.h (module 'propagation'): double ns3::MatrixPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3MgtBeaconHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtBeaconHeader::MgtBeaconHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): ns3::MgtBeaconHeader::MgtBeaconHeader(ns3::MgtBeaconHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtBeaconHeader const &', 'arg0')])
return
def register_Ns3MinstrelWifiManager_methods(root_module, cls):
## minstrel-wifi-manager.h (module 'wifi'): ns3::MinstrelWifiManager::MinstrelWifiManager(ns3::MinstrelWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MinstrelWifiManager const &', 'arg0')])
## minstrel-wifi-manager.h (module 'wifi'): ns3::MinstrelWifiManager::MinstrelWifiManager() [constructor]
cls.add_constructor([])
## minstrel-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::MinstrelWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetupPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::MinstrelWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::MinstrelWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::MinstrelWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): bool ns3::MinstrelWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
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'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr<ns3::MobilityModel const> 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<ns3::MobilityModel const> 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'): 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_Ns3MsduAggregator_methods(root_module, cls):
## msdu-aggregator.h (module 'wifi'): ns3::MsduAggregator::MsduAggregator() [constructor]
cls.add_constructor([])
## msdu-aggregator.h (module 'wifi'): ns3::MsduAggregator::MsduAggregator(ns3::MsduAggregator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MsduAggregator const &', 'arg0')])
## msdu-aggregator.h (module 'wifi'): bool ns3::MsduAggregator::Aggregate(ns3::Ptr<ns3::Packet const> packet, ns3::Ptr<ns3::Packet> aggregatedPacket, ns3::Mac48Address src, ns3::Mac48Address dest) [member function]
cls.add_method('Aggregate',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket'), param('ns3::Mac48Address', 'src'), param('ns3::Mac48Address', 'dest')],
is_pure_virtual=True, is_virtual=True)
## msdu-aggregator.h (module 'wifi'): static std::list<std::pair<ns3::Ptr<ns3::Packet>, ns3::AmsduSubframeHeader>, std::allocator<std::pair<ns3::Ptr<ns3::Packet>, ns3::AmsduSubframeHeader> > > ns3::MsduAggregator::Deaggregate(ns3::Ptr<ns3::Packet> aggregatedPacket) [member function]
cls.add_method('Deaggregate',
'std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::AmsduSubframeHeader > >',
[param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket')],
is_static=True)
## msdu-aggregator.h (module 'wifi'): static ns3::TypeId ns3::MsduAggregator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3NakagamiPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::NakagamiPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::NakagamiPropagationLossModel::NakagamiPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): double ns3::NakagamiPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=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<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3NistErrorRateModel_methods(root_module, cls):
## nist-error-rate-model.h (module 'wifi'): ns3::NistErrorRateModel::NistErrorRateModel(ns3::NistErrorRateModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NistErrorRateModel const &', 'arg0')])
## nist-error-rate-model.h (module 'wifi'): ns3::NistErrorRateModel::NistErrorRateModel() [constructor]
cls.add_constructor([])
## nist-error-rate-model.h (module 'wifi'): double ns3::NistErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function]
cls.add_method('GetChunkSuccessRate',
'double',
[param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')],
is_const=True, is_virtual=True)
## nist-error-rate-model.h (module 'wifi'): static ns3::TypeId ns3::NistErrorRateModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3NixVector_methods(root_module, cls):
cls.add_output_stream_operator()
## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor]
cls.add_constructor([])
## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor]
cls.add_constructor([param('ns3::NixVector const &', 'o')])
## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function]
cls.add_method('AddNeighborIndex',
'void',
[param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function]
cls.add_method('BitCount',
'uint32_t',
[param('uint32_t', 'numberOfNeighbors')],
is_const=True)
## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint32_t const *', 'buffer'), param('uint32_t', 'size')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function]
cls.add_method('ExtractNeighborIndex',
'uint32_t',
[param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function]
cls.add_method('GetRemainingBits',
'uint32_t',
[])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3Node_methods(root_module, cls):
## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Node const &', 'arg0')])
## node.h (module 'network'): ns3::Node::Node() [constructor]
cls.add_constructor([])
## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor]
cls.add_constructor([param('uint32_t', 'systemId')])
## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('AddApplication',
'uint32_t',
[param('ns3::Ptr< ns3::Application >', 'application')])
## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddDevice',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function]
cls.add_method('ChecksumEnabled',
'bool',
[],
is_static=True)
## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function]
cls.add_method('GetApplication',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function]
cls.add_method('GetNApplications',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('RegisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function]
cls.add_method('RegisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')])
## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('UnregisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function]
cls.add_method('UnregisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')])
## node.h (module 'network'): void ns3::Node::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## node.h (module 'network'): void ns3::Node::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_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_Ns3OkumuraHataPropagationLossModel_methods(root_module, cls):
## okumura-hata-propagation-loss-model.h (module 'propagation'): ns3::OkumuraHataPropagationLossModel::OkumuraHataPropagationLossModel() [constructor]
cls.add_constructor([])
## okumura-hata-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::OkumuraHataPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## okumura-hata-propagation-loss-model.h (module 'propagation'): double ns3::OkumuraHataPropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## okumura-hata-propagation-loss-model.h (module 'propagation'): double ns3::OkumuraHataPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3OnoeWifiManager_methods(root_module, cls):
## onoe-wifi-manager.h (module 'wifi'): ns3::OnoeWifiManager::OnoeWifiManager(ns3::OnoeWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OnoeWifiManager const &', 'arg0')])
## onoe-wifi-manager.h (module 'wifi'): ns3::OnoeWifiManager::OnoeWifiManager() [constructor]
cls.add_constructor([])
## onoe-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::OnoeWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## onoe-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::OnoeWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::OnoeWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::OnoeWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): bool ns3::OnoeWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3OutputStreamWrapper_methods(root_module, cls):
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor]
cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor]
cls.add_constructor([param('std::ostream *', 'os')])
## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function]
cls.add_method('GetStream',
'std::ostream *',
[])
return
def register_Ns3Packet_methods(root_module, cls):
cls.add_output_stream_operator()
## packet.h (module 'network'): ns3::Packet::Packet() [constructor]
cls.add_constructor([])
## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor]
cls.add_constructor([param('ns3::Packet const &', 'o')])
## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor]
cls.add_constructor([param('uint32_t', 'size')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddByteTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header')])
## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddPacketTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer')])
## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function]
cls.add_method('EnablePrinting',
'void',
[],
is_static=True)
## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function]
cls.add_method('FindFirstMatchingByteTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function]
cls.add_method('GetByteTagIterator',
'ns3::ByteTagIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function]
cls.add_method('GetNixVector',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function]
cls.add_method('GetPacketTagIterator',
'ns3::PacketTagIterator',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
deprecated=True, is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function]
cls.add_method('PeekHeader',
'uint32_t',
[param('ns3::Header &', 'header')],
is_const=True)
## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function]
cls.add_method('PeekPacketTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('PeekTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function]
cls.add_method('PrintByteTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function]
cls.add_method('PrintPacketTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function]
cls.add_method('RemoveAllByteTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function]
cls.add_method('RemoveAllPacketTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function]
cls.add_method('RemoveHeader',
'uint32_t',
[param('ns3::Header &', 'header')])
## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function]
cls.add_method('RemovePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('RemoveTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function]
cls.add_method('SetNixVector',
'void',
[param('ns3::Ptr< ns3::NixVector >', 'arg0')])
return
def register_Ns3RandomVariableChecker_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::RandomVariableChecker::RandomVariableChecker() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::RandomVariableChecker::RandomVariableChecker(ns3::RandomVariableChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RandomVariableChecker const &', 'arg0')])
return
def register_Ns3RandomVariableValue_methods(root_module, cls):
## random-variable.h (module 'core'): ns3::RandomVariableValue::RandomVariableValue() [constructor]
cls.add_constructor([])
## random-variable.h (module 'core'): ns3::RandomVariableValue::RandomVariableValue(ns3::RandomVariableValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RandomVariableValue const &', 'arg0')])
## random-variable.h (module 'core'): ns3::RandomVariableValue::RandomVariableValue(ns3::RandomVariable const & value) [constructor]
cls.add_constructor([param('ns3::RandomVariable const &', 'value')])
## random-variable.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::RandomVariableValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## random-variable.h (module 'core'): bool ns3::RandomVariableValue::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)
## random-variable.h (module 'core'): ns3::RandomVariable ns3::RandomVariableValue::Get() const [member function]
cls.add_method('Get',
'ns3::RandomVariable',
[],
is_const=True)
## random-variable.h (module 'core'): std::string ns3::RandomVariableValue::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)
## random-variable.h (module 'core'): void ns3::RandomVariableValue::Set(ns3::RandomVariable const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::RandomVariable const &', 'value')])
return
def register_Ns3RegularWifiMac_methods(root_module, cls):
## regular-wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::RegularWifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## regular-wifi-mac.h (module 'wifi'): ns3::RegularWifiMac::RegularWifiMac() [constructor]
cls.add_constructor([])
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetSlot(ns3::Time slotTime) [member function]
cls.add_method('SetSlot',
'void',
[param('ns3::Time', 'slotTime')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetSifs(ns3::Time sifs) [member function]
cls.add_method('SetSifs',
'void',
[param('ns3::Time', 'sifs')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function]
cls.add_method('SetEifsNoDifs',
'void',
[param('ns3::Time', 'eifsNoDifs')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetPifs(ns3::Time pifs) [member function]
cls.add_method('SetPifs',
'void',
[param('ns3::Time', 'pifs')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function]
cls.add_method('SetCtsTimeout',
'void',
[param('ns3::Time', 'ctsTimeout')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function]
cls.add_method('SetAckTimeout',
'void',
[param('ns3::Time', 'ackTimeout')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetPifs() const [member function]
cls.add_method('GetPifs',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetSifs() const [member function]
cls.add_method('GetSifs',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetSlot() const [member function]
cls.add_method('GetSlot',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetEifsNoDifs() const [member function]
cls.add_method('GetEifsNoDifs',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetCtsTimeout() const [member function]
cls.add_method('GetCtsTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetAckTimeout() const [member function]
cls.add_method('GetAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::RegularWifiMac::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Mac48Address',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Ssid ns3::RegularWifiMac::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetAddress(ns3::Mac48Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'address')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetBssid(ns3::Mac48Address bssid) [member function]
cls.add_method('SetBssid',
'void',
[param('ns3::Mac48Address', 'bssid')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::RegularWifiMac::GetBssid() const [member function]
cls.add_method('GetBssid',
'ns3::Mac48Address',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetPromisc() [member function]
cls.add_method('SetPromisc',
'void',
[],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): bool ns3::RegularWifiMac::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_pure_virtual=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetWifiPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Ptr<ns3::WifiPhy> ns3::RegularWifiMac::GetWifiPhy() const [member function]
cls.add_method('GetWifiPhy',
'ns3::Ptr< ns3::WifiPhy >',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Ptr<ns3::WifiRemoteStationManager> ns3::RegularWifiMac::GetWifiRemoteStationManager() const [member function]
cls.add_method('GetWifiRemoteStationManager',
'ns3::Ptr< ns3::WifiRemoteStationManager >',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function]
cls.add_method('SetForwardUpCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function]
cls.add_method('SetLinkUpCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function]
cls.add_method('SetLinkDownCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetBasicBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetBasicBlockAckTimeout() const [member function]
cls.add_method('GetBasicBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetCompressedBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetCompressedBlockAckTimeout() const [member function]
cls.add_method('GetCompressedBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('FinishConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetTypeOfStation(ns3::TypeOfStation type) [member function]
cls.add_method('SetTypeOfStation',
'void',
[param('ns3::TypeOfStation', 'type')],
visibility='protected')
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::TxOk(ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('TxOk',
'void',
[param('ns3::WifiMacHeader const &', 'hdr')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::TxFailed(ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('TxFailed',
'void',
[param('ns3::WifiMacHeader const &', 'hdr')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::ForwardUp(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address from, ns3::Mac48Address to) [member function]
cls.add_method('ForwardUp',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address', 'from'), param('ns3::Mac48Address', 'to')],
visibility='protected')
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::DeaggregateAmsduAndForward(ns3::Ptr<ns3::Packet> aggregatedPacket, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('DeaggregateAmsduAndForward',
'void',
[param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SendAddBaResponse(ns3::MgtAddBaRequestHeader const * reqHdr, ns3::Mac48Address originator) [member function]
cls.add_method('SendAddBaResponse',
'void',
[param('ns3::MgtAddBaRequestHeader const *', 'reqHdr'), param('ns3::Mac48Address', 'originator')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetQosSupported(bool enable) [member function]
cls.add_method('SetQosSupported',
'void',
[param('bool', 'enable')],
visibility='protected')
## regular-wifi-mac.h (module 'wifi'): bool ns3::RegularWifiMac::GetQosSupported() const [member function]
cls.add_method('GetQosSupported',
'bool',
[],
is_const=True, visibility='protected')
return
def register_Ns3RraaWifiManager_methods(root_module, cls):
## rraa-wifi-manager.h (module 'wifi'): ns3::RraaWifiManager::RraaWifiManager(ns3::RraaWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RraaWifiManager const &', 'arg0')])
## rraa-wifi-manager.h (module 'wifi'): ns3::RraaWifiManager::RraaWifiManager() [constructor]
cls.add_constructor([])
## rraa-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::RraaWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## rraa-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::RraaWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::RraaWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::RraaWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): bool ns3::RraaWifiManager::DoNeedRts(ns3::WifiRemoteStation * st, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRts',
'bool',
[param('ns3::WifiRemoteStation *', 'st'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): bool ns3::RraaWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Ssid_methods(root_module, cls):
cls.add_output_stream_operator()
## ssid.h (module 'wifi'): ns3::Ssid::Ssid(ns3::Ssid const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ssid const &', 'arg0')])
## ssid.h (module 'wifi'): ns3::Ssid::Ssid() [constructor]
cls.add_constructor([])
## ssid.h (module 'wifi'): ns3::Ssid::Ssid(std::string s) [constructor]
cls.add_constructor([param('std::string', 's')])
## ssid.h (module 'wifi'): ns3::Ssid::Ssid(char const * ssid, uint8_t length) [constructor]
cls.add_constructor([param('char const *', 'ssid'), param('uint8_t', 'length')])
## ssid.h (module 'wifi'): uint8_t ns3::Ssid::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_virtual=True)
## ssid.h (module 'wifi'): ns3::WifiInformationElementId ns3::Ssid::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): uint8_t ns3::Ssid::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): bool ns3::Ssid::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ssid.h (module 'wifi'): bool ns3::Ssid::IsEqual(ns3::Ssid const & o) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ssid const &', 'o')],
is_const=True)
## ssid.h (module 'wifi'): char * ns3::Ssid::PeekString() const [member function]
cls.add_method('PeekString',
'char *',
[],
is_const=True)
## ssid.h (module 'wifi'): void ns3::Ssid::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
return
def register_Ns3SsidChecker_methods(root_module, cls):
## ssid.h (module 'wifi'): ns3::SsidChecker::SsidChecker() [constructor]
cls.add_constructor([])
## ssid.h (module 'wifi'): ns3::SsidChecker::SsidChecker(ns3::SsidChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SsidChecker const &', 'arg0')])
return
def register_Ns3SsidValue_methods(root_module, cls):
## ssid.h (module 'wifi'): ns3::SsidValue::SsidValue() [constructor]
cls.add_constructor([])
## ssid.h (module 'wifi'): ns3::SsidValue::SsidValue(ns3::SsidValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SsidValue const &', 'arg0')])
## ssid.h (module 'wifi'): ns3::SsidValue::SsidValue(ns3::Ssid const & value) [constructor]
cls.add_constructor([param('ns3::Ssid const &', 'value')])
## ssid.h (module 'wifi'): ns3::Ptr<ns3::AttributeValue> ns3::SsidValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): bool ns3::SsidValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ssid.h (module 'wifi'): ns3::Ssid ns3::SsidValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ssid',
[],
is_const=True)
## ssid.h (module 'wifi'): std::string ns3::SsidValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): void ns3::SsidValue::Set(ns3::Ssid const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ssid const &', 'value')])
return
def register_Ns3StaWifiMac_methods(root_module, cls):
## sta-wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::StaWifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## sta-wifi-mac.h (module 'wifi'): ns3::StaWifiMac::StaWifiMac() [constructor]
cls.add_constructor([])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_virtual=True)
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::SetMaxMissedBeacons(uint32_t missed) [member function]
cls.add_method('SetMaxMissedBeacons',
'void',
[param('uint32_t', 'missed')])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::SetProbeRequestTimeout(ns3::Time timeout) [member function]
cls.add_method('SetProbeRequestTimeout',
'void',
[param('ns3::Time', 'timeout')])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::SetAssocRequestTimeout(ns3::Time timeout) [member function]
cls.add_method('SetAssocRequestTimeout',
'void',
[param('ns3::Time', 'timeout')])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::StartActiveAssociation() [member function]
cls.add_method('StartActiveAssociation',
'void',
[])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='private', is_virtual=True)
return
def register_Ns3SupportedRates_methods(root_module, cls):
cls.add_output_stream_operator()
## supported-rates.h (module 'wifi'): ns3::SupportedRates::SupportedRates(ns3::SupportedRates const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SupportedRates const &', 'arg0')])
## supported-rates.h (module 'wifi'): ns3::SupportedRates::SupportedRates() [constructor]
cls.add_constructor([])
## supported-rates.h (module 'wifi'): void ns3::SupportedRates::AddSupportedRate(uint32_t bs) [member function]
cls.add_method('AddSupportedRate',
'void',
[param('uint32_t', 'bs')])
## supported-rates.h (module 'wifi'): uint8_t ns3::SupportedRates::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_virtual=True)
## supported-rates.h (module 'wifi'): ns3::WifiInformationElementId ns3::SupportedRates::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): uint8_t ns3::SupportedRates::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): uint8_t ns3::SupportedRates::GetNRates() const [member function]
cls.add_method('GetNRates',
'uint8_t',
[],
is_const=True)
## supported-rates.h (module 'wifi'): uint32_t ns3::SupportedRates::GetRate(uint8_t i) const [member function]
cls.add_method('GetRate',
'uint32_t',
[param('uint8_t', 'i')],
is_const=True)
## supported-rates.h (module 'wifi'): bool ns3::SupportedRates::IsBasicRate(uint32_t bs) const [member function]
cls.add_method('IsBasicRate',
'bool',
[param('uint32_t', 'bs')],
is_const=True)
## supported-rates.h (module 'wifi'): bool ns3::SupportedRates::IsSupportedRate(uint32_t bs) const [member function]
cls.add_method('IsSupportedRate',
'bool',
[param('uint32_t', 'bs')],
is_const=True)
## supported-rates.h (module 'wifi'): void ns3::SupportedRates::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): void ns3::SupportedRates::SetBasicRate(uint32_t bs) [member function]
cls.add_method('SetBasicRate',
'void',
[param('uint32_t', 'bs')])
## supported-rates.h (module 'wifi'): ns3::SupportedRates::extended [variable]
cls.add_instance_attribute('extended', 'ns3::ExtendedSupportedRatesIE', is_const=False)
return
def register_Ns3TimeChecker_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker(ns3::TimeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeChecker const &', 'arg0')])
return
def register_Ns3TimeValue_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeValue const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor]
cls.add_constructor([param('ns3::Time const &', 'value')])
## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function]
cls.add_method('Get',
'ns3::Time',
[],
is_const=True)
## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Time const &', 'value')])
return
def register_Ns3TypeIdChecker_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')])
return
def register_Ns3TypeIdValue_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor]
cls.add_constructor([param('ns3::TypeId const &', 'value')])
## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function]
cls.add_method('Get',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::TypeId const &', 'value')])
return
def register_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_Ns3WifiChannel_methods(root_module, cls):
## wifi-channel.h (module 'wifi'): ns3::WifiChannel::WifiChannel() [constructor]
cls.add_constructor([])
## wifi-channel.h (module 'wifi'): ns3::WifiChannel::WifiChannel(ns3::WifiChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiChannel const &', 'arg0')])
## wifi-channel.h (module 'wifi'): static ns3::TypeId ns3::WifiChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3WifiModeChecker_methods(root_module, cls):
## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker::WifiModeChecker() [constructor]
cls.add_constructor([])
## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker::WifiModeChecker(ns3::WifiModeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiModeChecker const &', 'arg0')])
return
def register_Ns3WifiModeValue_methods(root_module, cls):
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue() [constructor]
cls.add_constructor([])
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue(ns3::WifiModeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiModeValue const &', 'arg0')])
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue(ns3::WifiMode const & value) [constructor]
cls.add_constructor([param('ns3::WifiMode const &', 'value')])
## wifi-mode.h (module 'wifi'): ns3::Ptr<ns3::AttributeValue> ns3::WifiModeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## wifi-mode.h (module 'wifi'): bool ns3::WifiModeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## wifi-mode.h (module 'wifi'): ns3::WifiMode ns3::WifiModeValue::Get() const [member function]
cls.add_method('Get',
'ns3::WifiMode',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): std::string ns3::WifiModeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## wifi-mode.h (module 'wifi'): void ns3::WifiModeValue::Set(ns3::WifiMode const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::WifiMode const &', 'value')])
return
def register_Ns3WifiNetDevice_methods(root_module, cls):
## wifi-net-device.h (module 'wifi'): ns3::WifiNetDevice::WifiNetDevice(ns3::WifiNetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiNetDevice const &', 'arg0')])
## wifi-net-device.h (module 'wifi'): ns3::WifiNetDevice::WifiNetDevice() [constructor]
cls.add_constructor([])
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::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)
## wifi-net-device.h (module 'wifi'): ns3::Address ns3::WifiNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Address ns3::WifiNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::Channel> ns3::WifiNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): uint32_t ns3::WifiNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::WifiMac> ns3::WifiNetDevice::GetMac() const [member function]
cls.add_method('GetMac',
'ns3::Ptr< ns3::WifiMac >',
[],
is_const=True)
## wifi-net-device.h (module 'wifi'): uint16_t ns3::WifiNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Address ns3::WifiNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Address ns3::WifiNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::Node> ns3::WifiNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::WifiPhy> ns3::WifiNetDevice::GetPhy() const [member function]
cls.add_method('GetPhy',
'ns3::Ptr< ns3::WifiPhy >',
[],
is_const=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::WifiRemoteStationManager> ns3::WifiNetDevice::GetRemoteStationManager() const [member function]
cls.add_method('GetRemoteStationManager',
'ns3::Ptr< ns3::WifiRemoteStationManager >',
[],
is_const=True)
## wifi-net-device.h (module 'wifi'): static ns3::TypeId ns3::WifiNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::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)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::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)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetMac(ns3::Ptr<ns3::WifiMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::WifiMac >', 'mac')])
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')])
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::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)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> manager) [member function]
cls.add_method('SetRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'manager')])
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3YansErrorRateModel_methods(root_module, cls):
## yans-error-rate-model.h (module 'wifi'): ns3::YansErrorRateModel::YansErrorRateModel(ns3::YansErrorRateModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::YansErrorRateModel const &', 'arg0')])
## yans-error-rate-model.h (module 'wifi'): ns3::YansErrorRateModel::YansErrorRateModel() [constructor]
cls.add_constructor([])
## yans-error-rate-model.h (module 'wifi'): double ns3::YansErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function]
cls.add_method('GetChunkSuccessRate',
'double',
[param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')],
is_const=True, is_virtual=True)
## yans-error-rate-model.h (module 'wifi'): static ns3::TypeId ns3::YansErrorRateModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3YansWifiChannel_methods(root_module, cls):
## yans-wifi-channel.h (module 'wifi'): static ns3::TypeId ns3::YansWifiChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## yans-wifi-channel.h (module 'wifi'): ns3::YansWifiChannel::YansWifiChannel() [constructor]
cls.add_constructor([])
## yans-wifi-channel.h (module 'wifi'): uint32_t ns3::YansWifiChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## yans-wifi-channel.h (module 'wifi'): ns3::Ptr<ns3::NetDevice> ns3::YansWifiChannel::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)
## yans-wifi-channel.h (module 'wifi'): void ns3::YansWifiChannel::Add(ns3::Ptr<ns3::YansWifiPhy> phy) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::YansWifiPhy >', 'phy')])
## yans-wifi-channel.h (module 'wifi'): void ns3::YansWifiChannel::SetPropagationLossModel(ns3::Ptr<ns3::PropagationLossModel> loss) [member function]
cls.add_method('SetPropagationLossModel',
'void',
[param('ns3::Ptr< ns3::PropagationLossModel >', 'loss')])
## yans-wifi-channel.h (module 'wifi'): void ns3::YansWifiChannel::SetPropagationDelayModel(ns3::Ptr<ns3::PropagationDelayModel> delay) [member function]
cls.add_method('SetPropagationDelayModel',
'void',
[param('ns3::Ptr< ns3::PropagationDelayModel >', 'delay')])
## yans-wifi-channel.h (module 'wifi'): void ns3::YansWifiChannel::Send(ns3::Ptr<ns3::YansWifiPhy> sender, ns3::Ptr<ns3::Packet const> packet, double txPowerDbm, ns3::WifiMode wifiMode, ns3::WifiPreamble preamble) const [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::YansWifiPhy >', 'sender'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'txPowerDbm'), param('ns3::WifiMode', 'wifiMode'), param('ns3::WifiPreamble', 'preamble')],
is_const=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_Ns3AdhocWifiMac_methods(root_module, cls):
## adhoc-wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::AdhocWifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## adhoc-wifi-mac.h (module 'wifi'): ns3::AdhocWifiMac::AdhocWifiMac() [constructor]
cls.add_constructor([])
## adhoc-wifi-mac.h (module 'wifi'): void ns3::AdhocWifiMac::SetAddress(ns3::Mac48Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'address')],
is_virtual=True)
## adhoc-wifi-mac.h (module 'wifi'): void ns3::AdhocWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function]
cls.add_method('SetLinkUpCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')],
is_virtual=True)
## adhoc-wifi-mac.h (module 'wifi'): void ns3::AdhocWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_virtual=True)
## adhoc-wifi-mac.h (module 'wifi'): void ns3::AdhocWifiMac::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='private', is_virtual=True)
return
def register_Ns3ApWifiMac_methods(root_module, cls):
## ap-wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::ApWifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ap-wifi-mac.h (module 'wifi'): ns3::ApWifiMac::ApWifiMac() [constructor]
cls.add_constructor([])
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function]
cls.add_method('SetLinkUpCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): bool ns3::ApWifiMac::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::SetAddress(ns3::Mac48Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'address')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::SetBeaconInterval(ns3::Time interval) [member function]
cls.add_method('SetBeaconInterval',
'void',
[param('ns3::Time', 'interval')])
## ap-wifi-mac.h (module 'wifi'): ns3::Time ns3::ApWifiMac::GetBeaconInterval() const [member function]
cls.add_method('GetBeaconInterval',
'ns3::Time',
[],
is_const=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::StartBeaconing() [member function]
cls.add_method('StartBeaconing',
'void',
[])
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::TxOk(ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('TxOk',
'void',
[param('ns3::WifiMacHeader const &', 'hdr')],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::TxFailed(ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('TxFailed',
'void',
[param('ns3::WifiMacHeader const &', 'hdr')],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::DeaggregateAmsduAndForward(ns3::Ptr<ns3::Packet> aggregatedPacket, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('DeaggregateAmsduAndForward',
'void',
[param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3DcaTxop_methods(root_module, cls):
## dca-txop.h (module 'wifi'): static ns3::TypeId ns3::DcaTxop::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dca-txop.h (module 'wifi'): ns3::DcaTxop::DcaTxop() [constructor]
cls.add_constructor([])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetLow(ns3::Ptr<ns3::MacLow> low) [member function]
cls.add_method('SetLow',
'void',
[param('ns3::Ptr< ns3::MacLow >', 'low')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetManager(ns3::DcfManager * manager) [member function]
cls.add_method('SetManager',
'void',
[param('ns3::DcfManager *', 'manager')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> remoteManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'remoteManager')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetTxOkCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetTxOkCallback',
'void',
[param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetTxFailedCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetTxFailedCallback',
'void',
[param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## dca-txop.h (module 'wifi'): ns3::Ptr<ns3::WifiMacQueue> ns3::DcaTxop::GetQueue() const [member function]
cls.add_method('GetQueue',
'ns3::Ptr< ns3::WifiMacQueue >',
[],
is_const=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetMinCw(uint32_t minCw) [member function]
cls.add_method('SetMinCw',
'void',
[param('uint32_t', 'minCw')],
is_virtual=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetMaxCw(uint32_t maxCw) [member function]
cls.add_method('SetMaxCw',
'void',
[param('uint32_t', 'maxCw')],
is_virtual=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetAifsn(uint32_t aifsn) [member function]
cls.add_method('SetAifsn',
'void',
[param('uint32_t', 'aifsn')],
is_virtual=True)
## dca-txop.h (module 'wifi'): uint32_t ns3::DcaTxop::GetMinCw() const [member function]
cls.add_method('GetMinCw',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dca-txop.h (module 'wifi'): uint32_t ns3::DcaTxop::GetMaxCw() const [member function]
cls.add_method('GetMaxCw',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dca-txop.h (module 'wifi'): uint32_t ns3::DcaTxop::GetAifsn() const [member function]
cls.add_method('GetAifsn',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::Queue(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('Queue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='private', is_virtual=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_functions(root_module):
module = root_module
## ssid.h (module 'wifi'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeSsidChecker() [free function]
module.add_function('MakeSsidChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## wifi-mode.h (module 'wifi'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeWifiModeChecker() [free function]
module.add_function('MakeWifiModeChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## qos-utils.h (module 'wifi'): extern uint8_t ns3::QosUtilsGetTidForPacket(ns3::Ptr<ns3::Packet const> packet) [free function]
module.add_function('QosUtilsGetTidForPacket',
'uint8_t',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## qos-utils.h (module 'wifi'): extern bool ns3::QosUtilsIsOldPacket(uint16_t startingSeq, uint16_t seqNumber) [free function]
module.add_function('QosUtilsIsOldPacket',
'bool',
[param('uint16_t', 'startingSeq'), param('uint16_t', 'seqNumber')])
## qos-utils.h (module 'wifi'): extern uint32_t ns3::QosUtilsMapSeqControlToUniqueInteger(uint16_t seqControl, uint16_t endSequence) [free function]
module.add_function('QosUtilsMapSeqControlToUniqueInteger',
'uint32_t',
[param('uint16_t', 'seqControl'), param('uint16_t', 'endSequence')])
## qos-utils.h (module 'wifi'): extern ns3::AcIndex ns3::QosUtilsMapTidToAc(uint8_t tid) [free function]
module.add_function('QosUtilsMapTidToAc',
'ns3::AcIndex',
[param('uint8_t', 'tid')])
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), 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_internal(module, root_module):
return
def main():
out = FileCodeSink(sys.stdout)
root_module = module_init()
register_types(root_module)
register_methods(root_module)
register_functions(root_module)
root_module.generate(out)
if __name__ == '__main__':
main()
| gpl-2.0 |
CINPLA/exana | exana/tracking/fields.py | 1 | 32391 | import numpy as np
def spatial_rate_map(x, y, t, spike_train, binsize=0.01, box_xlen=1,
box_ylen=1, mask_unvisited=True, convolve=True,
return_bins=False, smoothing=0.02):
"""Divide a 2D space in bins of size binsize**2, count the number of spikes
in each bin and divide by the time spent in respective bins. The map can
then be convolved with a gaussian kernel of size csize determined by the
smoothing factor, binsize and box_xlen.
Parameters
----------
spike_train : neo.SpikeTrain
x : float
1d vector of x positions
y : float
1d vector of y positions
t : float
1d vector of times at x, y positions
binsize : float
spatial binsize
box_xlen : quantities scalar in m
side length of quadratic box
mask_unvisited: bool
mask bins which has not been visited by nans
convolve : bool
convolve the rate map with a 2D Gaussian kernel
Returns
-------
out : rate map
if return_bins = True
out : rate map, xbins, ybins
"""
if not all([len(var) == len(var2) for var in [x,y,t] for var2 in [x,y,t]]):
raise ValueError('x, y, t must have same number of elements')
if box_xlen < x.max() or box_ylen < y.max():
raise ValueError('box length must be larger or equal to max path length')
from decimal import Decimal as dec
decimals = 1e10
remainderx = dec(float(box_xlen)*decimals) % dec(float(binsize)*decimals)
remaindery = dec(float(box_ylen)*decimals) % dec(float(binsize)*decimals)
if remainderx != 0 or remaindery != 0:
raise ValueError('the remainder should be zero i.e. the ' +
'box length should be an exact multiple ' +
'of the binsize')
# interpolate one extra timepoint
t_ = np.append(t, t[-1] + np.median(np.diff(t)))
spikes_in_bin, _ = np.histogram(spike_train, t_)
time_in_bin = np.diff(t_)
xbins = np.arange(0, box_xlen + binsize, binsize)
ybins = np.arange(0, box_ylen + binsize, binsize)
ix = np.digitize(x, xbins, right=True)
iy = np.digitize(y, ybins, right=True)
spike_pos = np.zeros((xbins.size, ybins.size))
time_pos = np.zeros((xbins.size, ybins.size))
for n in range(len(x)):
spike_pos[ix[n], iy[n]] += spikes_in_bin[n]
time_pos[ix[n], iy[n]] += time_in_bin[n]
# correct for shifting of map
spike_pos = spike_pos[1:, 1:]
time_pos = time_pos[1:, 1:]
with np.errstate(divide='ignore', invalid='ignore'):
rate = np.divide(spike_pos, time_pos)
if convolve:
rate[np.isnan(rate)] = 0. # for convolution
from astropy.convolution import Gaussian2DKernel, convolve_fft
csize = (box_xlen / binsize) * smoothing
kernel = Gaussian2DKernel(csize)
rate = convolve_fft(rate, kernel) # TODO edge correction
if mask_unvisited:
was_in_bin = np.asarray(time_pos, dtype=bool)
rate[np.invert(was_in_bin)] = np.nan
if return_bins:
return rate.T, xbins, ybins
else:
return rate.T
def gridness(rate_map, box_xlen, box_ylen, return_acorr=False,
step_size=0.1, method='iter', return_masked_acorr=False):
'''Calculates gridness of a rate map. Calculates the normalized
autocorrelation (A) of a rate map B where A is given as
A = 1/n\Sum_{x,y}(B - \bar{B})^{2}/\sigma_{B}^{2}. Further, the Pearsson's
product-moment correlation coefficients is calculated between A and A_{rot}
rotated 30 and 60 degrees. Finally the gridness is calculated as the
difference between the minimum of coefficients at 60 degrees and the
maximum of coefficients at 30 degrees i.e. gridness = min(r60) - max(r30).
If the method 'iter' is chosen:
In order to focus the analysis on symmetry of A the the central and the
outer part of the gridness is maximized by increasingly mask A at steps of
``step_size``.
If the method 'puncture' is chosen:
This is the standard way of calculating gridness, by masking the central
autocorrelation bump, in addition to rounding the map. See examples.
Parameters
----------
rate_map : numpy.ndarray
box_xlen : float
side length of quadratic box
step_size : float
step size in masking, only applies to the method "iter"
return_acorr : bool
return autocorrelation map or not
return_masked_acorr : bool
return masked autocorrelation map or not
method : 'iter' or 'puncture'
Returns
-------
out : gridness, (autocorrelation map, masked autocorrelation map)
Examples
--------
>>> from exana.tracking.tools import make_test_grid_rate_map
>>> import matplotlib.pyplot as plt
>>> rate_map, pos = make_test_grid_rate_map()
>>> iter_score = gridness(rate_map, box_xlen=1, box_ylen=1, method='iter')
>>> print('%.2f' % iter_score)
1.39
>>> puncture_score = gridness(rate_map, box_xlen=1, box_ylen=1, method='puncture')
>>> print('%.2f' % puncture_score)
0.96
.. plot::
import matplotlib.pyplot as plt
import numpy as np
from exana.tracking.tools import make_test_grid_rate_map
from exana.tracking import gridness
import matplotlib.pyplot as plt
rate_map, _ = make_test_grid_rate_map()
fig, axs = plt.subplots(2, 2)
g1, acorr, m_acorr1 = gridness(rate_map, box_xlen=1,
box_ylen=1, return_acorr=True,
return_masked_acorr=True,
method='iter')
g2, m_acorr2 = gridness(rate_map, box_xlen=1,
box_ylen=1,
return_masked_acorr=True,
method='puncture')
mats = [rate_map, m_acorr1, acorr, m_acorr2]
titles = ['Rate map', 'Masked acorr "iter", gridness = %.2f' % g1,
'Autocorrelation',
'Masked acorr "puncture", gridness = %.2f' % g2]
for ax, mat, title in zip(axs.ravel(), mats, titles):
ax.imshow(mat)
ax.set_title(title)
plt.tight_layout()
plt.show()
'''
import numpy.ma as ma
from exana.misc.tools import fftcorrelate2d
from exana.tracking.tools import gaussian2D
from scipy.optimize import curve_fit
tmp_map = rate_map.copy()
tmp_map[~np.isfinite(tmp_map)] = 0
acorr = fftcorrelate2d(tmp_map, tmp_map, mode='full', normalize=True)
rows, cols = acorr.shape
b_x = np.linspace(- box_xlen / 2., box_xlen / 2., rows)
b_y = np.linspace(- box_ylen / 2., box_ylen / 2., cols)
B_x, B_y = np.meshgrid(b_x, b_y)
if method == 'iter':
if return_masked_acorr: m_acorrs = []
gridscores = []
for outer in np.arange(box_xlen / 4, box_xlen / 2, step_size):
m_acorr = ma.masked_array(
acorr, mask=np.sqrt(B_x**2 + B_y**2) > outer)
for inner in np.arange(0, box_xlen / 4, step_size):
m_acorr = ma.masked_array(
m_acorr, mask=np.sqrt(B_x**2 + B_y**2) < inner)
r30, r60 = rotate_corr(m_acorr)
gridscores.append(np.min(r60) - np.max(r30))
if return_masked_acorr: m_acorrs.append(m_acorr)
gridscore = max(gridscores)
if return_masked_acorr: m_acorr = m_acorrs[gridscores.index(gridscore)]
elif method == 'puncture':
# round picture edges
_gaussian = lambda pos, a, s: gaussian2D(a, pos[0], pos[1], 0, 0, s).ravel()
p0 = (max(acorr.ravel()), min(box_xlen, box_ylen) / 100)
popt, pcov = curve_fit(_gaussian, (B_x, B_y), acorr.ravel(), p0=p0)
m_acorr = ma.masked_array(
acorr, mask=np.sqrt(B_x**2 + B_y**2) > min(box_xlen, box_ylen) / 2)
m_acorr = ma.masked_array(
m_acorr, mask=np.sqrt(B_x**2 + B_y**2) < popt[1])
r30, r60 = rotate_corr(m_acorr)
gridscore = float(np.min(r60) - np.max(r30))
if return_acorr and return_masked_acorr:
return gridscore, acorr, m_acorr
if return_masked_acorr:
return gridscore, m_acorr
if return_acorr:
return gridscore, acorr # acorrs[grids.index(max(grids))]
else:
return gridscore
def rotate_corr(acorr):
from exana.misc.tools import masked_corrcoef2d
from scipy.ndimage.interpolation import rotate
angles = range(30, 180+30, 30)
corr = []
# Rotate and compute correlation coefficient
for angle in angles:
rot_acorr = rotate(acorr, angle, reshape=False)
corr.append(masked_corrcoef2d(rot_acorr, acorr)[0, 1])
r60 = corr[1::2]
r30 = corr[::2]
return r30, r60
def occupancy_map(x, y, t,
binsize=0.01,
box_xlen=1,
box_ylen=1,
mask_unvisited=True,
convolve=True,
return_bins=False,
smoothing=0.02):
'''Divide a 2D space in bins of size binsize**2, count the time spent
in each bin. The map can be convolved with a gaussian kernel of size
csize determined by the smoothing factor, binsize and box_xlen.
Parameters
----------
x : array
1d vector of x positions
y : array
1d vector of y positions
t : array
1d vector of times at x, y positions
binsize : float
spatial binsize
box_xlen : float
side length of quadratic box
mask_unvisited: bool
mask bins which has not been visited by nans
convolve : bool
convolve the rate map with a 2D Gaussian kernel
Returns
-------
occupancy_map : numpy.ndarray
if return_bins = True
out : occupancy_map, xbins, ybins
'''
if not all([len(var) == len(var2) for var in [
x, y, t] for var2 in [x, y, t]]):
raise ValueError('x, y, t must have same number of elements')
if box_xlen < x.max() or box_ylen < y.max():
raise ValueError(
'box length must be larger or equal to max path length')
from decimal import Decimal as dec
decimals = 1e10
remainderx = dec(float(box_xlen)*decimals) % dec(float(binsize)*decimals)
remaindery = dec(float(box_ylen)*decimals) % dec(float(binsize)*decimals)
if remainderx != 0 or remaindery != 0:
raise ValueError('the remainder should be zero i.e. the ' +
'box length should be an exact multiple ' +
'of the binsize')
# interpolate one extra timepoint
t_ = np.array(t.tolist() + [t.max() + np.median(np.diff(t))])
time_in_bin = np.diff(t_)
xbins = np.arange(0, box_xlen + binsize, binsize)
ybins = np.arange(0, box_ylen + binsize, binsize)
ix = np.digitize(x, xbins, right=True)
iy = np.digitize(y, ybins, right=True)
time_pos = np.zeros((xbins.size, ybins.size))
for n in range(len(x) - 1):
time_pos[ix[n], iy[n]] += time_in_bin[n]
# correct for shifting of map since digitize returns values at right edges
time_pos = time_pos[1:, 1:]
if convolve:
rate[np.isnan(rate)] = 0. # for convolution
from astropy.convolution import Gaussian2DKernel, convolve_fft
csize = (box_xlen / binsize) * smoothing
kernel = Gaussian2DKernel(csize)
rate = convolve_fft(rate, kernel) # TODO edge correction
if mask_unvisited:
was_in_bin = np.asarray(time_pos, dtype=bool)
rate[np.invert(was_in_bin)] = np.nan
if return_bins:
return rate.T, xbins, ybins
else:
return rate.T
def nvisits_map(x, y, t,
binsize=0.01,
box_xlen=1,
box_ylen=1,
return_bins=False):
'''Divide a 2D space in bins of size binsize**2, count the
number of visits in each bin. The map can be convolved with
a gaussian kernel of size determined by the smoothing factor,
binsize and box_xlen.
Parameters
----------
x : array
1d vector of x positions
y : array
1d vector of y positions
t : array
1d vector of times at x, y positions
binsize : float
spatial binsize
box_xlen : float
side length of quadratic box
Returns
-------
nvisits_map : numpy.ndarray
if return_bins = True
out : nvisits_map, xbins, ybins
'''
if not all([len(var) == len(var2) for var in [
x, y, t] for var2 in [x, y, t]]):
raise ValueError('x, y, t must have same number of elements')
if box_xlen < x.max() or box_ylen < y.max():
raise ValueError(
'box length must be larger or equal to max path length')
from decimal import Decimal as dec
decimals = 1e10
remainderx = dec(float(box_xlen)*decimals) % dec(float(binsize)*decimals)
remaindery = dec(float(box_ylen)*decimals) % dec(float(binsize)*decimals)
if remainderx != 0 or remaindery != 0:
raise ValueError('the remainder should be zero i.e. the ' +
'box length should be an exact multiple ' +
'of the binsize')
xbins = np.arange(0, box_xlen + binsize, binsize)
ybins = np.arange(0, box_ylen + binsize, binsize)
ix = np.digitize(x, xbins, right=True)
iy = np.digitize(y, ybins, right=True)
nvisits_map = np.zeros((xbins.size, ybins.size))
for n in range(len(x)):
if n == 0:
nvisits_map[ix[n], iy[n]] = 1
else:
if ix[n-1] != ix[n] or iy[n-1] != iy[n]:
nvisits_map[ix[n], iy[n]] += 1
# correct for shifting of map since digitize returns values at right edges
nvisits_map = nvisits_map[1:, 1:]
if return_bins:
return nvisits_map.T, xbins, ybins
else:
return nvisits_map.T
def spatial_rate_map_1d(x, t, spike_train,
binsize=0.01,
track_len=1,
mask_unvisited=True,
convolve=True,
return_bins=False,
smoothing=0.02):
"""Take x coordinates of linear track data, divide in bins of binsize,
count the number of spikes in each bin and divide by the time spent in
respective bins. The map can then be convolved with a gaussian kernel of
size csize determined by the smoothing factor, binsize and box_xlen.
Parameters
----------
spike_train : array
x : array
1d vector of x positions
t : array
1d vector of times at x, y positions
binsize : float
spatial binsize
box_xlen : float
side length of quadratic box
mask_unvisited: bool
mask bins which has not been visited by nans
convolve : bool
convolve the rate map with a 2D Gaussian kernel
Returns
-------
out : rate map
if return_bins = True
out : rate map, xbins
"""
if not all([len(var) == len(var2) for var in [x, t] for var2 in [x, t]]):
raise ValueError('x, t must have same number of elements')
if track_len < x.max():
raise ValueError('track length must be\
larger or equal to max path length')
from decimal import Decimal as dec
decimals = 1e10
remainderx = dec(float(track_len)*decimals) % dec(float(binsize)*decimals)
if remainderx != 0:
raise ValueError('the remainder should be zero i.e. the ' +
'box length should be an exact multiple ' +
'of the binsize')
# interpolate one extra timepoint
t_ = np.array(t.tolist() + [t.max() + np.median(np.diff(t))])
spikes_in_bin, _ = np.histogram(spike_train, t_)
time_in_bin = np.diff(t_)
xbins = np.arange(0, track_len + binsize, binsize)
ix = np.digitize(x, xbins, right=True)
spike_pos = np.zeros(xbins.size)
time_pos = np.zeros(xbins.size)
for n in range(len(x)):
spike_pos[ix[n]] += spikes_in_bin[n]
time_pos[ix[n]] += time_in_bin[n]
# correct for shifting of map since digitize returns values at right edges
spike_pos = spike_pos[1:]
time_pos = time_pos[1:]
with np.errstate(divide='ignore', invalid='ignore'):
rate = np.divide(spike_pos, time_pos)
if convolve:
rate[np.isnan(rate)] = 0. # for convolution
from astropy.convolution import Gaussian2DKernel, convolve_fft
csize = (track_len / binsize) * smoothing
kernel = Gaussian2DKernel(csize)
rate = convolve_fft(rate, kernel) # TODO edge correction
if mask_unvisited:
was_in_bin = np.asarray(time_pos, dtype=bool)
rate[np.invert(was_in_bin)] = np.nan
if return_bins:
return rate.T, xbins
else:
return rate.T
def separate_fields(rate_map, laplace_thrsh=0, center_method='maxima',
cutoff_method='none', box_xlen=1, box_ylen=1, index=False):
"""Separates fields using the laplacian to identify fields separated by
a negative second derivative.
Parameters
----------
rate_map : np 2d array
firing rate in each bin
laplace_thrsh : float
value of laplacian to separate fields by relative to the minima. Should be
on the interval 0 to 1, where 0 cuts off at 0 and 1 cuts off at
min(laplace(rate_map)). Default 0.
center_method : string
method to find field centers. Valid options = ['center_of_mass',
'maxima','gaussian_fit']
cutoff_method (optional) : string or function
function to exclude small fields. If local field value of function
is lower than global function value, the field is excluded. Valid
string_options = ['median', 'mean','none'].
index : bool, default False
return bump center values as index or xy-pos
Returns
-------
fields : numpy array, shape like rate_map.
contains areas all filled with same value, corresponding to fields
in rate_map. The values are in range(1,nFields + 1), sorted by size of the
field (sum of all field values). 0 elsewhere.
n_field : int
field count
bump_centers : (n_field x 2) np ndarray
Coordinates of field centers
"""
cutoff_functions = {'mean':np.mean, 'median':np.median, 'none':None}
if not callable(cutoff_method):
try:
cutoff_func = cutoff_functions[cutoff_method]
except KeyError:
msg = "invalid cutoff_method flag '%s'" % cutoff_method
raise ValueError(msg)
else:
cutoff_func = cutoff_method
from scipy import ndimage
l = ndimage.laplace(rate_map)
l[l>laplace_thrsh*np.min(l)] = 0
# Labels areas of the laplacian not connected by values > 0.
fields, n_fields = ndimage.label(l)
# index 0 is the background
indx = np.arange(1,n_fields+1)
# Use cutoff method to remove unwanted fields
if cutoff_method != 'none':
try:
total_value = cutoff_func(fields)
except:
print('Unexpected error, cutoff_func doesnt like the input:')
raise
field_values = ndimage.labeled_comprehension(rate_map, fields, indx,
cutoff_func, float, 0)
try:
is_field = field_values >= total_value
except:
print('cutoff_func return_values doesnt want to compare:')
raise
if np.sum(is_field) == 0:
return np.zeros(rate_map.shape), 0, np.array([[],[]])
for i in indx:
if not is_field[i-1]:
fields[fields == i] = 0
n_fields = ndimage.label(fields, output=fields)
indx = np.arange(1,n_fields + 1)
# Sort by largest mean
sizes = ndimage.labeled_comprehension(rate_map, fields, indx,
np.mean, float, 0)
size_sort = np.argsort(sizes)[::-1]
new = np.zeros_like(fields)
for i in np.arange(n_fields):
new[fields == size_sort[i]+1] = i+1
fields = new
bc = get_bump_centers(rate_map,labels=fields,ret_index=index,indices=indx,method=center_method,
units=box_xlen.units)
# TODO exclude fields where maxima is on the edge of the field?
return fields, n_fields, bc
def get_bump_centers(rate_map, labels, ret_index=False, indices=None, method='maxima',
units=1):
"""Finds center of fields at labels."""
from scipy import ndimage
if method not in ['maxima','center_of_mass','gaussian_fit']:
msg = "invalid center_method flag '%s'" % method
raise ValueError(msg)
if indices is None:
indices = np.arange(1,np.max(labels)+1)
if method == 'maxima':
bc = ndimage.maximum_position(rate_map, labels=labels,
index=indices)
elif method == 'center_of_mass':
bc = ndimage.center_of_mass(rate_map, labels=labels, index=indices)
elif method == 'gaussian_fit':
from exana.tracking.tools import fit_gauss_asym
bc = np.zeros((len(indices),2))
import matplotlib.pyplot as plt
for i in indices:
r = rate_map.copy()
r[labels != i] = 0
popt = fit_gauss_asym(r, return_data=False)
# TODO Find out which axis is x and which is y
bc[i-1] = (popt[2],popt[1])
if ret_index:
msg = 'ret_index not implemented for gaussian fit'
raise NotImplementedError(msg)
if not ret_index and not method=='gaussian_fit':
bc = (bc + np.array((0.5,0.5)))/rate_map.shape
return np.array(bc)*units
def find_avg_dist(rate_map, thrsh = 0, plot=False):
"""Uses autocorrelation and separate_fields to find average distance
between bumps. Is dependent on high gridness to get separate bumps in
the autocorrelation
Parameters
----------
rate_map : np 2d array
firing rate in each bin
thrsh (optional) : float, default 0
cutoff value for the laplacian of the autocorrelation function.
Should be a negative number. Gives better separation if bumps are
connected by "bridges" or saddles where the laplacian is negative.
plot (optional) : bool, default False
plot acorr and the separated acorr, with bump centers
Returns
-------
avg_dist : float
relative units from 0 to 1 of the box size
"""
from scipy.ndimage import maximum_position
from exana.misc.tools import fftcorrelate2d
# autocorrelate. Returns array (2x - 1) the size of rate_map
acorr = fftcorrelate2d(rate_map,rate_map, mode = 'full', normalize = True)
#acorr[acorr<0] = 0 # TODO Fix this
f, nf, bump_centers = separate_fields(acorr,laplace_thrsh=thrsh,
center_method='maxima',cutoff_method='median')
# TODO Find a way to find valid value for
# thrsh, or remove.
bump_centers = np.array(bump_centers)
# find dists from center in (autocorrelation)relative units (from 0 to 1)
distances = np.linalg.norm(bump_centers - (0.5,0.5), axis = 1)
dist_sort = np.argsort(distances)
distances = distances[dist_sort]
# use maximum 6 closest values except center value
avg_dist = np.median(distances[1:7])
# correct for difference in shapes
avg_dist *= acorr.shape[0]/rate_map.shape[0] # = 1.98
# TODO : raise warning if too big difference between points
if plot:
import matplotlib.pyplot as plt
fig,[ax1,ax2] = plt.subplots(1,2)
ax1.imshow(acorr,extent = (0,1,0,1),origin='lower')
ax1.scatter(*(bump_centers[:,::-1].T))
ax2.imshow(f,extent = (0,1,0,1),origin='lower')
ax2.scatter(*(bump_centers[:,::-1].T))
return avg_dist
def fit_hex(bump_centers, avg_dist=None, plot_bumps = False, method='best'):
"""Fits a hex grid to a given set of bumps. Uses the three bumps most
Parameters
----------
bump_centers : Nx2 np.array
x,y positions of bump centers, x,y /in (0,1)
avg_dist (optional): float
average spacing between bumps
plot_bumps (optional): bool
if True, plots at the three bumps most likely to be in
correct hex-position to the current matplotlib axes.
method (optional): string, valid options: ['closest', 'best']
method to find angle from neighboring bumps.
'closest' uses six bumps nearest to center bump
'best' uses the two bumps nearest to avg_dist
Returns
-------
displacement : float
distance of bump closest to the center in meters
orientation : float
orientation of hexagon (in degrees)
"""
valid_methods = ['closest', 'best']
if method not in valid_methods:
msg = "invalid method flag '%s'" % method
raise ValueError(msg)
bump_centers = np.array(bump_centers)
# sort by distance to center
d = np.linalg.norm(bump_centers - (0.5,0.5), axis=1)
d_sort = np.argsort(d)
dist_sorted = bump_centers[d_sort]
center_bump = dist_sorted[0]; others = dist_sorted[1:]
displacement = d[d_sort][0]
# others distances to center bumps
relpos = others - center_bump
reldist = np.linalg.norm(relpos, axis=1)
if method == 'closest':
# get 6 closest bumps
rel_sort = np.argsort(reldist)
closest = others[rel_sort][:6]
relpos = relpos[rel_sort][:6]
elif method == 'best':
# get 2 bumps such that /sum_{i\neqj}(\abs{r_i-r_j}-avg_ist)^2 is minimized
squares = 1e32*np.ones((others.shape[0], others.shape[0]))
for i in range(len(relpos)):
for j in range(i,len(relpos)):
rel1 = (reldist[i] - avg_dist)**2
rel2 = (reldist[j] - avg_dist)**2
rel3 = (np.linalg.norm(relpos[i]-relpos[j]) - avg_dist)**2
squares[i,j] = rel1 + rel2 + rel3
rel_slice = np.unravel_index(np.argmin(squares), squares.shape)
rel_slice = np.array(rel_slice)
#rel_sort = np.argsort(np.abs(reldist-avg_dist))
closest = others[rel_slice]
relpos = relpos[rel_slice]
# sort by angle
a = np.arctan2(relpos[:,1], relpos[:,0])%(2*np.pi)
a_sort = np.argsort(a)
# extract lowest angle and convert to degrees
orientation = a[a_sort][0] *180/np.pi
# hex grid is symmetric under rotations of 60deg
orientation %= 60
if plot_bumps:
import matplotlib.pyplot as plt
ax=plt.gca()
i = 1
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
dx = xmax-xmin; dy = ymax - ymin
closest = closest[a_sort]
edges = [center_bump] if method == 'best' else []
edges += [c for c in closest]
edges = np.array(edges)*(dx,dy) + (xmin, ymin)
poly = plt.Polygon(edges, alpha=0.5,color='r')
ax.add_artist(poly)
return displacement, orientation
def calculate_grid_geometry(rate_map, plot_fields=False, **kwargs):
"""Calculates quantitative information about grid field.
Find bump centers, bump spacing, center diplacement and hexagon
orientation
Parameters
----------
rate_map : np 2d array
firing rate in each bin
plot_fields : if True, plots the field labels with field centers to the
current matplotlib ax. Default False
thrsh : float, default 0
see find_avg_dist()
center_method : string, valid options: ['maxima', 'center_of_mass']
default: 'center_of_mass'
see separate_fields()
method : string, valid options: ['closest', 'best']
see fit_hex()
Returns
-------
bump_centers : 2d np.array
x,y positions of bump centers
avg_dist : float
average spacing between bumps, \in [0,1]
displacement : float
distance of bump closest to the center
orientation : float
orientation of hexagon (in degrees)
Examples
--------
>>> import numpy as np
>>> rate_map = np.zeros((5,5))
>>> pos = np.array([ [0,2],
... [1,0],[1,4],
... [2,2],
... [3,0],[3,4],
... [4,2]])
>>> for(i,j) in pos:
... rate_map[i,j] = 1
...
>>> result = calculate_grid_geometry(rate_map)
"""
# TODO add back the following when it is correct
# (array([[0.5, 0.9],
# [0.9, 0.7],
# [0.1, 0.7],
# [0.5, 0.5],
# [0.9, 0.3],
# [0.1, 0.3],
# [0.5, 0.1]]) * m, 0.4472135954999579, 0.0, 26.565051177077983)
from scipy.ndimage import mean, center_of_mass
# TODO: smooth data?
# smooth_rate_map = lambda x:x
# rate_map = smooth_rate_map(rate_map)
center_method = kwargs.pop('center_method',None)
if center_method:
fields, nfields, bump_centers = separate_fields(rate_map,
center_method=center_method)
else:
fields, nfields, bump_centers = separate_fields(rate_map)
if bump_centers.size == 0:
import warnings
msg = 'couldnt find bump centers, returning None'
warnings.warn(msg, RuntimeWarning, stacklevel=2)
return None,None,None,None,
sh = np.array(rate_map.shape)
if plot_fields:
print(fields)
import matplotlib.pyplot as plt
x=np.linspace(0,1,sh[0]+1)
y=np.linspace(0,1,sh[1]+1)
x,y = np.meshgrid(x,y)
ax = plt.gca()
print('nfields: ',nfields)
plt.pcolormesh(x,y, fields)
# switch from row-column to x-y
bump_centers = bump_centers[:,::-1]
thrsh = kwargs.pop('thrsh', None)
if thrsh:
avg_dist = find_avg_dist(rate_map, thrsh)
else:
avg_dist = find_avg_dist(rate_map)
displacement, orientation = fit_hex(bump_centers, avg_dist,
plot_bumps=plot_fields, **kwargs)
return bump_centers, avg_dist, displacement, orientation
class RandomDisplacementBounds(object):
"""random displacement with bounds"""
def __init__(self, xmin, xmax, stepsize=0.5):
self.xmin = np.array(xmin)
self.xmax = np.array(xmax)
self.stepsize = stepsize
def __call__(self, x):
"""take a random step but ensure the new position is within the bounds"""
while True:
# this could be done in a much more clever way, but it will work for example purposes
xnew = x + (self.xmax-self.xmin)*np.random.uniform(-self.stepsize,
self.stepsize, np.shape(x))
if np.all(xnew < self.xmax) and np.all(xnew > self.xmin):
break
return xnew
def optimize_sep_fields(rate_map,step = 0.04, niter=40, T = 1.0, method = 'SLSQP',
glob=True, x0 = [0.065,0.1],callback=None):
"""Optimizes the separation of the fields by minimizing an error
function
Parameters
----------
rate_map :
method :
valid methods=['L-BFGS-B', 'TNC', 'SLSQP']
x0 : list
initial values for smoothing smoothing and laplace_thrsh
Returns
--------
res :
Result of the optimization. Contains smoothing and laplace_thrsh in
attribute res.x"""
from scipy import optimize
from exana.tracking.tools import separation_error_func as err_func
valid_methods = ['L-BFGS-B', 'TNC', 'SLSQP']
if method not in valid_methods:
raise ValueError('invalid method flag %s' %method)
rate_map[np.isnan(rate_map)] = 0.
method = 'SLSQP'
xmin = [0.025, 0]
xmax = [0.2, 1]
bounds = [(low,high) for low,high in zip(xmin,xmax)]
obj_func = lambda args: err_func(args[0], args[1], rate_map)
if glob:
take_step = RandomDisplacementBounds(xmin, xmax,stepsize=step)
minimizer_kwargs = dict(method=method, bounds=bounds)
res = optimize.basinhopping(obj_func, x0, niter=niter, T = T,
minimizer_kwargs=minimizer_kwargs,
take_step=take_step,callback=callback)
else:
res = optimize.minimize(obj_func, x0, method=method, bounds = bounds, options={'disp': True})
return res
if __name__ == "__main__":
import doctest
doctest.testmod()
| gpl-3.0 |
xindus40223115/2015cda_g1 | static/Brython3.1.1-20150328-091302/Lib/_abcoll.py | 688 | 5155 | # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
via collections; they are defined here only to alleviate certain
bootstrapping issues. Unit tests are in test_collections.
"""
from abc import ABCMeta, abstractmethod
import sys
__all__ = ["Hashable", "Iterable", "Iterator",
"Sized", "Container", "Callable",
"Set", "MutableSet",
"Mapping", "MutableMapping",
"MappingView", "KeysView", "ItemsView", "ValuesView",
"Sequence", "MutableSequence",
"ByteString",
]
"""
### collection related types which are not exposed through builtin ###
## iterators ##
#fixme brython
#bytes_iterator = type(iter(b''))
bytes_iterator = type(iter(''))
#fixme brython
#bytearray_iterator = type(iter(bytearray()))
#callable_iterator = ???
dict_keyiterator = type(iter({}.keys()))
dict_valueiterator = type(iter({}.values()))
dict_itemiterator = type(iter({}.items()))
list_iterator = type(iter([]))
list_reverseiterator = type(iter(reversed([])))
range_iterator = type(iter(range(0)))
set_iterator = type(iter(set()))
str_iterator = type(iter(""))
tuple_iterator = type(iter(()))
zip_iterator = type(iter(zip()))
## views ##
dict_keys = type({}.keys())
dict_values = type({}.values())
dict_items = type({}.items())
## misc ##
dict_proxy = type(type.__dict__)
"""
def abstractmethod(self):
return self
### ONE-TRICK PONIES ###
#class Iterable(metaclass=ABCMeta):
class Iterable:
@abstractmethod
def __iter__(self):
while False:
yield None
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
if any("__iter__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
#class Sized(metaclass=ABCMeta):
class Sized:
@abstractmethod
def __len__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Sized:
if any("__len__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
#class Container(metaclass=ABCMeta):
class Container:
@abstractmethod
def __contains__(self, x):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Container:
if any("__contains__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
### MAPPINGS ###
class Mapping(Sized, Iterable, Container):
@abstractmethod
def __getitem__(self, key):
raise KeyError
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def keys(self):
return KeysView(self)
def items(self):
return ItemsView(self)
def values(self):
return ValuesView(self)
def __eq__(self, other):
if not isinstance(other, Mapping):
return NotImplemented
return dict(self.items()) == dict(other.items())
def __ne__(self, other):
return not (self == other)
class MutableMapping(Mapping):
@abstractmethod
def __setitem__(self, key, value):
raise KeyError
@abstractmethod
def __delitem__(self, key):
raise KeyError
__marker = object()
def pop(self, key, default=__marker):
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value
def popitem(self):
try:
key = next(iter(self))
except StopIteration:
raise KeyError
value = self[key]
del self[key]
return key, value
def clear(self):
try:
while True:
self.popitem()
except KeyError:
pass
def update(*args, **kwds):
if len(args) > 2:
raise TypeError("update() takes at most 2 positional "
"arguments ({} given)".format(len(args)))
elif not args:
raise TypeError("update() takes at least 1 argument (0 given)")
self = args[0]
other = args[1] if len(args) >= 2 else ()
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
def setdefault(self, key, default=None):
try:
return self[key]
except KeyError:
self[key] = default
return default
#MutableMapping.register(dict)
| gpl-3.0 |
msduketown/xbmc | tools/EventClients/lib/python/ps3/keymaps.py | 245 | 2329 | # -*- coding: utf-8 -*-
# Copyright (C) 2008-2013 Team XBMC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# PS3 Remote and Controller Keymaps
keymap_remote = {
"16": 'power' ,#EJECT
"64": None ,#AUDIO
"65": None ,#ANGLE
"63": 'subtitle' ,#SUBTITLE
"0f": None ,#CLEAR
"28": None ,#TIME
"00": 'one' ,#1
"01": 'two' ,#2
"02": 'three' ,#3
"03": 'four' ,#4
"04": 'five' ,#5
"05": 'six' ,#6
"06": 'seven' ,#7
"07": 'eight' ,#8
"08": 'nine' ,#9
"09": 'zero' ,#0
"81": 'mytv' ,#RED
"82": 'mymusic' ,#GREEN
"80": 'mypictures' ,#BLUE
"83": 'myvideo' ,#YELLOW
"70": 'display' ,#DISPLAY
"1a": None ,#TOP MENU
"40": 'menu' ,#POP UP/MENU
"0e": None ,#RETURN
"5c": 'menu' ,#OPTIONS/TRIANGLE
"5d": 'back' ,#BACK/CIRCLE
"5e": 'info' ,#X
"5f": 'title' ,#VIEW/SQUARE
"54": 'up' ,#UP
"55": 'right' ,#RIGHT
"56": 'down' ,#DOWN
"57": 'left' ,#LEFT
"0b": 'select' ,#ENTER
"5a": 'volumeplus' ,#L1
"58": 'volumeminus' ,#L2
"51": 'Mute' ,#L3
"5b": 'pageplus' ,#R1
"59": 'pageminus' ,#R2
"52": None ,#R3
"43": None ,#PLAYSTATION
"50": None ,#SELECT
"53": None ,#START
"33": 'reverse' ,#<-SCAN
"34": 'forward' ,# SCAN->
"30": 'skipminus' ,#PREV
"31": 'skipplus' ,#NEXT
"60": None ,#<-SLOW/STEP
"61": None ,# SLOW/STEP->
"32": 'play' ,#PLAY
"38": 'stop' ,#STOP
"39": 'pause' ,#PAUSE
}
| gpl-2.0 |
rpmcpp/Audacity | lib-src/lv2/sord/waflib/Configure.py | 147 | 9872 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import os,shlex,sys,time
from waflib import ConfigSet,Utils,Options,Logs,Context,Build,Errors
try:
from urllib import request
except ImportError:
from urllib import urlopen
else:
urlopen=request.urlopen
BREAK='break'
CONTINUE='continue'
WAF_CONFIG_LOG='config.log'
autoconfig=False
conf_template='''# project %(app)s configured on %(now)s by
# waf %(wafver)s (abi %(abi)s, python %(pyver)x on %(systype)s)
# using %(args)s
#'''
def download_check(node):
pass
def download_tool(tool,force=False,ctx=None):
for x in Utils.to_list(Context.remote_repo):
for sub in Utils.to_list(Context.remote_locs):
url='/'.join((x,sub,tool+'.py'))
try:
web=urlopen(url)
try:
if web.getcode()!=200:
continue
except AttributeError:
pass
except Exception:
continue
else:
tmp=ctx.root.make_node(os.sep.join((Context.waf_dir,'waflib','extras',tool+'.py')))
tmp.write(web.read(),'wb')
Logs.warn('Downloaded %s from %s'%(tool,url))
download_check(tmp)
try:
module=Context.load_tool(tool)
except Exception:
Logs.warn('The tool %s from %s is unusable'%(tool,url))
try:
tmp.delete()
except Exception:
pass
continue
return module
raise Errors.WafError('Could not load the Waf tool')
class ConfigurationContext(Context.Context):
'''configures the project'''
cmd='configure'
error_handlers=[]
def __init__(self,**kw):
super(ConfigurationContext,self).__init__(**kw)
self.environ=dict(os.environ)
self.all_envs={}
self.top_dir=None
self.out_dir=None
self.tools=[]
self.hash=0
self.files=[]
self.tool_cache=[]
self.setenv('')
def setenv(self,name,env=None):
if name not in self.all_envs or env:
if not env:
env=ConfigSet.ConfigSet()
self.prepare_env(env)
else:
env=env.derive()
self.all_envs[name]=env
self.variant=name
def get_env(self):
return self.all_envs[self.variant]
def set_env(self,val):
self.all_envs[self.variant]=val
env=property(get_env,set_env)
def init_dirs(self):
top=self.top_dir
if not top:
top=Options.options.top
if not top:
top=getattr(Context.g_module,Context.TOP,None)
if not top:
top=self.path.abspath()
top=os.path.abspath(top)
self.srcnode=(os.path.isabs(top)and self.root or self.path).find_dir(top)
assert(self.srcnode)
out=self.out_dir
if not out:
out=Options.options.out
if not out:
out=getattr(Context.g_module,Context.OUT,None)
if not out:
out=Options.lockfile.replace('.lock-waf_%s_'%sys.platform,'').replace('.lock-waf','')
self.bldnode=(os.path.isabs(out)and self.root or self.path).make_node(out)
self.bldnode.mkdir()
if not os.path.isdir(self.bldnode.abspath()):
conf.fatal('Could not create the build directory %s'%self.bldnode.abspath())
def execute(self):
self.init_dirs()
self.cachedir=self.bldnode.make_node(Build.CACHE_DIR)
self.cachedir.mkdir()
path=os.path.join(self.bldnode.abspath(),WAF_CONFIG_LOG)
self.logger=Logs.make_logger(path,'cfg')
app=getattr(Context.g_module,'APPNAME','')
if app:
ver=getattr(Context.g_module,'VERSION','')
if ver:
app="%s (%s)"%(app,ver)
now=time.ctime()
pyver=sys.hexversion
systype=sys.platform
args=" ".join(sys.argv)
wafver=Context.WAFVERSION
abi=Context.ABI
self.to_log(conf_template%vars())
self.msg('Setting top to',self.srcnode.abspath())
self.msg('Setting out to',self.bldnode.abspath())
if id(self.srcnode)==id(self.bldnode):
Logs.warn('Setting top == out (remember to use "update_outputs")')
elif id(self.path)!=id(self.srcnode):
if self.srcnode.is_child_of(self.path):
Logs.warn('Are you certain that you do not want to set top="." ?')
super(ConfigurationContext,self).execute()
self.store()
Context.top_dir=self.srcnode.abspath()
Context.out_dir=self.bldnode.abspath()
env=ConfigSet.ConfigSet()
env['argv']=sys.argv
env['options']=Options.options.__dict__
env.run_dir=Context.run_dir
env.top_dir=Context.top_dir
env.out_dir=Context.out_dir
env['hash']=self.hash
env['files']=self.files
env['environ']=dict(self.environ)
if not self.env.NO_LOCK_IN_RUN:
env.store(Context.run_dir+os.sep+Options.lockfile)
if not self.env.NO_LOCK_IN_TOP:
env.store(Context.top_dir+os.sep+Options.lockfile)
if not self.env.NO_LOCK_IN_OUT:
env.store(Context.out_dir+os.sep+Options.lockfile)
def prepare_env(self,env):
if not env.PREFIX:
if Options.options.prefix or Utils.is_win32:
env.PREFIX=os.path.abspath(os.path.expanduser(Options.options.prefix))
else:
env.PREFIX=''
if not env.BINDIR:
env.BINDIR=Utils.subst_vars('${PREFIX}/bin',env)
if not env.LIBDIR:
env.LIBDIR=Utils.subst_vars('${PREFIX}/lib',env)
def store(self):
n=self.cachedir.make_node('build.config.py')
n.write('version = 0x%x\ntools = %r\n'%(Context.HEXVERSION,self.tools))
if not self.all_envs:
self.fatal('nothing to store in the configuration context!')
for key in self.all_envs:
tmpenv=self.all_envs[key]
tmpenv.store(os.path.join(self.cachedir.abspath(),key+Build.CACHE_SUFFIX))
def load(self,input,tooldir=None,funs=None,download=True):
tools=Utils.to_list(input)
if tooldir:tooldir=Utils.to_list(tooldir)
for tool in tools:
mag=(tool,id(self.env),funs)
if mag in self.tool_cache:
self.to_log('(tool %s is already loaded, skipping)'%tool)
continue
self.tool_cache.append(mag)
module=None
try:
module=Context.load_tool(tool,tooldir)
except ImportError ,e:
if Options.options.download:
module=download_tool(tool,ctx=self)
if not module:
self.fatal('Could not load the Waf tool %r or download a suitable replacement from the repository (sys.path %r)\n%s'%(tool,sys.path,e))
else:
self.fatal('Could not load the Waf tool %r from %r (try the --download option?):\n%s'%(tool,sys.path,e))
except Exception ,e:
self.to_log('imp %r (%r & %r)'%(tool,tooldir,funs))
self.to_log(Utils.ex_stack())
raise
if funs is not None:
self.eval_rules(funs)
else:
func=getattr(module,'configure',None)
if func:
if type(func)is type(Utils.readf):func(self)
else:self.eval_rules(func)
self.tools.append({'tool':tool,'tooldir':tooldir,'funs':funs})
def post_recurse(self,node):
super(ConfigurationContext,self).post_recurse(node)
self.hash=hash((self.hash,node.read('rb')))
self.files.append(node.abspath())
def eval_rules(self,rules):
self.rules=Utils.to_list(rules)
for x in self.rules:
f=getattr(self,x)
if not f:self.fatal("No such method '%s'."%x)
try:
f()
except Exception ,e:
ret=self.err_handler(x,e)
if ret==BREAK:
break
elif ret==CONTINUE:
continue
else:
raise
def err_handler(self,fun,error):
pass
def conf(f):
def fun(*k,**kw):
mandatory=True
if'mandatory'in kw:
mandatory=kw['mandatory']
del kw['mandatory']
try:
return f(*k,**kw)
except Errors.ConfigurationError:
if mandatory:
raise
setattr(ConfigurationContext,f.__name__,fun)
setattr(Build.BuildContext,f.__name__,fun)
return f
@conf
def add_os_flags(self,var,dest=None):
try:self.env.append_value(dest or var,shlex.split(self.environ[var]))
except KeyError:pass
@conf
def cmd_to_list(self,cmd):
if isinstance(cmd,str)and cmd.find(' '):
try:
os.stat(cmd)
except OSError:
return shlex.split(cmd)
else:
return[cmd]
return cmd
@conf
def check_waf_version(self,mini='1.6.99',maxi='1.8.0'):
self.start_msg('Checking for waf version in %s-%s'%(str(mini),str(maxi)))
ver=Context.HEXVERSION
if Utils.num2ver(mini)>ver:
self.fatal('waf version should be at least %r (%r found)'%(Utils.num2ver(mini),ver))
if Utils.num2ver(maxi)<ver:
self.fatal('waf version should be at most %r (%r found)'%(Utils.num2ver(maxi),ver))
self.end_msg('ok')
@conf
def find_file(self,filename,path_list=[]):
for n in Utils.to_list(filename):
for d in Utils.to_list(path_list):
p=os.path.join(d,n)
if os.path.exists(p):
return p
self.fatal('Could not find %r'%filename)
@conf
def find_program(self,filename,**kw):
exts=kw.get('exts',Utils.is_win32 and'.exe,.com,.bat,.cmd'or',.sh,.pl,.py')
environ=kw.get('environ',os.environ)
ret=''
filename=Utils.to_list(filename)
var=kw.get('var','')
if not var:
var=filename[0].upper()
if self.env[var]:
ret=self.env[var]
elif var in environ:
ret=environ[var]
path_list=kw.get('path_list','')
if not ret:
if path_list:
path_list=Utils.to_list(path_list)
else:
path_list=environ.get('PATH','').split(os.pathsep)
if not isinstance(filename,list):
filename=[filename]
for a in exts.split(','):
if ret:
break
for b in filename:
if ret:
break
for c in path_list:
if ret:
break
x=os.path.expanduser(os.path.join(c,b+a))
if os.path.isfile(x):
ret=x
if not ret and Utils.winreg:
ret=Utils.get_registry_app_path(Utils.winreg.HKEY_CURRENT_USER,filename)
if not ret and Utils.winreg:
ret=Utils.get_registry_app_path(Utils.winreg.HKEY_LOCAL_MACHINE,filename)
self.msg('Checking for program '+','.join(filename),ret or False)
self.to_log('find program=%r paths=%r var=%r -> %r'%(filename,path_list,var,ret))
if not ret:
self.fatal(kw.get('errmsg','')or'Could not find the program %s'%','.join(filename))
if var:
self.env[var]=ret
return ret
@conf
def find_perl_program(self,filename,path_list=[],var=None,environ=None,exts=''):
try:
app=self.find_program(filename,path_list=path_list,var=var,environ=environ,exts=exts)
except Exception:
self.find_program('perl',var='PERL')
app=self.find_file(filename,os.environ['PATH'].split(os.pathsep))
if not app:
raise
if var:
self.env[var]=Utils.to_list(self.env['PERL'])+[app]
self.msg('Checking for %r'%filename,app)
| gpl-2.0 |
40223137/w1717 | static/Brython3.1.0-20150301-090019/Lib/site-packages/pygame/locals.py | 603 | 1141 | ## pygame - Python Game Library
## Copyright (C) 2000-2003 Pete Shinners
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Library General Public
## License as published by the Free Software Foundation; either
## version 2 of the License, or (at your option) any later version.
##
## This library is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## Library General Public License for more details.
##
## You should have received a copy of the GNU Library General Public
## License along with this library; if not, write to the Free
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
## Pete Shinners
## pete@shinners.org
"""Set of functions from PyGame that are handy to have in
the local namespace for your module"""
from pygame.constants import *
from pygame.rect import Rect
import pygame.color as color
Color = color.Color
| gpl-3.0 |
btovar/cctools | apps/wq_hypersweep/test.py | 1 | 1690 | from work_queue import *
import sys
def compose_task(i,j):
id = (i-1)*20+j
d_rate = i*0.05
r_blok = j
outfile = "results%d.csv" % id
command = "./script.sh results%d.csv %f %d" % (id,d_rate,r_blok)
t = Task(command)
t.specify_file("env.tar.gz", "env.tar.gz", WORK_QUEUE_INPUT, cache=True)
t.specify_file("datasets/cifar-10-batches-py", "datasets/cifar-10-batches-py", WORK_QUEUE_INPUT, cache=True)
t.specify_file("resnet.py", "resnet.py", WORK_QUEUE_INPUT, cache=True)
t.specify_file("script.sh", "script.sh", WORK_QUEUE_INPUT, cache=True)
t.specify_file(outfile, outfile, WORK_QUEUE_OUTPUT, cache=False)
return t
def main():
try:
q = WorkQueue(port = WORK_QUEUE_DEFAULT_PORT)
except:
print("Instantiation of Work Queue failed.")
sys.exit(1)
print("Listening on port %d..." % q.port)
for i in range(1,21):
for j in range (1,21):
t = compose_task(i,j)
taskid = q.submit(t)
print("Submitted task (id# %d): %s" % (taskid, t.command))
print("waiting for tasks to complete...")
whitelist = []
blacklist = []
while not q.empty():
t = q.wait(5)
if t:
print("task (id# %d) complete: %s (return code %d)" % (t.id, t.command, t.return_status))
if t.return_status == 0:
if t.hostname not in whitelist:
whitelist.append(t.hostname)
if t.return_status != 0:
print("stdout:\n{}".format(t.output))
print("Blacklisting host: %s" % t.hostname)
q.blacklist(t.hostname)
blacklist.append(t.hostname)
q.submit(t)
print("Resubmitted task (id# %s): %s" % (t.id, t.command))
print("All tasks complete.")
print("Whitelist:", whitelist)
print("Blacklist:", blacklist)
sys.exit(0)
if __name__ == '__main__':
main()
| gpl-2.0 |
dvitme/odoomrp-wip | mrp_production_simulated_capacity/models/mrp_production.py | 11 | 1393 | # -*- encoding: utf-8 -*-
##############################################################################
#
# 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 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/.
#
##############################################################################
from openerp import models, api
class MrpProduction(models.Model):
_inherit = 'mrp.production'
@api.multi
def _get_min_qty_for_production(self, routing=False):
qty = super(MrpProduction, self)._get_min_qty_for_production(routing)
min_capacity = routing and max(routing.workcenter_lines.filtered(
'limited_production_capacity').mapped('workcenter_id.'
'capacity_per_cycle_min')
) or 0
return max(qty, min_capacity)
| agpl-3.0 |
Pluto-tv/chromium-crosswalk | third_party/typ/typ/tests/test_case_test.py | 84 | 1908 | # Copyright 2014 Dirk Pranke. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typ import test_case
class TestFuncs(test_case.MainTestCase):
def test_convert_newlines(self):
cn = test_case.convert_newlines
self.assertEqual(cn('foo'), 'foo')
self.assertEqual(cn('foo\nbar\nbaz'), 'foo\nbar\nbaz')
self.assertEqual(cn('foo\rbar\nbaz\r'), 'foo\nbar\nbaz\n')
self.assertEqual(cn('foo\r\nbar\r\nbaz\r\nmeh\n'),
'foo\nbar\nbaz\nmeh\n')
class TestMainTestCase(test_case.MainTestCase):
def test_basic(self):
h = self.make_host()
files = {
'test.py': """
import os
import sys
sys.stdout.write("in: %s\\n" % sys.stdin.read())
sys.stdout.write("out: %s\\n" % os.environ['TEST_VAR'])
sys.stderr.write("err\\n")
with open("../results", "w") as fp:
fp.write(open("../input", "r").read() + " written")
""",
'input': 'results',
'subdir/x': 'y',
}
exp_files = files.copy()
exp_files['results'] = 'results written'
self.check(prog=[h.python_interpreter, '../test.py'],
stdin='hello on stdin',
env={'TEST_VAR': 'foo'},
cwd='subdir',
files=files,
ret=0, out='in: hello on stdin\nout: foo\n',
err='err\n', exp_files=exp_files)
| bsd-3-clause |
michelp/pybladeRF | bladeRF/_cffi.py | 2 | 1811 | import os
import inspect
from functools import wraps
from cffi import FFI
lib = None
ffi = FFI()
ffi.cdef('const char * bladerf_strerror(int error);')
ffi.cdef("""
#define BLADERF_ERR_UNEXPECTED ...
#define BLADERF_ERR_RANGE ...
#define BLADERF_ERR_INVAL ...
#define BLADERF_ERR_MEM ...
#define BLADERF_ERR_IO ...
#define BLADERF_ERR_TIMEOUT ...
#define BLADERF_ERR_NODEV ...
#define BLADERF_ERR_UNSUPPORTED ...
#define BLADERF_ERR_MISALIGNED ...
#define BLADERF_ERR_CHECKSUM ...
""")
# Code copied from michelp/pyczmq which was authored by me -mp
def ptop(typ, val=ffi.NULL):
ptop = ffi.new('%s*[1]' % typ)
ptop[0] = val
return ptop
def cdef(decl, returns_string=False, nullable=False):
ffi.cdef(decl)
def wrap(f):
@wraps(f)
def inner_f(*args):
val = f(*args)
if nullable and val == ffi.NULL:
return None
elif returns_string:
return ffi.string(val)
return val
# this insanity inserts a formatted argspec string
# into the function's docstring, so that sphinx
# gets the right args instead of just the wrapper args
args, varargs, varkw, defaults = inspect.getargspec(f)
defaults = () if defaults is None else defaults
defaults = ["\"{}\"".format(a) if type(a) == str else a for a in defaults]
l = ["{}={}".format(arg, defaults[(idx+1)*-1])
if len(defaults)-1 >= idx else
arg for idx, arg in enumerate(reversed(list(args)))]
if varargs:
l.append('*' + varargs)
if varkw:
l.append('**' + varkw)
doc = "{}({})\n\nC: ``{}``\n\n{}".format(f.__name__, ', '.join(reversed(l)), decl, f.__doc__)
inner_f.__doc__ = doc
return inner_f
return wrap
| gpl-3.0 |
jhseu/tensorflow | tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/basic.py | 1 | 2547 | # Copyright 2019 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.
# ==============================================================================
# RUN: %p/basic | FileCheck %s
# pylint: disable=missing-docstring,line-too-long
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v2 as tf
from tensorflow.compiler.mlir.tensorflow.tests.tf_saved_model import common
# Verify that the tf.versions attribute exists. It is difficult to enforce
# contents, since the version numbers change over time. The conversion logic
# itself is verified in the common graphdef converter, so here just assert
# it is being invoked.
# CHECK: module
# CHECK-SAME: tf.versions
# CHECK-SAME: bad_consumers
# CHECK-SAME: min_consumer
# CHECK-SAME: producer
class TestModule(tf.Module):
def __init__(self):
super(TestModule, self).__init__()
self.v42 = tf.Variable(42.0)
self.c43 = tf.constant(43.0)
# CHECK: "tf_saved_model.global_tensor"() {is_mutable, sym_name = "[[VAR:[a-zA-Z_0-9]+]]", tf_saved_model.exported_names = ["v42"], type = tensor<f32>, value = dense<4.200000e+01> : tensor<f32>} : () -> ()
# CHECK: "tf_saved_model.global_tensor"() {sym_name = "[[CONST:[a-zA-Z_0-9]+]]", tf_saved_model.exported_names = [], type = tensor<f32>, value = dense<4.300000e+01> : tensor<f32>} : () -> ()
# CHECK: func {{@[a-zA-Z_0-9]+}}(
# CHECK-SAME: %arg0: tensor<f32> {tf_saved_model.index_path = [0]},
# CHECK-SAME: %arg1: tensor<*x!tf.resource> {tf_saved_model.bound_input = @[[VAR]]},
# CHECK-SAME: %arg2: tensor<f32> {tf_saved_model.bound_input = @[[CONST]]}) -> (
# CHECK-SAME: tensor<f32> {tf_saved_model.index_path = []})
# CHECK-SAME: attributes {{.*}} tf_saved_model.exported_names = ["some_function"]
@tf.function(input_signature=[tf.TensorSpec([], tf.float32)])
def some_function(self, x):
return x + self.v42 + self.c43
if __name__ == '__main__':
common.do_test(TestModule)
| apache-2.0 |
wnt-zhp/hufce | django/db/models/sql/subqueries.py | 87 | 8259 | """
Query subclasses which provide extra functionality beyond simple data retrieval.
"""
from django.core.exceptions import FieldError
from django.db.models.fields import DateField, FieldDoesNotExist
from django.db.models.sql.constants import *
from django.db.models.sql.datastructures import Date
from django.db.models.sql.query import Query
from django.db.models.sql.where import AND, Constraint
from django.utils.functional import Promise
from django.utils.encoding import force_unicode
__all__ = ['DeleteQuery', 'UpdateQuery', 'InsertQuery', 'DateQuery',
'AggregateQuery']
class DeleteQuery(Query):
"""
Delete queries are done through this class, since they are more constrained
than general queries.
"""
compiler = 'SQLDeleteCompiler'
def do_query(self, table, where, using):
self.tables = [table]
self.where = where
self.get_compiler(using).execute_sql(None)
def delete_batch(self, pk_list, using, field=None):
"""
Set up and execute delete queries for all the objects in pk_list.
More than one physical query may be executed if there are a
lot of values in pk_list.
"""
if not field:
field = self.model._meta.pk
for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
where = self.where_class()
where.add((Constraint(None, field.column, field), 'in',
pk_list[offset:offset + GET_ITERATOR_CHUNK_SIZE]), AND)
self.do_query(self.model._meta.db_table, where, using=using)
class UpdateQuery(Query):
"""
Represents an "update" SQL query.
"""
compiler = 'SQLUpdateCompiler'
def __init__(self, *args, **kwargs):
super(UpdateQuery, self).__init__(*args, **kwargs)
self._setup_query()
def _setup_query(self):
"""
Runs on initialization and after cloning. Any attributes that would
normally be set in __init__ should go in here, instead, so that they
are also set up after a clone() call.
"""
self.values = []
self.related_ids = None
if not hasattr(self, 'related_updates'):
self.related_updates = {}
def clone(self, klass=None, **kwargs):
return super(UpdateQuery, self).clone(klass,
related_updates=self.related_updates.copy(), **kwargs)
def update_batch(self, pk_list, values, using):
pk_field = self.model._meta.pk
self.add_update_values(values)
for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
self.where = self.where_class()
self.where.add((Constraint(None, pk_field.column, pk_field), 'in',
pk_list[offset:offset + GET_ITERATOR_CHUNK_SIZE]),
AND)
self.get_compiler(using).execute_sql(None)
def add_update_values(self, values):
"""
Convert a dictionary of field name to value mappings into an update
query. This is the entry point for the public update() method on
querysets.
"""
values_seq = []
for name, val in values.iteritems():
field, model, direct, m2m = self.model._meta.get_field_by_name(name)
if not direct or m2m:
raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field)
if model:
self.add_related_update(model, field, val)
continue
values_seq.append((field, model, val))
return self.add_update_fields(values_seq)
def add_update_fields(self, values_seq):
"""
Turn a sequence of (field, model, value) triples into an update query.
Used by add_update_values() as well as the "fast" update path when
saving models.
"""
# Check that no Promise object passes to the query. Refs #10498.
values_seq = [(value[0], value[1], force_unicode(value[2]))
if isinstance(value[2], Promise) else value
for value in values_seq]
self.values.extend(values_seq)
def add_related_update(self, model, field, value):
"""
Adds (name, value) to an update query for an ancestor model.
Updates are coalesced so that we only run one update query per ancestor.
"""
try:
self.related_updates[model].append((field, None, value))
except KeyError:
self.related_updates[model] = [(field, None, value)]
def get_related_updates(self):
"""
Returns a list of query objects: one for each update required to an
ancestor model. Each query will have the same filtering conditions as
the current query but will only update a single table.
"""
if not self.related_updates:
return []
result = []
for model, values in self.related_updates.iteritems():
query = UpdateQuery(model)
query.values = values
if self.related_ids is not None:
query.add_filter(('pk__in', self.related_ids))
result.append(query)
return result
class InsertQuery(Query):
compiler = 'SQLInsertCompiler'
def __init__(self, *args, **kwargs):
super(InsertQuery, self).__init__(*args, **kwargs)
self.fields = []
self.objs = []
def clone(self, klass=None, **kwargs):
extras = {
'fields': self.fields[:],
'objs': self.objs[:],
'raw': self.raw,
}
extras.update(kwargs)
return super(InsertQuery, self).clone(klass, **extras)
def insert_values(self, fields, objs, raw=False):
"""
Set up the insert query from the 'insert_values' dictionary. The
dictionary gives the model field names and their target values.
If 'raw_values' is True, the values in the 'insert_values' dictionary
are inserted directly into the query, rather than passed as SQL
parameters. This provides a way to insert NULL and DEFAULT keywords
into the query, for example.
"""
self.fields = fields
# Check that no Promise object reaches the DB. Refs #10498.
for field in fields:
for obj in objs:
value = getattr(obj, field.attname)
if isinstance(value, Promise):
setattr(obj, field.attname, force_unicode(value))
self.objs = objs
self.raw = raw
class DateQuery(Query):
"""
A DateQuery is a normal query, except that it specifically selects a single
date field. This requires some special handling when converting the results
back to Python objects, so we put it in a separate class.
"""
compiler = 'SQLDateCompiler'
def add_date_select(self, field_name, lookup_type, order='ASC'):
"""
Converts the query into a date extraction query.
"""
try:
result = self.setup_joins(
field_name.split(LOOKUP_SEP),
self.get_meta(),
self.get_initial_alias(),
False
)
except FieldError:
raise FieldDoesNotExist("%s has no field named '%s'" % (
self.model._meta.object_name, field_name
))
field = result[0]
assert isinstance(field, DateField), "%r isn't a DateField." \
% field.name
alias = result[3][-1]
select = Date((alias, field.column), lookup_type)
self.select = [select]
self.select_fields = [None]
self.select_related = False # See #7097.
self.set_extra_mask([])
self.distinct = True
self.order_by = order == 'ASC' and [1] or [-1]
if field.null:
self.add_filter(("%s__isnull" % field_name, False))
class AggregateQuery(Query):
"""
An AggregateQuery takes another query as a parameter to the FROM
clause and only selects the elements in the provided list.
"""
compiler = 'SQLAggregateCompiler'
def add_subquery(self, query, using):
self.subquery, self.sub_params = query.get_compiler(using).as_sql(with_col_aliases=True)
| gpl-3.0 |
anak10thn/graphics-dojo-qt5 | dragmove/dragmovecharm.py | 1 | 3229 | #############################################################################
##
## Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
## Contact: Qt Software Information (qt-info@nokia.com)
##
## This file is part of the Graphics Dojo project on Qt Labs.
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 or 3.0 as published by the Free Software Foundation
## and appearing in the file LICENSE.GPL included in the packaging of
## this file. Please review the following information to ensure GNU
## General Public Licensing requirements will be met:
## http://www.fsf.org/licensing/licenses/info/GPLv2.html and
## http://www.gnu.org/copyleft/gpl.html.
##
## If you are unsure which license is appropriate for your use, please
## contact the sales department at qt-sales@nokia.com.
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
#############################################################################
from PyQt4.QtCore import QEvent, QObject, QPoint, Qt
from PyQt4.QtGui import QMouseEvent, QWidget
class DragMoveData:
def __init__(self):
self.isMoving = False
self.startDrag = QPoint()
class DragMoveCharm(QObject):
def __init__(self, parent = None):
QObject.__init__(self, parent)
self.dragMoveData = {}
def activateOn(self, widget):
if widget in self.dragMoveData:
return
data = DragMoveData()
data.startDrag = QPoint(0, 0)
data.isMoving = False
self.dragMoveData[widget] = data
widget.installEventFilter(self)
def deactivateFrom(self, widget):
del self.dragMoveData[widget]
self.dragMoveData.remove(widget)
widget.removeEventFilter(self)
def eventFilter(self, object, event):
if not isinstance(object, QWidget):
return False
widget = object
type = event.type()
if type != QEvent.MouseButtonPress and \
type != QEvent.MouseButtonRelease and \
type != QEvent.MouseMove:
return False
if isinstance(event, QMouseEvent):
if event.modifiers() != Qt.NoModifier:
return False
button = event.button()
mouseEvent = event
try:
data = self.dragMoveData[widget]
except KeyError:
return False
consumed = False
if type == QEvent.MouseButtonPress and button == Qt.LeftButton:
data.startDrag = QPoint(mouseEvent.globalPos())
data.isMoving = True
event.accept()
consumed = True
if type == QEvent.MouseButtonRelease:
data.startDrag = QPoint(0, 0)
data.isMoving = False
if type == QEvent.MouseMove and data.isMoving:
pos = mouseEvent.globalPos()
widget.move(widget.pos() + pos - data.startDrag)
data.startDrag = QPoint(pos)
consumed = True
return consumed
| gpl-2.0 |
Workday/OpenFrame | native_client_sdk/src/build_tools/tests/verify_filelist_test.py | 132 | 3854 | #!/usr/bin/env python
# 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.
import os
import sys
import unittest
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BUILD_TOOLS_DIR = os.path.dirname(SCRIPT_DIR)
sys.path.append(BUILD_TOOLS_DIR)
import verify_filelist
def Verify(platform, rules_contents, directory_list):
rules = verify_filelist.Rules('test', platform, rules_contents)
rules.VerifyDirectoryList(directory_list)
class VerifyFilelistTestCase(unittest.TestCase):
def testBasic(self):
rules = """\
foo/file1
foo/file2
foo/file3
bar/baz/other
"""
dirlist = ['foo/file1', 'foo/file2', 'foo/file3', 'bar/baz/other']
Verify('linux', rules, dirlist)
def testGlob(self):
rules = 'foo/*'
dirlist = ['foo/file1', 'foo/file2', 'foo/file3/and/subdir']
Verify('linux', rules, dirlist)
def testPlatformVar(self):
rules = 'dir/${PLATFORM}/blah'
dirlist = ['dir/linux/blah']
Verify('linux', rules, dirlist)
def testPlatformVarGlob(self):
rules = 'dir/${PLATFORM}/*'
dirlist = ['dir/linux/file1', 'dir/linux/file2']
Verify('linux', rules, dirlist)
def testPlatformRule(self):
rules = """\
[linux]dir/linux/only
all/platforms
"""
linux_dirlist = ['dir/linux/only', 'all/platforms']
other_dirlist = ['all/platforms']
Verify('linux', rules, linux_dirlist)
Verify('mac', rules, other_dirlist)
def testMultiPlatformRule(self):
rules = """\
[linux,win]dir/no/macs
all/platforms
"""
nonmac_dirlist = ['dir/no/macs', 'all/platforms']
mac_dirlist = ['all/platforms']
Verify('linux', rules, nonmac_dirlist)
Verify('win', rules, nonmac_dirlist)
Verify('mac', rules, mac_dirlist)
def testPlatformRuleBadPlatform(self):
rules = '[frob]bad/platform'
self.assertRaises(verify_filelist.ParseException, Verify,
'linux', rules, [])
def testMissingFile(self):
rules = """\
foo/file1
foo/missing
"""
dirlist = ['foo/file1']
self.assertRaises(verify_filelist.VerifyException, Verify,
'linux', rules, dirlist)
def testExtraFile(self):
rules = 'foo/file1'
dirlist = ['foo/file1', 'foo/extra_file']
self.assertRaises(verify_filelist.VerifyException, Verify,
'linux', rules, dirlist)
def testEmptyGlob(self):
rules = 'foo/*'
dirlist = ['foo'] # Directory existing is not enough!
self.assertRaises(verify_filelist.VerifyException, Verify,
'linux', rules, dirlist)
def testBadGlob(self):
rules = '*/foo/bar'
dirlist = []
self.assertRaises(verify_filelist.ParseException, Verify,
'linux', rules, dirlist)
def testUnknownPlatform(self):
rules = 'foo'
dirlist = ['foo']
for platform in ('linux', 'mac', 'win'):
Verify(platform, rules, dirlist)
self.assertRaises(verify_filelist.ParseException, Verify,
'foobar', rules, dirlist)
def testUnexpectedPlatformFile(self):
rules = '[mac,win]foo/file1'
dirlist = ['foo/file1']
self.assertRaises(verify_filelist.VerifyException, Verify,
'linux', rules, dirlist)
def testWindowsPaths(self):
if os.path.sep != '/':
rules = 'foo/bar/baz'
dirlist = ['foo\\bar\\baz']
Verify('win', rules, dirlist)
else:
rules = 'foo/bar/baz\\foo'
dirlist = ['foo/bar/baz\\foo']
Verify('linux', rules, dirlist)
def testNestedGlobs(self):
rules = """\
foo/*
foo/bar/*"""
dirlist = ['foo/file', 'foo/bar/file']
Verify('linux', rules, dirlist)
rules = """\
foo/bar/*
foo/*"""
dirlist = ['foo/file', 'foo/bar/file']
Verify('linux', rules, dirlist)
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
julianwang/cinder | cinder/tests/unit/test_huawei_18000.py | 6 | 40275 | # Copyright (c) 2013 - 2014 Huawei Technologies Co., Ltd.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
""" Tests for huawei 18000 storage."""
import json
import os
import shutil
import tempfile
import time
from xml.dom import minidom
import mock
from oslo_log import log as logging
from cinder import exception
from cinder import test
from cinder.volume import configuration as conf
from cinder.volume.drivers.huawei import huawei_18000
from cinder.volume.drivers.huawei import rest_common
LOG = logging.getLogger(__name__)
test_volume = {'name': 'volume-21ec7341-9256-497b-97d9-ef48edcf0635',
'size': 2,
'volume_name': 'vol1',
'id': '21ec7341-9256-497b-97d9-ef48edcf0635',
'volume_id': '21ec7341-9256-497b-97d9-ef48edcf0635',
'provider_auth': None,
'project_id': 'project',
'display_name': 'vol1',
'display_description': 'test volume',
'volume_type_id': None,
'provider_location': '11'}
test_snap = {'name': 'volume-21ec7341-9256-497b-97d9-ef48edcf0635',
'size': 1,
'volume_name': 'vol1',
'id': '21ec7341-9256-497b-97d9-ef48edcf0635',
'volume_id': '21ec7341-9256-497b-97d9-ef48edcf0635',
'provider_auth': None,
'project_id': 'project',
'display_name': 'vol1',
'display_description': 'test volume',
'volume_type_id': None,
'provider_location': '11'}
FakeConnector = {'initiator': 'iqn.1993-08.debian:01:ec2bff7ac3a3',
'wwpns': ['10000090fa0d6754'],
'wwnns': ['10000090fa0d6755'],
'host': 'ubuntuc'}
def find_data(method):
if method is None:
data = """{"error":{"code":0},
"data":{"ID":"1",
"NAME":"5mFHcBv4RkCcD+JyrWc0SA"}}"""
if method == 'GET':
data = """{"error":{"code":0},
"data":[{"ID":"1",
"NAME":"IexzQZJWSXuX2e9I7c8GNQ"}]}"""
return data
def find_data_lun(method):
if method == 'GET':
data = """{"error":{"code":0},
"data":{"ID":"1",
"NAME":"IexzQZJWSXuX2e9I7c8GNQ",
"HEALTHSTATUS":"1",
"RUNNINGSTATUS":"27"}}"""
return data
def find_data_lungroup(method):
if method is None:
data = '{"error":{"code":0},\
"data":{"NAME":"5mFHcBv4RkCcD+JyrWc0SA",\
"DESCRIPTION":"5mFHcBv4RkCcD+JyrWc0SA",\
"ID":"11",\
"TYPE":256}}'
if method == "GET":
data = """{"error":{"code":0},
"data":[{
"NAME":"OpenStack_LunGroup_1",
"DESCRIPTION":"5mFHcBv4RkCcD+JyrWc0SA",
"ID":"11",
"TYPE":256}]}"""
if method == "DELETE":
data = """{"error":{"code":0},
"data":[{
"NAME":"IexzQZJWSXuX2e9I7c8GNQ",
"DESCRIPTION":"5mFHcBv4RkCcD+JyrWc0SA",
"ID":"11",
"TYPE":256}]}"""
return data
def find_data_hostgroup(method):
if method is None:
data = """{"error":{"code":0},"data":{
"NAME":"ubuntuc",
"DESCRIPTION":"",
"ID":"0",
"TYPE":14}}"""
if method == "GET":
data = """{"error":{"code":0},"data":[{
"NAME":"ubuntuc",
"DESCRIPTION":"",
"ID":"0","TYPE":14}]}"""
return data
def Fake_sleep(time):
pass
def find_data_mappingview(method, other_flag):
if method is None:
data = """{"error":{"code":0},"data":
{"WORKMODE":"255","HEALTHSTATUS":"1",
"NAME":"mOWtSXnaQKi3hpB3tdFRIQ",
"RUNNINGSTATUS":"27","DESCRIPTION":"",
"ENABLEINBANDCOMMAND":"true",
"ID":"1","INBANDLUNWWN":"",
"TYPE":245}}
"""
if method == "GET":
if other_flag:
data = """{"error":{"code":0},"data":[
{"WORKMODE":"255","HEALTHSTATUS":"1",
"NAME":"mOWtSXnaQKi3hpB3tdFRIQ",
"RUNNINGSTATUS":"27","DESCRIPTION":"",
"ENABLEINBANDCOMMAND":"true","ID":"1",
"INBANDLUNWWN":"","TYPE":245},
{"WORKMODE":"255","HEALTHSTATUS":"1",
"NAME":"YheUoRwbSX2BxN767nvLSw",
"RUNNINGSTATUS":"27","DESCRIPTION":"",
"ENABLEINBANDCOMMAND":"true",
"ID":"2","INBANDLUNWWN":"",
"TYPE":245}]}
"""
else:
data = """{"error":{"code":0},"data":[
{"WORKMODE":"255","HEALTHSTATUS":"1",
"NAME":"IexzQZJWSXuX2e9I7c8GNQ",
"RUNNINGSTATUS":"27","DESCRIPTION":"",
"ENABLEINBANDCOMMAND":"true","ID":"1",
"INBANDLUNWWN":"","TYPE":245},
{"WORKMODE":"255","HEALTHSTATUS":"1",
"NAME":"YheUoRwbSX2BxN767nvLSw",
"RUNNINGSTATUS":"27","DESCRIPTION":"",
"ENABLEINBANDCOMMAND":"true","ID":"2",
"INBANDLUNWWN":"","TYPE":245}]}
"""
return data
def find_data_snapshot(method):
if method is None:
data = '{"error":{"code":0},"data":{"ID":11,"NAME":"YheUoRwbSX2BxN7"}}'
if method == "GET":
data = """{"error":{"code":0},"data":[
{"ID":11,"NAME":"SDFAJSDFLKJ"},
{"ID":12,"NAME":"SDFAJSDFLKJ2"}]}"""
return data
def find_data_host(method):
if method is None:
data = """{"error":{"code":0},
"data":
{"PARENTTYPE":245,
"NAME":"Default Host",
"DESCRIPTION":"",
"RUNNINGSTATUS":"1",
"IP":"",
"PARENTNAME":"0",
"OPERATIONSYSTEM":"1",
"LOCATION":"",
"HEALTHSTATUS":"1",
"MODEL":"",
"ID":"0",
"PARENTID":"0",
"NETWORKNAME":"",
"TYPE":21}} """
if method == "GET":
data = """{"error":{"code":0},
"data":[
{"PARENTTYPE":245,"NAME":"ubuntuc",
"DESCRIPTION":"","RUNNINGSTATUS":"1",
"IP":"","PARENTNAME":"",
"OPERATIONSYSTEM":"0","LOCATION":"",
"HEALTHSTATUS":"1","MODEL":"",
"ID":"1","PARENTID":"",
"NETWORKNAME":"","TYPE":21},
{"PARENTTYPE":245,"NAME":"ubuntu",
"DESCRIPTION":"","RUNNINGSTATUS":"1",
"IP":"","PARENTNAME":"","OPERATIONSYSTEM":"0",
"LOCATION":"","HEALTHSTATUS":"1",
"MODEL":"","ID":"2","PARENTID":"",
"NETWORKNAME":"","TYPE":21}]} """
return data
def find_data_host_associate(method):
if (method is None) or (method == "GET"):
data = '{"error":{"code":0}}'
return data
def data_session(url):
if url == "/xx/sessions":
data = """{"error":{"code":0},
"data":{"username":"admin",
"iBaseToken":"2001031430",
"deviceid":"210235G7J20000000000"}}"""
if url == "sessions":
data = '{"error":{"code":0},"data":{"ID":11}}'
return data
def data_lun(url, method):
if url == "lun":
data = find_data(method)
if url == "lun/1":
data = find_data_lun(method)
if url == "lun?range=[0-65535]":
data = find_data(method)
if url == "lungroup?range=[0-8191]":
data = find_data_lungroup(method)
if url == "lungroup":
data = find_data_lungroup(method)
if url == "lungroup/associate":
data = """{"error":{"code":0},
"data":{"NAME":"5mFHcBv4RkCcD+JyrWc0SA",
"DESCRIPTION":"5mFHcBv4RkCcD+JyrWc0SA",
"ID":"11",
"TYPE":256}}"""
return data
def data_host(url, method):
if url == "hostgroup":
data = find_data_hostgroup(method)
if url == "hostgroup?range=[0-8191]":
data = find_data_hostgroup(method)
if url == "host":
data = find_data_host(method)
if url == "host?range=[0-65534]":
data = find_data_host(method)
if url == "host/associate":
data = find_data_host_associate(method)
if url == "host/associate?TYPE=21&ASSOCIATEOBJTYPE=14&ASSOCIATEOBJID=0":
data = find_data_host_associate(method)
return data
def find_data_storagepool_snapshot(url, method):
if url == "storagepool":
data = """{"error":{"code":0},
"data":[{"USERFREECAPACITY":"985661440",
"ID":"0",
"NAME":"OpenStack_Pool",
"USERTOTALCAPACITY":"985661440"
}]}"""
if url == "snapshot":
data = find_data_snapshot(method)
if url == "snapshot/activate":
data = """{"error":{"code":0},"data":[
{"ID":11,"NAME":"SDFAJSDFLKJ"},
{"ID":12,"NAME":"SDFAJSDFLKJ"}]}"""
return data
def find_data_luncpy_range_eth_port(url):
if url == "luncopy":
data = """{"error":{"code":0},
"data":{"COPYSTOPTIME":"-1",
"HEALTHSTATUS":"1",
"NAME":"w1PSNvu6RumcZMmSh4/l+Q==",
"RUNNINGSTATUS":"36",
"DESCRIPTION":"w1PSNvu6RumcZMmSh4/l+Q==",
"ID":"0","LUNCOPYTYPE":"1",
"COPYPROGRESS":"0","COPYSPEED":"2",
"TYPE":219,"COPYSTARTTIME":"-1"}}"""
if url == "LUNCOPY?range=[0-100000]":
data = """{"error":{"code":0},
"data":[{"COPYSTOPTIME":"1372209335",
"HEALTHSTATUS":"1",
"NAME":"w1PSNvu6RumcZMmSh4/l+Q==",
"RUNNINGSTATUS":"40",
"DESCRIPTION":"w1PSNvu6RumcZMmSh4/l+Q==",
"ID":"0","LUNCOPYTYPE":"1",
"COPYPROGRESS":"100",
"COPYSPEED":"2",
"TYPE":219,
"COPYSTARTTIME":"1372209329"}]}"""
if url == "eth_port":
data = """{"error":{"code":0},
"data":[{"PARENTTYPE":209,
"MACADDRESS":"00:22:a1:0a:79:57",
"ETHNEGOTIATE":"-1","ERRORPACKETS":"0",
"IPV4ADDR":"192.168.100.2",
"IPV6GATEWAY":"","IPV6MASK":"0",
"OVERFLOWEDPACKETS":"0","ISCSINAME":"P0",
"HEALTHSTATUS":"1","ETHDUPLEX":"2",
"ID":"16909568","LOSTPACKETS":"0",
"TYPE":213,"NAME":"P0","INIORTGT":"4",
"RUNNINGSTATUS":"10","IPV4GATEWAY":"",
"BONDNAME":"","STARTTIME":"1371684218",
"SPEED":"1000","ISCSITCPPORT":"0",
"IPV4MASK":"255.255.0.0","IPV6ADDR":"",
"LOGICTYPE":"0","LOCATION":"ENG0.B5.P0",
"MTU":"1500","PARENTID":"1.5"}]}"""
return data
class Fake18000Common(rest_common.RestCommon):
def __init__(self, configuration):
rest_common.RestCommon.__init__(self, configuration)
self.test_normal = True
self.other_flag = True
self.associate_flag = True
self.connect_flag = False
self.delete_flag = False
self.terminateFlag = False
self.deviceid = None
def _change_file_mode(self, filepath):
pass
def _parse_volume_type(self, volume):
poolinfo = self._find_pool_info()
volume_size = self._get_volume_size(poolinfo, volume)
params = {'LUNType': 0,
'WriteType': '1',
'PrefetchType': '3',
'qos_level': 'Qos-high',
'StripUnitSize': '64',
'PrefetchValue': '0',
'PrefetchTimes': '0',
'qos': 'OpenStack_Qos_High',
'MirrorSwitch': '1',
'tier': 'Tier_high'}
params['volume_size'] = volume_size
params['pool_id'] = poolinfo['ID']
return params
def _get_snapshotid_by_name(self, snapshot_name):
return "11"
def _get_qosid_by_lunid(self, lunid):
return ""
def _check_snapshot_exist(self, snapshot_id):
return True
def fc_initiator_data(self):
data = """{"error":{"code":0},"data":[
{"HEALTHSTATUS":"1","NAME":"",
"MULTIPATHTYPE":"1","ISFREE":"true",
"RUNNINGSTATUS":"27","ID":"10000090fa0d6754",
"OPERATIONSYSTEM":"255","TYPE":223},
{"HEALTHSTATUS":"1","NAME":"",
"MULTIPATHTYPE":"1","ISFREE":"true",
"RUNNINGSTATUS":"27","ID":"10000090fa0d6755",
"OPERATIONSYSTEM":"255","TYPE":223}]}"""
return data
def host_link(self):
data = """{"error":{"code":0},
"data":[{"PARENTTYPE":21,
"TARGET_ID":"0000000000000000",
"INITIATOR_NODE_WWN":"20000090fa0d6754",
"INITIATOR_TYPE":"223",
"RUNNINGSTATUS":"27",
"PARENTNAME":"ubuntuc",
"INITIATOR_ID":"10000090fa0d6754",
"TARGET_PORT_WWN":"24000022a10a2a39",
"HEALTHSTATUS":"1",
"INITIATOR_PORT_WWN":"10000090fa0d6754",
"ID":"010000090fa0d675-0000000000110400",
"TARGET_NODE_WWN":"21000022a10a2a39",
"PARENTID":"1","CTRL_ID":"0",
"TYPE":255,"TARGET_TYPE":"212"}]}"""
self.connect_flag = True
return data
def call(self, url=False, data=None, method=None):
url = url.replace('http://100.115.10.69:8082/deviceManager/rest', '')
url = url.replace('/210235G7J20000000000/', '')
data = None
if self.test_normal:
if url == "/xx/sessions" or url == "sessions":
data = data_session(url)
if url == "lun/count?TYPE=11&ASSOCIATEOBJTYPE=256&"\
"ASSOCIATEOBJID=11":
data = """{"data":{"COUNT":"7"},
"error":{"code":0,"description":"0"}}"""
if url == "lungroup/associate?TYPE=256&ASSOCIATEOBJTYPE=11&"\
"ASSOCIATEOBJID=11":
data = """{"error":{"code":0},
"data":[{"ID":11}]}"""
if url == "storagepool" or url == "snapshot" or url == "snaps"\
"hot/activate":
data = find_data_storagepool_snapshot(url, method)
if url == "lungroup" or url == "lungroup/associate"\
or url == "lun" or url == "lun/1":
data = data_lun(url, method)
if url == "lun?range=[0-65535]" or url == "lungroup?r"\
"ange=[0-8191]":
data = data_lun(url, method)
if url == "lungroup/associate?ID=11"\
"&ASSOCIATEOBJTYPE=11&ASSOCIATEOBJID=11"\
or url == "lungroup/associate?ID=12"\
"&ASSOCIATEOBJTYPE=11&ASSOCIATEOBJID=12":
data = '{"error":{"code":0}}'
self.terminateFlag = True
if url == "fc_initiator/10000090fa0d6754" or url == "lun/11"\
or url == "LUNCOPY/0"\
or url == "mappingview/REMOVE_ASSOCIATE":
data = '{"error":{"code":0}}'
self.delete_flag = True
if url == "LUNCOPY/start" or url == "mappingview/1"\
or url == "hostgroup/associate":
data = '{"error":{"code":0}}'
if url == "MAPPINGVIEW/CREATE_ASSOCIATE" or url == "snapshot/11"\
or url == "snapshot/stop" or url == "LUNGroup/11":
data = '{"error":{"code":0}}'
self.delete_flag = True
if url == "luncopy" or url == "eth_port" or url == "LUNC"\
"OPY?range=[0-100000]":
data = find_data_luncpy_range_eth_port(url)
if url == "iscsidevicename":
data = """{"error":{"code":0},
"data":[{"CMO_ISCSI_DEVICE_NAME":
"iqn.2006-08.com.huawei:oceanstor:21000022a10a2a39:iscsinametest"}]}"""
if url == "hostgroup" or url == "host" or url == "host/associate":
data = data_host(url, method)
if url == "host/associate?TYPE=21&ASSOCIATEOBJTYPE=14&AS"\
"SOCIATEOBJID=0":
data = data_host(url, method)
if url == "hostgroup?range=[0-8191]" or url == "host?ra"\
"nge=[0-65534]":
data = data_host(url, method)
if url == "iscsi_initiator/iqn.1993-08.debian:01:ec2bff7ac3a3":
data = """{"error":{"code":0},"data":{
"ID":"iqn.1993-08.debian:01:ec2bff7ac3a3",
"NAME":"iqn.1993-08.debian:01:ec2bff7ac3a3",
"ISFREE":"True"}}"""
if url == "iscsi_initiator" or url == "iscsi_initiator/"\
or url == "iscsi_initiator?range=[0-65535]":
data = '{"error":{"code":0}}'
if url == "mappingview" or url == "mappingview?range=[0-65535]":
data = find_data_mappingview(method, self.other_flag)
if (url == ("lun/associate?ID=1&TYPE=11&"
"ASSOCIATEOBJTYPE=21&ASSOCIATEOBJID=0")
or url == ("lun/associate?TYPE=11&ASSOCIATEOBJTYPE=256"
"&ASSOCIATEOBJID=11")
or (url == ("lun/associate?TYPE=11&ASSOCIATEOBJTYPE=256"
"&ASSOCIATEOBJID=12")
and not self.associate_flag)):
data = '{"error":{"code":0},"data":[{"ID":"11"}]}'
if ((url == ("lun/associate?TYPE=11&ASSOCIATEOBJTYPE=256"
"&ASSOCIATEOBJID=12"))
and self.associate_flag):
data = '{"error":{"code":0},"data":[{"ID":"12"}]}'
if url == "fc_initiator?ISFREE=true&range=[0-1000]":
data = self.fc_initiator_data()
if url == "host_link?INITIATOR_TYPE=223&INITIATOR_PORT_WWN="\
"10000090fa0d6754":
data = self.host_link()
if url == "mappingview/associate?TYPE=245&"\
"ASSOCIATEOBJTYPE=14&ASSOCIATEOBJID=0"\
or url == "mappingview/associate?TYPE=245&"\
"ASSOCIATEOBJTYPE=256&ASSOCIATEOBJID=11":
data = '{"error":{"code":0},"data":[{"ID":11,"NAME":"test"}]}'
if url == "lun/associate?TYPE=11&"\
"ASSOCIATEOBJTYPE=21&ASSOCIATEOBJID=1":
data = '{"error":{"code":0}}'
self.connect_flag = True
if url == "iscsi_tgt_port":
data = '{"data":[{"ETHPORTID":"139267",\
"ID":"iqn.oceanstor:21004846fb8ca15f::22003:111.111.101.244",\
"TPGT":"8196","TYPE":249}],\
"error":{"code":0,"description":"0"}}'
else:
data = '{"error":{"code":31755596}}'
if (url == "lun/11") and (method == "GET"):
data = """{"error":{"code":0},"data":{"ID":"11",
"IOCLASSID":"11",
"NAME":"5mFHcBv4RkCcD+JyrWc0SA"}}"""
res_json = json.loads(data)
return res_json
class Fake18000Storage(huawei_18000.Huawei18000ISCSIDriver):
"""Fake Huawei Storage, Rewrite some methods of HuaweiISCSIDriver."""
def __init__(self, configuration):
super(Fake18000Storage, self).__init__(configuration)
self.configuration = configuration
def do_setup(self):
self.common = Fake18000Common(configuration=self.configuration)
class Fake18000FCStorage(huawei_18000.Huawei18000FCDriver):
"""Fake Huawei Storage, Rewrite some methods of HuaweiISCSIDriver."""
def __init__(self, configuration):
super(Fake18000FCStorage, self).__init__(configuration)
self.configuration = configuration
def do_setup(self):
self.common = Fake18000Common(configuration=self.configuration)
class Huawei18000ISCSIDriverTestCase(test.TestCase):
def setUp(self):
super(Huawei18000ISCSIDriverTestCase, self).setUp()
self.tmp_dir = tempfile.mkdtemp()
self.fake_conf_file = self.tmp_dir + '/cinder_huawei_conf.xml'
self.addCleanup(shutil.rmtree, self.tmp_dir)
self.create_fake_conf_file()
self.addCleanup(os.remove, self.fake_conf_file)
self.configuration = mock.Mock(spec=conf.Configuration)
self.configuration.cinder_huawei_conf_file = self.fake_conf_file
self.stubs.Set(time, 'sleep', Fake_sleep)
driver = Fake18000Storage(configuration=self.configuration)
self.driver = driver
self.driver.do_setup()
self.driver.common.test_normal = True
def testloginSuccess(self):
deviceid = self.driver.common.login()
self.assertEqual(deviceid, '210235G7J20000000000')
def testcreatevolumesuccess(self):
self.driver.common.login()
lun_info = self.driver.create_volume(test_volume)
self.assertEqual(lun_info['provider_location'], '1')
self.assertEqual(lun_info['lun_info']['NAME'],
'5mFHcBv4RkCcD+JyrWc0SA')
def testcreatesnapshotsuccess(self):
self.driver.common.login()
lun_info = self.driver.create_snapshot(test_volume)
self.assertEqual(lun_info['provider_location'], 11)
self.assertEqual(lun_info['lun_info']['NAME'], 'YheUoRwbSX2BxN7')
def testdeletevolumesuccess(self):
self.driver.common.login()
self.driver.common.delete_flag = False
self.driver.delete_volume(test_volume)
self.assertTrue(self.driver.common.delete_flag)
def testdeletesnapshotsuccess(self):
self.driver.common.login()
self.driver.common.delete_flag = False
self.driver.delete_snapshot(test_snap)
self.assertTrue(self.driver.common.delete_flag)
def testcolonevolumesuccess(self):
self.driver.common.login()
lun_info = self.driver.create_cloned_volume(test_volume,
test_volume)
self.assertEqual(lun_info['provider_location'], '1')
self.assertEqual(lun_info['lun_info']['NAME'],
'5mFHcBv4RkCcD+JyrWc0SA')
def testcreateolumefromsnapsuccess(self):
self.driver.common.login()
lun_info = self.driver.create_volume_from_snapshot(test_volume,
test_volume)
self.assertEqual(lun_info['provider_location'], '1')
self.assertEqual(lun_info['lun_info']['NAME'],
'5mFHcBv4RkCcD+JyrWc0SA')
def testinitializeconnectionsuccess(self):
self.driver.common.login()
iscsi_properties = self.driver.initialize_connection(test_volume,
FakeConnector)
self.assertEqual(iscsi_properties['data']['target_lun'], 1)
def testterminateconnectionsuccess(self):
self.driver.common.login()
self.driver.common.terminateFlag = False
self.driver.terminate_connection(test_volume, FakeConnector)
self.assertTrue(self.driver.common.terminateFlag)
def testinitializeconnectionnoviewsuccess(self):
self.driver.common.login()
self.driver.common.other_flag = False
self.driver.common.connect_flag = False
self.driver.initialize_connection(test_volume, FakeConnector)
self.assertTrue(self.driver.common.connect_flag)
def testterminateconnectionoviewnsuccess(self):
self.driver.common.login()
self.driver.common.terminateFlag = False
self.driver.terminate_connection(test_volume, FakeConnector)
self.assertTrue(self.driver.common.terminateFlag)
def testgetvolumestatus(self):
self.driver.common.login()
data = self.driver.get_volume_stats()
self.assertEqual(data['driver_version'], '1.1.0')
def testloginfail(self):
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException, self.driver.common.login)
def testcreatesnapshotfail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.create_snapshot, test_volume)
def testcreatevolumefail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.create_volume, test_volume)
def testdeletevolumefail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.delete_volume, test_volume)
def testdeletesnapshotfail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.delete_snapshot, test_volume)
def testinitializeconnectionfail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.initialize_connection,
test_volume, FakeConnector)
def testgetdefaulttimeout(self):
result = self.driver.common._get_default_timeout()
self.assertEqual('43200', result)
def testgetwaitinterval(self):
result = self.driver.common._get_wait_interval('LUNReadyWaitInterval')
self.assertEqual('2', result)
def test_lun_is_associated_to_lungroup(self):
self.driver.common.login()
self.driver.common._associate_lun_to_lungroup('11', '11')
result = self.driver.common._is_lun_associated_to_lungroup('11', '11')
self.assertTrue(result)
def test_lun_is_not_associated_to_lun_group(self):
self.driver.common.login()
self.driver.common._associate_lun_to_lungroup('12', '12')
self.driver.common.associate_flag = True
result = self.driver.common._is_lun_associated_to_lungroup('12', '12')
self.assertTrue(result)
self.driver.common._remove_lun_from_lungroup('12', '12')
self.driver.common.associate_flag = False
result = self.driver.common._is_lun_associated_to_lungroup('12', '12')
self.assertFalse(result)
def create_fake_conf_file(self):
"""Create a fake Config file
Huawei storage customize a XML configuration file, the configuration
file is used to set the Huawei storage custom parameters, therefore,
in the UT test we need to simulate such a configuration file
"""
doc = minidom.Document()
config = doc.createElement('config')
doc.appendChild(config)
storage = doc.createElement('Storage')
config.appendChild(storage)
controllerip0 = doc.createElement('ControllerIP0')
controllerip0_text = doc.createTextNode('10.10.10.1')
controllerip0.appendChild(controllerip0_text)
storage.appendChild(controllerip0)
controllerip1 = doc.createElement('ControllerIP1')
controllerip1_text = doc.createTextNode('10.10.10.2')
controllerip1.appendChild(controllerip1_text)
storage.appendChild(controllerip1)
username = doc.createElement('UserName')
username_text = doc.createTextNode('admin')
username.appendChild(username_text)
storage.appendChild(username)
userpassword = doc.createElement('UserPassword')
userpassword_text = doc.createTextNode('Admin@storage')
userpassword.appendChild(userpassword_text)
storage.appendChild(userpassword)
url = doc.createElement('RestURL')
url_text = doc.createTextNode('http://100.115.10.69:8082/'
'deviceManager/rest/')
url.appendChild(url_text)
storage.appendChild(url)
lun = doc.createElement('LUN')
config.appendChild(lun)
storagepool = doc.createElement('StoragePool')
pool_text = doc.createTextNode('OpenStack_Pool')
storagepool.appendChild(pool_text)
lun.appendChild(storagepool)
timeout = doc.createElement('Timeout')
timeout_text = doc.createTextNode('43200')
timeout.appendChild(timeout_text)
lun.appendChild(timeout)
lun_ready_wait_interval = doc.createElement('LUNReadyWaitInterval')
lun_ready_wait_interval_text = doc.createTextNode('2')
lun_ready_wait_interval.appendChild(lun_ready_wait_interval_text)
lun.appendChild(lun_ready_wait_interval)
prefetch = doc.createElement('Prefetch')
prefetch.setAttribute('Type', '0')
prefetch.setAttribute('Value', '0')
lun.appendChild(prefetch)
iscsi = doc.createElement('iSCSI')
config.appendChild(iscsi)
defaulttargetip = doc.createElement('DefaultTargetIP')
defaulttargetip_text = doc.createTextNode('100.115.10.68')
defaulttargetip.appendChild(defaulttargetip_text)
iscsi.appendChild(defaulttargetip)
initiator = doc.createElement('Initiator')
initiator.setAttribute('Name', 'iqn.1993-08.debian:01:ec2bff7ac3a3')
initiator.setAttribute('TargetIP', '192.168.100.2')
iscsi.appendChild(initiator)
fakefile = open(self.fake_conf_file, 'w')
fakefile.write(doc.toprettyxml(indent=''))
fakefile.close()
class Huawei18000FCDriverTestCase(test.TestCase):
def setUp(self):
super(Huawei18000FCDriverTestCase, self).setUp()
self.tmp_dir = tempfile.mkdtemp()
self.fake_conf_file = self.tmp_dir + '/cinder_huawei_conf.xml'
self.addCleanup(shutil.rmtree, self.tmp_dir)
self.create_fake_conf_file()
self.addCleanup(os.remove, self.fake_conf_file)
self.configuration = mock.Mock(spec=conf.Configuration)
self.configuration.cinder_huawei_conf_file = self.fake_conf_file
self.stubs.Set(time, 'sleep', Fake_sleep)
driver = Fake18000FCStorage(configuration=self.configuration)
self.driver = driver
self.driver.do_setup()
self.driver.common.test_normal = True
def testloginSuccess(self):
deviceid = self.driver.common.login()
self.assertEqual(deviceid, '210235G7J20000000000')
def testcreatevolumesuccess(self):
self.driver.common.login()
lun_info = self.driver.create_volume(test_volume)
self.assertEqual(lun_info['provider_location'], '1')
self.assertEqual(lun_info['lun_info']['NAME'],
'5mFHcBv4RkCcD+JyrWc0SA')
def testcreatesnapshotsuccess(self):
self.driver.common.login()
lun_info = self.driver.create_snapshot(test_volume)
self.assertEqual(lun_info['provider_location'], 11)
self.assertEqual(lun_info['lun_info']['NAME'], 'YheUoRwbSX2BxN7')
def testdeletevolumesuccess(self):
self.driver.common.login()
self.driver.common.delete_flag = False
self.driver.delete_volume(test_volume)
self.assertTrue(self.driver.common.delete_flag)
def testdeletesnapshotsuccess(self):
self.driver.common.login()
self.driver.common.delete_flag = False
self.driver.delete_snapshot(test_snap)
self.assertTrue(self.driver.common.delete_flag)
def testcolonevolumesuccess(self):
self.driver.common.login()
lun_info = self.driver.create_cloned_volume(test_volume,
test_volume)
self.assertEqual(lun_info['provider_location'], '1')
self.assertEqual(lun_info['lun_info']['NAME'],
'5mFHcBv4RkCcD+JyrWc0SA')
def testcreateolumefromsnapsuccess(self):
self.driver.common.login()
volumeid = self.driver.create_volume_from_snapshot(test_volume,
test_volume)
self.assertEqual(volumeid['provider_location'], '1')
def testinitializeconnectionsuccess(self):
self.driver.common.login()
properties = self.driver.initialize_connection(test_volume,
FakeConnector)
self.assertEqual(properties['data']['target_lun'], 1)
def testterminateconnectionsuccess(self):
self.driver.common.login()
self.driver.common.terminateFlag = False
self.driver.terminate_connection(test_volume, FakeConnector)
self.assertTrue(self.driver.common.terminateFlag)
def testinitializeconnectionnoviewsuccess(self):
self.driver.common.login()
self.driver.common.other_flag = False
self.driver.common.connect_flag = False
self.driver.initialize_connection(test_volume, FakeConnector)
self.assertTrue(self.driver.common.connect_flag)
def testterminateconnectionoviewnsuccess(self):
self.driver.common.login()
self.driver.common.terminateFlag = False
self.driver.terminate_connection(test_volume, FakeConnector)
self.assertTrue(self.driver.common.terminateFlag)
def testgetvolumestatus(self):
self.driver.common.login()
data = self.driver.get_volume_stats()
self.assertEqual(data['driver_version'], '1.1.0')
def testloginfail(self):
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.common.login)
def testcreatesnapshotfail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.create_snapshot, test_volume)
def testcreatevolumefail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.create_volume, test_volume)
def testdeletevolumefail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.delete_volume, test_volume)
def testdeletesnapshotfail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.delete_snapshot, test_volume)
def testinitializeconnectionfail(self):
self.driver.common.login()
self.driver.common.test_normal = False
self.assertRaises(exception.CinderException,
self.driver.initialize_connection,
test_volume, FakeConnector)
def testgetdefaulttimeout(self):
result = self.driver.common._get_default_timeout()
self.assertEqual('43200', result)
def testgetwaitinterval(self):
result = self.driver.common._get_wait_interval('LUNReadyWaitInterval')
self.assertEqual('2', result)
def test_lun_is_associated_to_lungroup(self):
self.driver.common.login()
self.driver.common._associate_lun_to_lungroup('11', '11')
result = self.driver.common._is_lun_associated_to_lungroup('11', '11')
self.assertTrue(result)
def test_lun_is_not_associated_to_lun_group(self):
self.driver.common.login()
self.driver.common._associate_lun_to_lungroup('12', '12')
self.driver.common.associate_flag = True
result = self.driver.common._is_lun_associated_to_lungroup('12', '12')
self.assertTrue(result)
self.driver.common._remove_lun_from_lungroup('12', '12')
self.driver.common.associate_flag = False
result = self.driver.common._is_lun_associated_to_lungroup('12', '12')
self.assertFalse(result)
def create_fake_conf_file(self):
"""Create a fake Config file
Huawei storage customize a XML configuration file, the configuration
file is used to set the Huawei storage custom parameters, therefore,
in the UT test we need to simulate such a configuration file
"""
doc = minidom.Document()
config = doc.createElement('config')
doc.appendChild(config)
storage = doc.createElement('Storage')
config.appendChild(storage)
controllerip0 = doc.createElement('ControllerIP0')
controllerip0_text = doc.createTextNode('10.10.10.1')
controllerip0.appendChild(controllerip0_text)
storage.appendChild(controllerip0)
controllerip1 = doc.createElement('ControllerIP1')
controllerip1_text = doc.createTextNode('10.10.10.2')
controllerip1.appendChild(controllerip1_text)
storage.appendChild(controllerip1)
username = doc.createElement('UserName')
username_text = doc.createTextNode('admin')
username.appendChild(username_text)
storage.appendChild(username)
userpassword = doc.createElement('UserPassword')
userpassword_text = doc.createTextNode('Admin@storage')
userpassword.appendChild(userpassword_text)
storage.appendChild(userpassword)
url = doc.createElement('RestURL')
url_text = doc.createTextNode('http://100.115.10.69:8082/'
'deviceManager/rest/')
url.appendChild(url_text)
storage.appendChild(url)
lun = doc.createElement('LUN')
config.appendChild(lun)
storagepool = doc.createElement('StoragePool')
pool_text = doc.createTextNode('OpenStack_Pool')
storagepool.appendChild(pool_text)
lun.appendChild(storagepool)
timeout = doc.createElement('Timeout')
timeout_text = doc.createTextNode('43200')
timeout.appendChild(timeout_text)
lun.appendChild(timeout)
lun_ready_wait_interval = doc.createElement('LUNReadyWaitInterval')
lun_ready_wait_interval_text = doc.createTextNode('2')
lun_ready_wait_interval.appendChild(lun_ready_wait_interval_text)
lun.appendChild(lun_ready_wait_interval)
prefetch = doc.createElement('Prefetch')
prefetch.setAttribute('Type', '0')
prefetch.setAttribute('Value', '0')
lun.appendChild(prefetch)
iscsi = doc.createElement('iSCSI')
config.appendChild(iscsi)
defaulttargetip = doc.createElement('DefaultTargetIP')
defaulttargetip_text = doc.createTextNode('100.115.10.68')
defaulttargetip.appendChild(defaulttargetip_text)
iscsi.appendChild(defaulttargetip)
initiator = doc.createElement('Initiator')
initiator.setAttribute('Name', 'iqn.1993-08.debian:01:ec2bff7ac3a3')
initiator.setAttribute('TargetIP', '192.168.100.2')
iscsi.appendChild(initiator)
fakefile = open(self.fake_conf_file, 'w')
fakefile.write(doc.toprettyxml(indent=''))
fakefile.close()
| apache-2.0 |
dursk/django | django/contrib/gis/utils/ogrinfo.py | 564 | 1984 | """
This module includes some utility functions for inspecting the layout
of a GDAL data source -- the functionality is analogous to the output
produced by the `ogrinfo` utility.
"""
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.gdal.geometries import GEO_CLASSES
def ogrinfo(data_source, num_features=10):
"""
Walks the available layers in the supplied `data_source`, displaying
the fields for the first `num_features` features.
"""
# Checking the parameters.
if isinstance(data_source, str):
data_source = DataSource(data_source)
elif isinstance(data_source, DataSource):
pass
else:
raise Exception('Data source parameter must be a string or a DataSource object.')
for i, layer in enumerate(data_source):
print("data source : %s" % data_source.name)
print("==== layer %s" % i)
print(" shape type: %s" % GEO_CLASSES[layer.geom_type.num].__name__)
print(" # features: %s" % len(layer))
print(" srs: %s" % layer.srs)
extent_tup = layer.extent.tuple
print(" extent: %s - %s" % (extent_tup[0:2], extent_tup[2:4]))
print("Displaying the first %s features ====" % num_features)
width = max(*map(len, layer.fields))
fmt = " %%%ss: %%s" % width
for j, feature in enumerate(layer[:num_features]):
print("=== Feature %s" % j)
for fld_name in layer.fields:
type_name = feature[fld_name].type_name
output = fmt % (fld_name, type_name)
val = feature.get(fld_name)
if val:
if isinstance(val, str):
val_fmt = ' ("%s")'
else:
val_fmt = ' (%s)'
output += val_fmt % val
else:
output += ' (None)'
print(output)
# For backwards compatibility.
sample = ogrinfo
| bsd-3-clause |
JackMorris/CaiusHallHelper | main.py | 1 | 1768 | import sys
from datetime import date, timedelta
from configuration import Configuration
from service import raven_service, email_service
def main():
configuration_file_path = sys.argv[1]
configuration = Configuration(configuration_file_path)
_authenticate_services(configuration)
_make_user_bookings(configuration.users, 3)
_send_user_reports(configuration.users, 0)
def _authenticate_services(configuration):
""" Use `configuration` to authenticate raven_service and email_service.
:param configuration: Configuration instance for system configuration
"""
raven_service.set_default_credentials(configuration.default_crsid,
configuration.default_password)
email_service.set_email_credentials(configuration.gmail_username,
configuration.gmail_password)
def _make_user_bookings(users, days_in_advance):
""" Create bookings for each user in `users`.
:param users: list of Users to create bookings for
:param days_in_advance: how far in advance to book
:return: list of Booking instances containing all booked events
"""
date_to_book = date.today() + timedelta(days=days_in_advance)
bookings = []
for user in users:
bookings.append(user.create_booking(date_to_book))
return bookings
def _send_user_reports(users, days_in_advance):
""" Send reports to each user in `users`.
:param users: list of User instances to send reports to
:param days_in_advance: how many days in advance the reports should be for
"""
date_for_report = date.today() + timedelta(days=days_in_advance)
for user in users:
user.email_report(date_for_report)
if __name__ == '__main__':
main() | mit |
hehongliang/tensorflow | tensorflow/python/ops/linalg/linear_operator_diag.py | 12 | 9235 | # 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.
# ==============================================================================
"""`LinearOperator` acting like a diagonal matrix."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops.linalg import linalg_impl as linalg
from tensorflow.python.ops.linalg import linear_operator
from tensorflow.python.ops.linalg import linear_operator_util
from tensorflow.python.util.tf_export import tf_export
__all__ = ["LinearOperatorDiag",]
@tf_export("linalg.LinearOperatorDiag")
class LinearOperatorDiag(linear_operator.LinearOperator):
"""`LinearOperator` acting like a [batch] square diagonal matrix.
This operator acts like a [batch] diagonal matrix `A` with shape
`[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a
batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is
an `N x N` matrix. This matrix `A` is not materialized, but for
purposes of broadcasting this shape will be relevant.
`LinearOperatorDiag` is initialized with a (batch) vector.
```python
# Create a 2 x 2 diagonal linear operator.
diag = [1., -1.]
operator = LinearOperatorDiag(diag)
operator.to_dense()
==> [[1., 0.]
[0., -1.]]
operator.shape
==> [2, 2]
operator.log_abs_determinant()
==> scalar Tensor
x = ... Shape [2, 4] Tensor
operator.matmul(x)
==> Shape [2, 4] Tensor
# Create a [2, 3] batch of 4 x 4 linear operators.
diag = tf.random_normal(shape=[2, 3, 4])
operator = LinearOperatorDiag(diag)
# Create a shape [2, 1, 4, 2] vector. Note that this shape is compatible
# since the batch dimensions, [2, 1], are broadcast to
# operator.batch_shape = [2, 3].
y = tf.random_normal(shape=[2, 1, 4, 2])
x = operator.solve(y)
==> operator.matmul(x) = y
```
#### Shape compatibility
This operator acts on [batch] matrix with compatible shape.
`x` is a batch matrix with compatible shape for `matmul` and `solve` if
```
operator.shape = [B1,...,Bb] + [N, N], with b >= 0
x.shape = [C1,...,Cc] + [N, R],
and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd]
```
#### Performance
Suppose `operator` is a `LinearOperatorDiag` of shape `[N, N]`,
and `x.shape = [N, R]`. Then
* `operator.matmul(x)` involves `N * R` multiplications.
* `operator.solve(x)` involves `N` divisions and `N * R` multiplications.
* `operator.determinant()` involves a size `N` `reduce_prod`.
If instead `operator` and `x` have shape `[B1,...,Bb, N, N]` and
`[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`.
#### Matrix property hints
This `LinearOperator` is initialized with boolean flags of the form `is_X`,
for `X = non_singular, self_adjoint, positive_definite, square`.
These have the following meaning:
* If `is_X == True`, callers should expect the operator to have the
property `X`. This is a promise that should be fulfilled, but is *not* a
runtime assert. For example, finite floating point precision may result
in these promises being violated.
* If `is_X == False`, callers should expect the operator to not have `X`.
* If `is_X == None` (the default), callers should have no expectation either
way.
"""
def __init__(self,
diag,
is_non_singular=None,
is_self_adjoint=None,
is_positive_definite=None,
is_square=None,
name="LinearOperatorDiag"):
r"""Initialize a `LinearOperatorDiag`.
Args:
diag: Shape `[B1,...,Bb, N]` `Tensor` with `b >= 0` `N >= 0`.
The diagonal of the operator. Allowed dtypes: `float16`, `float32`,
`float64`, `complex64`, `complex128`.
is_non_singular: Expect that this operator is non-singular.
is_self_adjoint: Expect that this operator is equal to its hermitian
transpose. If `diag.dtype` is real, this is auto-set to `True`.
is_positive_definite: Expect that this operator is positive definite,
meaning the quadratic form `x^H A x` has positive real part for all
nonzero `x`. Note that we do not require the operator to be
self-adjoint to be positive-definite. See:
https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square: Expect that this operator acts like square [batch] matrices.
name: A name for this `LinearOperator`.
Raises:
TypeError: If `diag.dtype` is not an allowed type.
ValueError: If `diag.dtype` is real, and `is_self_adjoint` is not `True`.
"""
with ops.name_scope(name, values=[diag]):
self._diag = ops.convert_to_tensor(diag, name="diag")
self._check_diag(self._diag)
# Check and auto-set hints.
if not self._diag.dtype.is_complex:
if is_self_adjoint is False:
raise ValueError("A real diagonal operator is always self adjoint.")
else:
is_self_adjoint = True
if is_square is False:
raise ValueError("Only square diagonal operators currently supported.")
is_square = True
super(LinearOperatorDiag, self).__init__(
dtype=self._diag.dtype,
graph_parents=[self._diag],
is_non_singular=is_non_singular,
is_self_adjoint=is_self_adjoint,
is_positive_definite=is_positive_definite,
is_square=is_square,
name=name)
def _check_diag(self, diag):
"""Static check of diag."""
allowed_dtypes = [
dtypes.float16,
dtypes.float32,
dtypes.float64,
dtypes.complex64,
dtypes.complex128,
]
dtype = diag.dtype
if dtype not in allowed_dtypes:
raise TypeError(
"Argument diag must have dtype in %s. Found: %s"
% (allowed_dtypes, dtype))
if diag.get_shape().ndims is not None and diag.get_shape().ndims < 1:
raise ValueError("Argument diag must have at least 1 dimension. "
"Found: %s" % diag)
def _shape(self):
# If d_shape = [5, 3], we return [5, 3, 3].
d_shape = self._diag.get_shape()
return d_shape.concatenate(d_shape[-1:])
def _shape_tensor(self):
d_shape = array_ops.shape(self._diag)
k = d_shape[-1]
return array_ops.concat((d_shape, [k]), 0)
def _assert_non_singular(self):
return linear_operator_util.assert_no_entries_with_modulus_zero(
self._diag,
message="Singular operator: Diagonal contained zero values.")
def _assert_positive_definite(self):
if self.dtype.is_complex:
message = (
"Diagonal operator had diagonal entries with non-positive real part, "
"thus was not positive definite.")
else:
message = (
"Real diagonal operator had non-positive diagonal entries, "
"thus was not positive definite.")
return check_ops.assert_positive(
math_ops.real(self._diag),
message=message)
def _assert_self_adjoint(self):
return linear_operator_util.assert_zero_imag_part(
self._diag,
message=(
"This diagonal operator contained non-zero imaginary values. "
" Thus it was not self-adjoint."))
def _matmul(self, x, adjoint=False, adjoint_arg=False):
diag_term = math_ops.conj(self._diag) if adjoint else self._diag
x = linalg.adjoint(x) if adjoint_arg else x
diag_mat = array_ops.expand_dims(diag_term, -1)
return diag_mat * x
def _determinant(self):
return math_ops.reduce_prod(self._diag, axis=[-1])
def _log_abs_determinant(self):
log_det = math_ops.reduce_sum(
math_ops.log(math_ops.abs(self._diag)), axis=[-1])
if self.dtype.is_complex:
log_det = math_ops.cast(log_det, dtype=self.dtype)
return log_det
def _solve(self, rhs, adjoint=False, adjoint_arg=False):
diag_term = math_ops.conj(self._diag) if adjoint else self._diag
rhs = linalg.adjoint(rhs) if adjoint_arg else rhs
inv_diag_mat = array_ops.expand_dims(1. / diag_term, -1)
return rhs * inv_diag_mat
def _to_dense(self):
return array_ops.matrix_diag(self._diag)
def _diag_part(self):
return self.diag
def _add_to_tensor(self, x):
x_diag = array_ops.matrix_diag_part(x)
new_diag = self._diag + x_diag
return array_ops.matrix_set_diag(x, new_diag)
@property
def diag(self):
return self._diag
| apache-2.0 |
pombredanne/pytype | pytype/tests/test_attributes.py | 1 | 2408 | """Test instance and class attributes."""
from pytype.tests import test_inference
class TestAttributes(test_inference.InferenceTest):
"""Tests for attributes."""
def testSimpleAttribute(self):
with self.Infer("""
class A(object):
def method1(self):
self.a = 3
def method2(self):
self.a = 3j
""", deep=True, solve_unknowns=False, extract_locals=True) as ty:
self.assertTypesMatchPytd(ty, """
class A:
a: complex or int
def method1(self) -> NoneType
def method2(self) -> NoneType
""")
def testOutsideAttributeAccess(self):
with self.Infer("""
class A(object):
pass
def f1():
A().a = 3
def f2():
A().a = 3j
""", deep=True, solve_unknowns=False, extract_locals=True) as ty:
self.assertTypesMatchPytd(ty, """
class A:
a: complex or int
def f1() -> NoneType
def f2() -> NoneType
""")
def testPrivate(self):
with self.Infer("""
class C(object):
def __init__(self):
self._x = 3
def foo(self):
return self._x
""", deep=True, solve_unknowns=False, extract_locals=True) as ty:
self.assertTypesMatchPytd(ty, """
class C:
_x: int
def foo(self) -> int
""")
def testPublic(self):
with self.Infer("""
class C(object):
def __init__(self):
self.x = 3
def foo(self):
return self.x
""", deep=True, solve_unknowns=False, extract_locals=True) as ty:
self.assertTypesMatchPytd(ty, """
class C:
x: int
def foo(self) -> int
""")
def testCrosswise(self):
with self.Infer("""
class A(object):
def __init__(self):
if id(self):
self.b = B()
def set_on_b(self):
self.b.x = 3
class B(object):
def __init__(self):
if id(self):
self.a = A()
def set_on_a(self):
self.a.x = 3j
""", deep=True, solve_unknowns=False, extract_locals=True) as ty:
self.assertTypesMatchPytd(ty, """
class A:
b: B
x: complex
def set_on_b(self) -> NoneType
class B:
a: A
x: int
def set_on_a(self) -> NoneType
""")
if __name__ == "__main__":
test_inference.main()
| apache-2.0 |
ngokevin/zamboni | mkt/developers/tests/test_views_versions.py | 2 | 30543 | import datetime
import os
from django.conf import settings
import mock
from nose.tools import eq_, ok_
from pyquery import PyQuery as pq
import amo
import amo.tests
from amo.tests import req_factory_factory
from mkt.comm.models import CommunicationNote
from mkt.constants.applications import DEVICE_TYPES
from mkt.developers.models import ActivityLog, AppLog, PreloadTestPlan
from mkt.developers.views import preload_submit, status
from mkt.files.models import File
from mkt.reviewers.models import EditorSubscription, EscalationQueue
from mkt.site.fixtures import fixture
from mkt.submit.tests.test_views import BasePackagedAppTest
from mkt.users.models import UserProfile
from mkt.versions.models import Version
from mkt.webapps.models import AddonUser, Webapp
class TestVersion(amo.tests.TestCase):
fixtures = fixture('group_admin', 'user_999', 'user_admin',
'user_admin_group', 'webapp_337141')
def setUp(self):
self.client.login(username='admin@mozilla.com', password='password')
self.webapp = self.get_webapp()
self.url = self.webapp.get_dev_url('versions')
def get_webapp(self):
return Webapp.objects.get(id=337141)
def test_nav_link(self):
r = self.client.get(self.url)
eq_(pq(r.content)('.edit-addon-nav li.selected a').attr('href'),
self.url)
def test_items(self):
doc = pq(self.client.get(self.url).content)
eq_(doc('#version-status').length, 1)
eq_(doc('#version-list').length, 0)
eq_(doc('#delete-addon').length, 1)
eq_(doc('#modal-delete').length, 1)
eq_(doc('#modal-disable').length, 1)
eq_(doc('#modal-delete-version').length, 0)
def test_delete_link(self):
# Hard "Delete App" link should be visible for only incomplete apps.
self.webapp.update(status=amo.STATUS_NULL)
doc = pq(self.client.get(self.url).content)
eq_(doc('#delete-addon').length, 1)
eq_(doc('#modal-delete').length, 1)
def test_pending(self):
self.webapp.update(status=amo.STATUS_PENDING)
r = self.client.get(self.url)
eq_(r.status_code, 200)
doc = pq(r.content)
eq_(doc('#version-status .status-pending').length, 1)
eq_(doc('#rejection').length, 0)
def test_public(self):
eq_(self.webapp.status, amo.STATUS_PUBLIC)
r = self.client.get(self.url)
eq_(r.status_code, 200)
doc = pq(r.content)
eq_(doc('#version-status .status-public').length, 1)
eq_(doc('#rejection').length, 0)
def test_blocked(self):
self.webapp.update(status=amo.STATUS_BLOCKED)
r = self.client.get(self.url)
eq_(r.status_code, 200)
doc = pq(r.content)
eq_(doc('#version-status .status-blocked').length, 1)
eq_(doc('#rejection').length, 0)
assert 'blocked by a site administrator' in doc.text()
def test_rejected(self):
comments = "oh no you di'nt!!"
amo.set_user(UserProfile.objects.get(username='admin'))
amo.log(amo.LOG.REJECT_VERSION, self.webapp,
self.webapp.current_version, user_id=999,
details={'comments': comments, 'reviewtype': 'pending'})
self.webapp.update(status=amo.STATUS_REJECTED)
amo.tests.make_rated(self.webapp)
(self.webapp.versions.latest()
.all_files[0].update(status=amo.STATUS_DISABLED))
r = self.client.get(self.url)
eq_(r.status_code, 200)
doc = pq(r.content)('#version-status')
eq_(doc('.status-rejected').length, 1)
eq_(doc('#rejection').length, 1)
eq_(doc('#rejection blockquote').text(), comments)
my_reply = 'fixed just for u, brah'
r = self.client.post(self.url, {'notes': my_reply,
'resubmit-app': ''})
self.assertRedirects(r, self.url, 302)
webapp = self.get_webapp()
eq_(webapp.status, amo.STATUS_PENDING,
'Reapplied apps should get marked as pending')
eq_(webapp.versions.latest().all_files[0].status, amo.STATUS_PENDING,
'Files for reapplied apps should get marked as pending')
action = amo.LOG.WEBAPP_RESUBMIT
assert AppLog.objects.filter(
addon=webapp, activity_log__action=action.id).exists(), (
"Didn't find `%s` action in logs." % action.short)
def test_no_ratings_no_resubmit(self):
self.webapp.update(status=amo.STATUS_REJECTED)
r = self.client.post(self.url, {'notes': 'lol',
'resubmit-app': ''})
eq_(r.status_code, 403)
self.webapp.content_ratings.create(ratings_body=0, rating=0)
r = self.client.post(self.url, {'notes': 'lol',
'resubmit-app': ''})
self.assert3xx(r, self.webapp.get_dev_url('versions'))
def test_comm_thread_after_resubmission(self):
self.webapp.update(status=amo.STATUS_REJECTED)
amo.tests.make_rated(self.webapp)
amo.set_user(UserProfile.objects.get(username='admin'))
(self.webapp.versions.latest()
.all_files[0].update(status=amo.STATUS_DISABLED))
my_reply = 'no give up'
self.client.post(self.url, {'notes': my_reply,
'resubmit-app': ''})
notes = CommunicationNote.objects.all()
eq_(notes.count(), 1)
eq_(notes[0].body, my_reply)
def test_rejected_packaged(self):
self.webapp.update(is_packaged=True)
comments = "oh no you di'nt!!"
amo.set_user(UserProfile.objects.get(username='admin'))
amo.log(amo.LOG.REJECT_VERSION, self.webapp,
self.webapp.current_version, user_id=999,
details={'comments': comments, 'reviewtype': 'pending'})
self.webapp.update(status=amo.STATUS_REJECTED)
(self.webapp.versions.latest()
.all_files[0].update(status=amo.STATUS_DISABLED))
r = self.client.get(self.url)
eq_(r.status_code, 200)
doc = pq(r.content)('#version-status')
eq_(doc('.status-rejected').length, 1)
eq_(doc('#rejection').length, 1)
eq_(doc('#rejection blockquote').text(), comments)
class BaseAddVersionTest(BasePackagedAppTest):
def setUp(self):
super(BaseAddVersionTest, self).setUp()
self.app = amo.tests.app_factory(
complete=True, is_packaged=True, app_domain='app://hy.fr',
version_kw=dict(version='1.0'))
self.url = self.app.get_dev_url('versions')
self.user = UserProfile.objects.get(username='regularuser')
AddonUser.objects.create(user=self.user, addon=self.app)
def _post(self, expected_status=200):
res = self.client.post(self.url, {'upload': self.upload.pk,
'upload-version': ''})
eq_(res.status_code, expected_status)
return res
@mock.patch('mkt.webapps.tasks.update_cached_manifests.delay', new=mock.Mock)
class TestAddVersion(BaseAddVersionTest):
def setUp(self):
super(TestAddVersion, self).setUp()
# Update version to be < 1.0 so we don't throw validation errors.
self.app.current_version.update(version='0.9',
created=self.days_ago(1))
def test_post(self):
self._post(302)
version = self.app.versions.latest()
eq_(version.version, '1.0')
eq_(version.all_files[0].status, amo.STATUS_PENDING)
def test_post_subscribers(self):
# Same test as above, but add a suscriber. We only want to make sure
# we are not causing a traceback because of that.
reviewer = UserProfile.objects.create(email='foo@example.com')
self.grant_permission(reviewer, 'Apps:Review')
EditorSubscription.objects.create(addon=self.app, user=reviewer)
self._post(302)
version = self.app.versions.latest()
eq_(version.version, '1.0')
eq_(version.all_files[0].status, amo.STATUS_PENDING)
def test_unique_version(self):
self.app.current_version.update(version='1.0')
res = self._post(200)
self.assertFormError(res, 'upload_form', 'upload',
'Version 1.0 already exists.')
def test_origin_changed(self):
for origin in (None, 'app://yo.lo'):
self.app.update(app_domain=origin)
res = self._post(200)
self.assertFormError(res, 'upload_form', 'upload',
'Changes to "origin" are not allowed.')
def test_pending_on_new_version(self):
# Test app rejection, then new version, updates app status to pending.
self.app.update(status=amo.STATUS_REJECTED)
files = File.objects.filter(version__addon=self.app)
files.update(status=amo.STATUS_DISABLED)
self._post(302)
self.app.reload()
version = self.app.versions.latest()
eq_(version.version, '1.0')
eq_(version.all_files[0].status, amo.STATUS_PENDING)
eq_(self.app.status, amo.STATUS_PENDING)
@mock.patch('mkt.developers.views.run_validator')
def test_prefilled_features(self, run_validator_):
run_validator_.return_value = '{"feature_profile": ["apps", "audio"]}'
# All features should be disabled.
features = self.app.current_version.features.to_dict()
eq_(any(features.values()), False)
self._post(302)
# In this new version we should be prechecked new ones.
features = self.app.versions.latest().features.to_dict()
for key, feature in features.iteritems():
eq_(feature, key in ('has_apps', 'has_audio'))
def test_blocklist_on_new_version(self):
# Test app blocked, then new version, doesn't update app status, and
# app shows up in escalation queue.
self.app.update(status=amo.STATUS_BLOCKED)
files = File.objects.filter(version__addon=self.app)
files.update(status=amo.STATUS_DISABLED)
self._post(302)
version = self.app.versions.latest()
eq_(version.version, '1.0')
eq_(version.all_files[0].status, amo.STATUS_PENDING)
self.app.update_status()
eq_(self.app.status, amo.STATUS_BLOCKED)
assert EscalationQueue.objects.filter(addon=self.app).exists(), (
'App not in escalation queue')
def test_new_version_when_incomplete(self):
self.app.update(status=amo.STATUS_NULL)
files = File.objects.filter(version__addon=self.app)
files.update(status=amo.STATUS_DISABLED)
self._post(302)
self.app.reload()
version = self.app.versions.latest()
eq_(version.version, '1.0')
eq_(version.all_files[0].status, amo.STATUS_PENDING)
eq_(self.app.status, amo.STATUS_PENDING)
def test_vip_app_added_to_escalation_queue(self):
self.app.update(vip_app=True)
self._post(302)
assert EscalationQueue.objects.filter(addon=self.app).exists(), (
'VIP App not in escalation queue')
class TestAddVersionPrereleasePermissions(BaseAddVersionTest):
@property
def package(self):
return self.packaged_app_path('prerelease.zip')
def test_escalate_on_prerelease_permissions(self):
"""Test that apps that use prerelease permissions are escalated."""
UserProfile.objects.create(email=settings.NOBODY_EMAIL_ADDRESS)
self.app.current_version.update(version='0.9',
created=self.days_ago(1))
ok_(not EscalationQueue.objects.filter(addon=self.app).exists(),
'App in escalation queue')
self._post(302)
version = self.app.versions.latest()
eq_(version.version, '1.0')
eq_(version.all_files[0].status, amo.STATUS_PENDING)
self.app.update_status()
eq_(self.app.status, amo.STATUS_PUBLIC)
ok_(EscalationQueue.objects.filter(addon=self.app).exists(),
'App not in escalation queue')
class TestAddVersionNoPermissions(BaseAddVersionTest):
@property
def package(self):
return self.packaged_app_path('no_permissions.zip')
def test_no_escalate_on_blank_permissions(self):
"""Test that apps that do not use permissions are not escalated."""
self.app.current_version.update(version='0.9',
created=self.days_ago(1))
ok_(not EscalationQueue.objects.filter(addon=self.app).exists(),
'App in escalation queue')
self._post(302)
version = self.app.versions.latest()
eq_(version.version, '1.0')
eq_(version.all_files[0].status, amo.STATUS_PENDING)
self.app.update_status()
eq_(self.app.status, amo.STATUS_PUBLIC)
ok_(not EscalationQueue.objects.filter(addon=self.app).exists(),
'App in escalation queue')
class TestVersionPackaged(amo.tests.WebappTestCase):
fixtures = fixture('user_999', 'webapp_337141')
def setUp(self):
super(TestVersionPackaged, self).setUp()
assert self.client.login(username='steamcube@mozilla.com',
password='password')
self.app.update(is_packaged=True)
self.app = self.get_app()
# Needed for various status checking routines on fully complete apps.
amo.tests.make_rated(self.app)
if not self.app.categories:
self.app.update(categories=['utilities'])
self.app.addondevicetype_set.create(device_type=DEVICE_TYPES.keys()[0])
self.app.previews.create()
self.url = self.app.get_dev_url('versions')
self.delete_url = self.app.get_dev_url('versions.delete')
def test_items_packaged(self):
doc = pq(self.client.get(self.url).content)
eq_(doc('#version-status').length, 1)
eq_(doc('#version-list').length, 1)
eq_(doc('#delete-addon').length, 1)
eq_(doc('#modal-delete').length, 1)
eq_(doc('#modal-disable').length, 1)
eq_(doc('#modal-delete-version').length, 1)
def test_version_list_packaged(self):
self.app.update(is_packaged=True)
amo.tests.version_factory(addon=self.app, version='2.0',
file_kw=dict(status=amo.STATUS_PENDING))
self.app = self.get_app()
doc = pq(self.client.get(self.url).content)
eq_(doc('#version-status').length, 1)
eq_(doc('#version-list tbody tr').length, 2)
# 1 pending and 1 public.
eq_(doc('#version-list span.status-pending').length, 1)
eq_(doc('#version-list span.status-public').length, 1)
# Check version strings and order of versions.
eq_(map(lambda x: x.text, doc('#version-list h4 a')),
['2.0', '1.0'])
# There should be 2 delete buttons.
eq_(doc('#version-list a.delete-version.button').length, 2)
# Check download url.
eq_(doc('#version-list a.download').eq(0).attr('href'),
self.app.versions.all()[0].all_files[0].get_url_path(''))
eq_(doc('#version-list a.download').eq(1).attr('href'),
self.app.versions.all()[1].all_files[0].get_url_path(''))
def test_delete_version_xss(self):
version = self.app.versions.latest()
version.update(version='<script>alert("xss")</script>')
res = self.client.get(self.url)
assert '<script>alert(' not in res.content
assert '<script>alert(' in res.content
# Now do the POST to delete.
res = self.client.post(self.delete_url, {'version_id': version.pk},
follow=True)
assert not Version.objects.filter(pk=version.pk).exists()
# Check xss in success flash message.
assert '<script>alert(' not in res.content
assert '<script>alert(' in res.content
def test_delete_only_version(self):
eq_(self.app.versions.count(), 1)
version = self.app.latest_version
self.client.post(self.delete_url, {'version_id': version.pk})
assert not Version.objects.filter(pk=version.pk).exists()
eq_(ActivityLog.objects.filter(action=amo.LOG.DELETE_VERSION.id)
.count(), 1)
# Since this was the last version, the app status should be incomplete.
eq_(self.get_app().status, amo.STATUS_NULL)
def test_delete_last_public_version(self):
"""
Test that deleting the last PUBLIC version but there is an APPROVED
version marks the app as APPROVED.
Similar to the above test but ensures APPROVED versions don't get
confused with PUBLIC versions.
"""
eq_(self.app.versions.count(), 1)
ver1 = self.app.latest_version
ver1.all_files[0].update(status=amo.STATUS_APPROVED)
ver2 = amo.tests.version_factory(
addon=self.app, version='2.0',
file_kw=dict(status=amo.STATUS_PUBLIC))
self.client.post(self.delete_url, {'version_id': ver2.pk})
self.app.reload()
eq_(self.app.status, amo.STATUS_APPROVED)
eq_(self.app.latest_version, ver1)
eq_(self.app.current_version, None)
eq_(self.app.versions.count(), 1)
eq_(Version.with_deleted.get(pk=ver2.pk).all_files[0].status,
amo.STATUS_DISABLED)
def test_delete_version_app_public(self):
"""Test deletion of current_version when app is PUBLIC."""
eq_(self.app.status, amo.STATUS_PUBLIC)
ver1 = self.app.latest_version
ver2 = amo.tests.version_factory(
addon=self.app, version='2.0',
file_kw=dict(status=amo.STATUS_PUBLIC))
eq_(self.app.latest_version, ver2)
eq_(self.app.current_version, ver2)
self.client.post(self.delete_url, {'version_id': ver2.pk})
self.app.reload()
eq_(self.app.status, amo.STATUS_PUBLIC)
eq_(self.app.latest_version, ver1)
eq_(self.app.current_version, ver1)
eq_(self.app.versions.count(), 1)
eq_(Version.with_deleted.get(pk=ver2.pk).all_files[0].status,
amo.STATUS_DISABLED)
@mock.patch('mkt.webapps.tasks.index_webapps')
@mock.patch('mkt.webapps.tasks.update_cached_manifests')
@mock.patch('mkt.webapps.models.Webapp.update_name_from_package_manifest')
def test_delete_version_app_hidden(self, update_name_mock,
update_manifest_mock, index_mock):
"""Test deletion of current_version when app is UNLISTED."""
self.app.update(status=amo.STATUS_UNLISTED)
ver1 = self.app.latest_version
ver2 = amo.tests.version_factory(
addon=self.app, version='2.0',
file_kw=dict(status=amo.STATUS_PUBLIC))
eq_(self.app.latest_version, ver2)
eq_(self.app.current_version, ver2)
update_manifest_mock.reset_mock()
index_mock.reset_mock()
self.client.post(self.delete_url, {'version_id': ver2.pk})
self.app.reload()
eq_(self.app.status, amo.STATUS_UNLISTED)
eq_(self.app.latest_version, ver1)
eq_(self.app.current_version, ver1)
eq_(self.app.versions.count(), 1)
eq_(Version.with_deleted.get(pk=ver2.pk).all_files[0].status,
amo.STATUS_DISABLED)
eq_(update_name_mock.call_count, 1)
eq_(update_manifest_mock.delay.call_count, 1)
eq_(index_mock.delay.call_count, 1)
@mock.patch('mkt.webapps.tasks.index_webapps')
@mock.patch('mkt.webapps.tasks.update_cached_manifests')
@mock.patch('mkt.webapps.models.Webapp.update_name_from_package_manifest')
def test_delete_version_app_private(self, update_name_mock,
update_manifest_mock, index_mock):
"""Test deletion of current_version when app is APPROVED."""
self.app.update(status=amo.STATUS_APPROVED)
ver1 = self.app.latest_version
ver2 = amo.tests.version_factory(
addon=self.app, version='2.0',
file_kw=dict(status=amo.STATUS_PUBLIC))
eq_(self.app.latest_version, ver2)
eq_(self.app.current_version, ver2)
update_manifest_mock.reset_mock()
index_mock.reset_mock()
self.client.post(self.delete_url, {'version_id': ver2.pk})
self.app.reload()
eq_(self.app.status, amo.STATUS_APPROVED)
eq_(self.app.latest_version, ver1)
eq_(self.app.current_version, ver1)
eq_(self.app.versions.count(), 1)
eq_(Version.with_deleted.get(pk=ver2.pk).all_files[0].status,
amo.STATUS_DISABLED)
eq_(update_name_mock.call_count, 1)
eq_(update_manifest_mock.delay.call_count, 1)
eq_(index_mock.delay.call_count, 1)
def test_delete_version_while_disabled(self):
self.app.update(disabled_by_user=True)
version = self.app.latest_version
res = self.client.post(self.delete_url, {'version_id': version.pk})
eq_(res.status_code, 302)
eq_(self.get_app().status, amo.STATUS_NULL)
version = Version.with_deleted.get(pk=version.pk)
assert version.deleted
def test_anonymous_delete_redirects(self):
self.client.logout()
version = self.app.versions.latest()
res = self.client.post(self.delete_url, dict(version_id=version.pk))
self.assertLoginRedirects(res, self.delete_url)
def test_non_author_no_delete_for_you(self):
self.client.logout()
assert self.client.login(username='regular@mozilla.com',
password='password')
version = self.app.versions.latest()
res = self.client.post(self.delete_url, dict(version_id=version.pk))
eq_(res.status_code, 403)
@mock.patch.object(Version, 'delete')
def test_roles_and_delete(self, mock_version):
user = UserProfile.objects.get(email='regular@mozilla.com')
addon_user = AddonUser.objects.create(user=user, addon=self.app)
allowed = [amo.AUTHOR_ROLE_OWNER, amo.AUTHOR_ROLE_DEV]
for role in [r[0] for r in amo.AUTHOR_CHOICES]:
self.client.logout()
addon_user.role = role
addon_user.save()
assert self.client.login(username='regular@mozilla.com',
password='password')
version = self.app.versions.latest()
res = self.client.post(self.delete_url,
dict(version_id=version.pk))
if role in allowed:
self.assert3xx(res, self.url)
assert mock_version.called, ('Unexpected: `Version.delete` '
'should have been called.')
mock_version.reset_mock()
else:
eq_(res.status_code, 403)
def test_cannot_delete_blocked(self):
v = self.app.versions.latest()
f = v.all_files[0]
f.update(status=amo.STATUS_BLOCKED)
res = self.client.post(self.delete_url, dict(version_id=v.pk))
eq_(res.status_code, 403)
def test_dev_cannot_blocklist(self):
url = self.app.get_dev_url('blocklist')
res = self.client.post(url)
eq_(res.status_code, 403)
@mock.patch('lib.crypto.packaged.os.unlink', new=mock.Mock)
def test_admin_can_blocklist(self):
self.grant_permission(UserProfile.objects.get(username='regularuser'),
'Apps:Configure')
assert self.client.login(username='regular@mozilla.com',
password='password')
v_count = self.app.versions.count()
url = self.app.get_dev_url('blocklist')
res = self.client.post(url)
self.assert3xx(res, self.app.get_dev_url('versions'))
app = self.app.reload()
eq_(app.versions.count(), v_count + 1)
eq_(app.status, amo.STATUS_BLOCKED)
eq_(app.versions.latest().files.latest().status, amo.STATUS_BLOCKED)
class TestPreloadSubmit(amo.tests.TestCase):
fixtures = fixture('group_admin', 'user_admin', 'user_admin_group',
'webapp_337141')
def setUp(self):
self.create_switch('preload-apps')
self.user = UserProfile.objects.get(username='admin')
self.login(self.user)
self.webapp = Webapp.objects.get(id=337141)
self.url = self.webapp.get_dev_url('versions')
self.home_url = self.webapp.get_dev_url('preload_home')
self.submit_url = self.webapp.get_dev_url('preload_submit')
path = os.path.dirname(os.path.abspath(__file__))
self.test_pdf = path + '/files/test.pdf'
self.test_xls = path + '/files/test.xls'
def _submit_pdf(self):
f = open(self.test_pdf, 'r')
req = req_factory_factory(self.submit_url, user=self.user, post=True,
data={'agree': True, 'test_plan': f})
return preload_submit(req, self.webapp.app_slug)
def test_get_200(self):
eq_(self.client.get(self.home_url).status_code, 200)
eq_(self.client.get(self.submit_url).status_code, 200)
@mock.patch('mkt.developers.views.save_test_plan')
@mock.patch('mkt.developers.views.messages')
def test_preload_on_status_page(self, noop1, noop2):
req = req_factory_factory(self.url, user=self.user)
r = status(req, self.webapp.app_slug)
doc = pq(r.content)
eq_(doc('#preload .listing-footer a').attr('href'),
self.webapp.get_dev_url('preload_home'))
assert doc('#preload .not-submitted')
self._submit_pdf()
req = req_factory_factory(self.url, user=self.user)
r = status(req, self.webapp.app_slug)
doc = pq(r.content)
eq_(doc('#preload .listing-footer a').attr('href'),
self.webapp.get_dev_url('preload_submit'))
assert doc('#preload .submitted')
def _assert_submit(self, endswith, content_type, save_mock):
test_plan = PreloadTestPlan.objects.get()
eq_(test_plan.addon, self.webapp)
assert test_plan.filename.startswith('test_plan_')
assert test_plan.filename.endswith(endswith)
self.assertCloseToNow(test_plan.last_submission)
eq_(save_mock.call_args[0][0].content_type, content_type)
assert save_mock.call_args[0][1].startswith('test_plan')
eq_(save_mock.call_args[0][2], self.webapp)
@mock.patch('mkt.developers.views.save_test_plan')
@mock.patch('mkt.developers.views.messages')
def test_submit_pdf(self, noop, save_mock):
r = self._submit_pdf()
self.assert3xx(r, self.url)
self._assert_submit('pdf', 'application/pdf', save_mock)
@mock.patch('mkt.developers.views.save_test_plan')
@mock.patch('mkt.developers.views.messages')
def test_submit_xls(self, noop, save_mock):
f = open(self.test_xls, 'r')
req = req_factory_factory(self.submit_url, user=self.user, post=True,
data={'agree': True, 'test_plan': f})
r = preload_submit(req, self.webapp.app_slug)
self.assert3xx(r, self.url)
self._assert_submit('xls', 'application/vnd.ms-excel', save_mock)
@mock.patch('mkt.developers.views.save_test_plan')
@mock.patch('mkt.developers.views.messages')
def test_submit_bad_file(self, noop, save_mock):
f = open(os.path.abspath(__file__), 'r')
req = req_factory_factory(self.submit_url, user=self.user, post=True,
data={'agree': True, 'test_plan': f})
r = preload_submit(req, self.webapp.app_slug)
eq_(r.status_code, 200)
eq_(PreloadTestPlan.objects.count(), 0)
assert not save_mock.called
assert ('Invalid file type' in
pq(r.content)('.test_plan .errorlist').text())
@mock.patch('mkt.developers.views.save_test_plan')
@mock.patch('mkt.developers.views.messages')
def test_submit_no_file(self, noop, save_mock):
req = req_factory_factory(self.submit_url, user=self.user, post=True,
data={'agree': True})
r = preload_submit(req, self.webapp.app_slug)
eq_(r.status_code, 200)
eq_(PreloadTestPlan.objects.count(), 0)
assert not save_mock.called
assert 'required' in pq(r.content)('.test_plan .errorlist').text()
@mock.patch('mkt.developers.views.save_test_plan')
@mock.patch('mkt.developers.views.messages')
def test_submit_no_agree(self, noop, save_mock):
f = open(self.test_xls, 'r')
req = req_factory_factory(self.submit_url, user=self.user, post=True,
data={'test_plan': f})
r = preload_submit(req, self.webapp.app_slug)
eq_(r.status_code, 200)
eq_(PreloadTestPlan.objects.count(), 0)
assert not save_mock.called
assert 'required' in pq(r.content)('.agree .errorlist').text()
@mock.patch('mkt.developers.views.save_test_plan')
@mock.patch('mkt.developers.views.messages')
def test_submit_multiple_status(self, noop, save_mock):
f = open(self.test_xls, 'r')
req = req_factory_factory(self.submit_url, user=self.user, post=True,
data={'test_plan': f, 'agree': True})
preload_submit(req, self.webapp.app_slug)
self._submit_pdf()
eq_(PreloadTestPlan.objects.count(), 2)
xls = PreloadTestPlan.objects.get(filename__contains='xls')
pdf = PreloadTestPlan.objects.get(filename__contains='pdf')
eq_(xls.status, amo.STATUS_DISABLED)
eq_(pdf.status, amo.STATUS_PUBLIC)
# Check the link points to most recent one.
req = req_factory_factory(self.url, user=self.user)
r = status(req, self.webapp.app_slug)
doc = pq(r.content)
eq_(doc('.test-plan-download').attr('href'),
pdf.preload_test_plan_url)
@mock.patch.object(settings, 'PREINSTALL_TEST_PLAN_LATEST',
datetime.datetime.now() + datetime.timedelta(days=1))
@mock.patch('mkt.developers.views.save_test_plan')
@mock.patch('mkt.developers.views.messages')
def test_outdated(self, noop, save_mock):
self._submit_pdf()
req = req_factory_factory(self.url, user=self.user)
r = status(req, self.webapp.app_slug)
doc = pq(r.content)
assert doc('.outdated')
| bsd-3-clause |
inasafe/inasafe | safe/report/extractors/composer.py | 3 | 19646 | # coding=utf-8
"""Module used to generate context for composer related rendering.
Particular example are:
- Map rendering
- PDF rendering
- PNG rendering
"""
import datetime
from copy import deepcopy
from qgis.core import QgsProject
from safe.common.version import get_version
from safe.definitions.fields import analysis_name_field
from safe.definitions.provenance import (
provenance_exposure_layer_id,
provenance_multi_exposure_layers_id)
from safe.definitions.reports.infographic import (
html_frame_elements,
population_chart,
inasafe_logo_white,
image_item_elements, map_overview)
from safe.report.extractors.util import (
value_from_field_name,
resolve_from_dictionary,
jinja2_output_as_string)
from safe.utilities.settings import setting
__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
class QGISComposerContext():
"""Default context class for QGIS Composition.
The reason we made it a class is because things needed for composition
were much more obvious and solid than Jinja2 template context.
.. versionadded:: 4.0
"""
def __init__(self):
"""Create QGIS Composer context."""
self._substitution_map = {}
self._infographic_elements = []
self._image_elements = []
self._html_frame_elements = []
self._map_elements = []
self._map_legends = []
@property
def substitution_map(self):
"""Substitution map.
:return: Substitution map containing dict mapping used in QGIS
Composition template
:rtype: dict
"""
return self._substitution_map
@substitution_map.setter
def substitution_map(self, value):
"""Substitution map.
:param value: Substitution map containing dict mapping used in QGIS
Composition template
:type value: dict
"""
self._substitution_map = value
@property
def infographic_elements(self):
"""Infographic elements.
:return: Embedded infographics elements that needed to be generated
for QGIS Composition
:rtype: list(dict)
"""
return self._infographic_elements
@infographic_elements.setter
def infographic_elements(self, value):
"""Infographic elements.
:param value: Embedded infographics elements that needed to be
generated for QGIS Composition
:type value: list(dict)
"""
self._infographic_elements = value
@property
def image_elements(self):
"""Image elements.
:return: Scanned all the image elements in the composition that
needed to be replaced
:rtype: list(dict)
"""
return self._image_elements
@image_elements.setter
def image_elements(self, value):
"""Image elements.
:param value: Scanned all the image elements in the composition that
needed to be replaced
:type value: list(dict)
"""
self._image_elements = value
@property
def html_frame_elements(self):
"""HTML frame elements.
:return: Scanned all html frame elements
:rtype: list(dict)
"""
return self._html_frame_elements
@html_frame_elements.setter
def html_frame_elements(self, value):
"""HTML frame elements.
:param value: Scanned all html frame elements
:type value: list(dict)
"""
self._html_frame_elements = value
@property
def map_elements(self):
"""Map elements.
:return: Scanned all map elements
:rtype: list(dict)
"""
return self._map_elements
@map_elements.setter
def map_elements(self, value):
"""Map elements.
:param value: Scanned all map elements
:type value: list(dict)
"""
self._map_elements = value
@property
def map_legends(self):
"""Map legends.
:return: Scanned all map legends element
:rtype: list(dict)
"""
return self._map_legends
@map_legends.setter
def map_legends(self, value):
"""Map legends.
:param value: Scanned all map legends
:type value: list(dict)
"""
self._map_legends = value
def qgis_composer_extractor(impact_report, component_metadata):
"""Extract composer context.
This method extract necessary context for a given impact report and
component metadata and save the context so it can be used in composer
rendering phase
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information about the component we want to render
:type component_metadata: safe.report.report_metadata.
ReportComponentsMetadata
:return: context for rendering phase
:rtype: dict
.. versionadded:: 4.0
"""
# QGIS Composer needed certain context to generate the output
# - Map Settings
# - Substitution maps
# - Element settings, such as icon for picture file or image source
# Generate map settings
qgis_context = impact_report.qgis_composition_context
inasafe_context = impact_report.inasafe_context
provenance = impact_report.impact_function.provenance
extra_args = component_metadata.extra_args
context = QGISComposerContext()
# Set default image elements to replace
image_elements = [
{
'id': 'safe-logo',
'path': inasafe_context.inasafe_logo
},
{
'id': 'black-inasafe-logo',
'path': inasafe_context.black_inasafe_logo
},
{
'id': 'white-inasafe-logo',
'path': inasafe_context.white_inasafe_logo
},
{
'id': 'north-arrow',
'path': inasafe_context.north_arrow
},
{
'id': 'organisation-logo',
'path': inasafe_context.organisation_logo
},
{
'id': 'supporters_logo',
'path': inasafe_context.supporters_logo
}
]
context.image_elements = image_elements
# Set default HTML Frame elements to replace
html_frame_elements = [
{
'id': 'impact-report',
'mode': 'text', # another mode is url
'text': '', # TODO: get impact summary table
}
]
context.html_frame_elements = html_frame_elements
"""Define the layers for the impact map."""
project = QgsProject.instance()
layers = []
exposure_summary_layers = []
if impact_report.multi_exposure_impact_function:
for impact_function in (
impact_report.multi_exposure_impact_function.impact_functions):
impact_layer = impact_function.exposure_summary or (
impact_function.aggregate_hazard_impacted)
exposure_summary_layers.append(impact_layer)
# use custom ordered layer if any
if impact_report.ordered_layers:
for layer in impact_report.ordered_layers:
layers.append(layer)
# We are keeping this if we want to enable below behaviour again.
# Currently realtime might have layer order without impact layer in it.
# # make sure at least there is an impact layer
# if impact_report.multi_exposure_impact_function:
# additional_layers = [] # for exposure summary layers
# impact_layer_found = False
# impact_functions = (
# impact_report.multi_exposure_impact_function.impact_functions)
# # check for impact layer occurrences
# for analysis in impact_functions:
# impact_layer = analysis.exposure_summary or (
# analysis.aggregate_hazard_impacted)
# for index, layer in enumerate(layers):
# if impact_layer.source() == layer.source():
# add_impact_layers_to_canvas(analysis)
# layers[index] = impact_layer
# impact_layer_found = True
# if not impact_layer_found:
# for analysis in impact_functions:
# add_impact_layers_to_canvas(analysis)
# impact_layer = analysis.exposure_summary or (
# analysis.aggregate_hazard_impacted)
# layer_uri = full_layer_uri(impact_layer)
# layer = load_layer_from_registry(layer_uri)
# additional_layers.append(layer)
# layers = additional_layers + layers
# else:
# impact_layer = (
# impact_report.impact_function.exposure_summary or (
# impact_report.impact_function.aggregate_hazard_impacted))
# if impact_layer not in layers:
# layers.insert(0, impact_layer)
# use default layer order if no custom ordered layer found
else:
if not impact_report.multi_exposure_impact_function: # single IF
layers = [impact_report.impact] + impact_report.extra_layers
else: # multi-exposure IF
layers = [] + impact_report.extra_layers
add_supplementary_layers = (
not impact_report.multi_exposure_impact_function or not (
impact_report.multi_exposure_impact_function.
output_layers_ordered)
)
if add_supplementary_layers:
# Check show only impact.
show_only_impact = setting(
'set_show_only_impact_on_report', expected_type=bool)
if not show_only_impact:
hazard_layer = project.mapLayers().get(
provenance['hazard_layer_id'], None)
aggregation_layer_id = provenance['aggregation_layer_id']
if aggregation_layer_id:
aggregation_layer = project.mapLayers().get(
aggregation_layer_id, None)
layers.append(aggregation_layer)
layers.append(hazard_layer)
# check hide exposure settings
hide_exposure_flag = setting(
'setHideExposureFlag', expected_type=bool)
if not hide_exposure_flag:
exposure_layers_id = []
if provenance.get(
provenance_exposure_layer_id['provenance_key']):
exposure_layers_id.append(
provenance.get(
provenance_exposure_layer_id['provenance_key']))
elif provenance.get(
provenance_multi_exposure_layers_id['provenance_key']):
exposure_layers_id = provenance.get(
provenance_multi_exposure_layers_id['provenance_key'])
# place exposure at the bottom
for layer_id in exposure_layers_id:
exposure_layer = project.mapLayers().get(layer_id)
layers.append(exposure_layer)
# default extent is analysis extent
if not qgis_context.extent:
qgis_context.extent = impact_report.impact_function.analysis_extent
map_elements = [
{
'id': 'impact-map',
'extent': qgis_context.extent,
'grid_split_count': 5,
'layers': layers,
}
]
context.map_elements = map_elements
# calculate map_legends, only show the legend for impact layer
if impact_report.legend_layers: # use requested legend if any
layers = impact_report.legend_layers
elif impact_report.multi_exposure_impact_function: # multi-exposure IF
layers = exposure_summary_layers
else: # single IF
layers = [impact_report.impact]
symbol_count = 0
for layer in layers:
""":type: qgis.core.QgsMapLayer"""
try:
symbol_count += len(layer.legendSymbologyItems())
continue
except Exception: # pylint: disable=broad-except
pass
try:
symbol_count += len(layer.renderer().legendSymbolItems())
continue
except Exception: # pylint: disable=broad-except
pass
symbol_count += 1
legend_title = provenance.get('map_legend_title') or ''
map_legends = [
{
'id': 'impact-legend',
'title': legend_title,
'layers': layers,
'symbol_count': symbol_count,
# 'column_count': 2, # the number of column in legend display
}
]
context.map_legends = map_legends
# process substitution map
start_datetime = provenance['start_datetime']
""":type: datetime.datetime"""
date_format = resolve_from_dictionary(extra_args, 'date-format')
time_format = resolve_from_dictionary(extra_args, 'time-format')
if isinstance(start_datetime, datetime.datetime):
date = start_datetime.strftime(date_format)
time = start_datetime.strftime(time_format)
else:
date = ''
time = ''
long_version = get_version()
tokens = long_version.split('.')
version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])
# Get title of the layer
title = provenance.get('map_title') or ''
# Set source
unknown_source_text = resolve_from_dictionary(
extra_args, ['defaults', 'unknown_source'])
aggregation_not_used = resolve_from_dictionary(
extra_args, ['defaults', 'aggregation_not_used'])
hazard_source = (
provenance.get(
'hazard_keywords', {}).get('source') or unknown_source_text)
exposure_source = (
provenance.get(
'exposure_keywords', {}).get('source') or unknown_source_text)
if provenance['aggregation_layer']:
aggregation_source = (
provenance['aggregation_keywords'].get('source')
or unknown_source_text)
else:
aggregation_source = aggregation_not_used
spatial_reference_format = resolve_from_dictionary(
extra_args, 'spatial-reference-format')
reference_name = spatial_reference_format.format(
crs=impact_report.impact_function.crs.authid())
analysis_layer = impact_report.analysis
analysis_name = value_from_field_name(
analysis_name_field['field_name'], analysis_layer)
# Prepare the substitution map
version_title = resolve_from_dictionary(extra_args, 'version-title')
disclaimer_title = resolve_from_dictionary(extra_args, 'disclaimer-title')
date_title = resolve_from_dictionary(extra_args, 'date-title')
time_title = resolve_from_dictionary(extra_args, 'time-title')
caution_title = resolve_from_dictionary(extra_args, 'caution-title')
caution_text = resolve_from_dictionary(extra_args, 'caution-text')
version_text = resolve_from_dictionary(extra_args, 'version-text')
legend_section_title = resolve_from_dictionary(
extra_args, 'legend-title')
information_title = resolve_from_dictionary(
extra_args, 'information-title')
supporters_title = resolve_from_dictionary(
extra_args, 'supporters-title')
source_title = resolve_from_dictionary(extra_args, 'source-title')
analysis_title = resolve_from_dictionary(extra_args, 'analysis-title')
reference_title = resolve_from_dictionary(
extra_args, 'spatial-reference-title')
substitution_map = {
'impact-title': title,
'date': date,
'time': time,
'safe-version': version, # deprecated
'disclaimer': inasafe_context.disclaimer,
# These added in 3.2
'version-title': version_title,
'inasafe-version': version,
'disclaimer-title': disclaimer_title,
'date-title': date_title,
'time-title': time_title,
'caution-title': caution_title,
'caution-text': caution_text,
'version-text': version_text.format(version=version),
'legend-title': legend_section_title,
'information-title': information_title,
'supporters-title': supporters_title,
'source-title': source_title,
'analysis-title': analysis_title,
'analysis-name': analysis_name,
'reference-title': reference_title,
'reference-name': reference_name,
'hazard-source': hazard_source,
'exposure-source': exposure_source,
'aggregation-source': aggregation_source,
}
context.substitution_map = substitution_map
return context
def qgis_composer_infographic_extractor(impact_report, component_metadata):
"""Extract composer context specific for infographic template.
This method extract necessary context for a given impact report and
component metadata and save the context so it can be used in composer
rendering phase
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information about the component we want to render
:type component_metadata: safe.report.report_metadata.
ReportComponentsMetadata
:return: context for rendering phase
:rtype: dict
.. versionadded:: 4.2
"""
qgis_context = impact_report.qgis_composition_context
extra_args = component_metadata.extra_args
context = QGISComposerContext()
"""Image Elements."""
# get all image elements with their respective source path
image_elements = deepcopy(image_item_elements)
# remove inasafe_logo_white because we use expression for the image source
image_elements.remove(inasafe_logo_white)
# remove population_chart because we still don't have the source path
image_elements.remove(population_chart)
context.image_elements = image_elements
# get the source path of population_chart
population_donut_path = impact_report.component_absolute_output_path(
'population-chart-png')
population_chart['path'] = population_donut_path
context.image_elements.append(population_chart)
"""HTML Elements."""
components = resolve_from_dictionary(extra_args, 'components')
html_elements = deepcopy(html_frame_elements)
# get the html content from component that has been proceed
for element in html_elements:
component = components.get(element['component'])
if component:
element['text'] = jinja2_output_as_string(
impact_report, component['key'])
context.html_frame_elements = html_elements
"""Map Elements."""
map_overview_layer = None
project = QgsProject.instance()
for layer in list(project.mapLayers().values()):
if layer.name() == map_overview['id']:
map_overview_layer = layer
layers = [impact_report.impact_function.analysis_impacted]
if map_overview_layer:
layers.append(map_overview_layer)
# default extent is analysis extent
if not qgis_context.extent:
qgis_context.extent = impact_report.impact_function.analysis_extent
map_elements = [
{
'id': 'map-overview',
'extent': qgis_context.extent,
'grid_split_count': 5,
'layers': layers,
}
]
context.map_elements = map_elements
return context
| gpl-3.0 |
svirusxxx/cjdns | node_build/dependencies/libuv/build/gyp/test/linux/gyptest-implicit-rpath.py | 252 | 1172 | #!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that the implicit rpath is added only when needed.
"""
import TestGyp
import re
import subprocess
import sys
if sys.platform.startswith('linux'):
test = TestGyp.TestGyp(formats=['ninja', 'make'])
CHDIR = 'implicit-rpath'
test.run_gyp('test.gyp', chdir=CHDIR)
test.build('test.gyp', test.ALL, chdir=CHDIR)
def GetRpaths(p):
p = test.built_file_path(p, chdir=CHDIR)
r = re.compile(r'Library rpath: \[([^\]]+)\]')
proc = subprocess.Popen(['readelf', '-d', p], stdout=subprocess.PIPE)
o = proc.communicate()[0]
assert not proc.returncode
return r.findall(o)
if test.format == 'ninja':
expect = '$ORIGIN/lib/'
elif test.format == 'make':
expect = '$ORIGIN/lib.target/'
else:
test.fail_test()
if GetRpaths('shared_executable') != [expect]:
test.fail_test()
if GetRpaths('shared_executable_no_so_suffix') != [expect]:
test.fail_test()
if GetRpaths('static_executable'):
test.fail_test()
test.pass_test()
| gpl-3.0 |
DolphinDream/sverchok | nodes/curve/nearest_point.py | 1 | 6929 | import numpy as np
import bpy
from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty
from mathutils import Matrix
from mathutils.kdtree import KDTree
import sverchok
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level, get_data_nesting_level
from sverchok.utils.logging import info, exception
from sverchok.utils.curve import SvCurve
from sverchok.utils.dummy_nodes import add_dummy
from sverchok.dependencies import scipy
if scipy is None:
add_dummy('SvExNearestPointOnCurveNode', "Nearest Point on Curve", 'scipy')
else:
from scipy.optimize import minimize_scalar
def init_guess(curve, points_from, samples=50):
u_min, u_max = curve.get_u_bounds()
us = np.linspace(u_min, u_max, num=samples)
points = curve.evaluate_array(us).tolist()
#print("P:", points)
kdt = KDTree(len(us))
for i, v in enumerate(points):
kdt.insert(v, i)
kdt.balance()
us_out = []
nearest_out = []
for point_from in points_from:
nearest, i, distance = kdt.find(point_from)
us_out.append(us[i])
nearest_out.append(tuple(nearest))
return us_out, nearest_out
def goal(curve, point_from):
def distance(t):
dv = curve.evaluate(t) - np.array(point_from)
return np.linalg.norm(dv)
return distance
class SvExNearestPointOnCurveNode(bpy.types.Node, SverchCustomTreeNode):
"""
Triggers: Nearest Point on Curve
Tooltip: Find the point on the curve which is the nearest to the given point
"""
bl_idname = 'SvExNearestPointOnCurveNode'
bl_label = 'Nearest Point on Curve'
bl_icon = 'OUTLINER_OB_EMPTY'
sv_icon = 'SV_NEAREST_CURVE'
samples : IntProperty(
name = "Init Resolution",
default = 50,
min = 3,
update = updateNode)
precise : BoolProperty(
name = "Precise",
default = True,
update = updateNode)
solvers = [
('Brent', "Brent", "Uses inverse parabolic interpolation when possible to speed up convergence of golden section method", 0),
('Bounded', "Bounded", "Uses the Brent method to find a local minimum in the interval", 1),
('Golden', 'Golden Section', "Uses the golden section search technique", 2)
]
method : EnumProperty(
name = "Method",
description = "Solver method to use; select the one which works for your case",
items = solvers,
default = 'Brent',
update = updateNode)
def draw_buttons(self, context, layout):
layout.prop(self, 'samples')
layout.prop(self, 'precise', toggle=True)
def draw_buttons_ext(self, context, layout):
layout.prop(self, 'method')
def sv_init(self, context):
self.inputs.new('SvCurveSocket', "Curve")
p = self.inputs.new('SvVerticesSocket', "Point")
p.use_prop = True
p.default_property = (0.0, 0.0, 0.0)
self.outputs.new('SvVerticesSocket', "Point")
self.outputs.new('SvStringsSocket', "T")
def process(self):
if not any(socket.is_linked for socket in self.outputs):
return
curves_s = self.inputs['Curve'].sv_get()
curves_s = ensure_nesting_level(curves_s, 2, data_types=(SvCurve,))
src_point_s = self.inputs['Point'].sv_get()
src_point_s = ensure_nesting_level(src_point_s, 4)
points_out = []
t_out = []
for curves, src_points_i in zip_long_repeat(curves_s, src_point_s):
for curve, src_points in zip_long_repeat(curves, src_points_i):
t_min, t_max = curve.get_u_bounds()
new_t = []
new_points = []
init_ts, init_points = init_guess(curve, src_points,samples=self.samples)
#self.info("I: %s", init_points)
for src_point, init_t, init_point in zip(src_points, init_ts, init_points):
if self.precise:
delta_t = (t_max - t_min) / self.samples
self.debug("T_min %s, T_max %s, init_t %s, delta_t %s", t_min, t_max, init_t, delta_t)
if init_t <= t_min:
if init_t - delta_t >= t_min:
bracket = (init_t - delta_t, init_t, t_max)
else:
bracket = None # (t_min, t_min + delta_t, t_min + 2*delta_t)
elif init_t >= t_max:
if init_t + delta_t <= t_max:
bracket = (t_min, init_t, init_t + delta_t)
else:
bracket = None # (t_max - 2*delta_t, t_max - delta_t, t_max)
else:
bracket = (t_min, init_t, t_max)
result = minimize_scalar(goal(curve, src_point),
bounds = (t_min, t_max),
bracket = bracket,
method = self.method
)
if not result.success:
if hasattr(result, 'message'):
message = result.message
else:
message = repr(result)
raise Exception("Can't find the nearest point for {}: {}".format(src_point, message))
t0 = result.x
if t0 < t_min:
t0 = t_min
elif t0 > t_max:
t0 = t_max
else:
t0 = init_t
new_points.append(init_point)
new_t.append(t0)
if self.precise and self.outputs['Point'].is_linked:
new_points = curve.evaluate_array(np.array(new_t)).tolist()
points_out.append(new_points)
t_out.append(new_t)
self.outputs['Point'].sv_set(points_out)
self.outputs['T'].sv_set(t_out)
def register():
if scipy is not None:
bpy.utils.register_class(SvExNearestPointOnCurveNode)
def unregister():
if scipy is not None:
bpy.utils.unregister_class(SvExNearestPointOnCurveNode)
| gpl-3.0 |
blackzw/openwrt_sdk_dev1 | staging_dir/target-mips_r2_uClibc-0.9.33.2/usr/lib/python2.7/unittest/runner.py | 109 | 6502 | """Running tests"""
import sys
import time
from . import result
from .signals import registerResult
__unittest = True
class _WritelnDecorator(object):
"""Used to decorate file-like objects with a handy 'writeln' method"""
def __init__(self,stream):
self.stream = stream
def __getattr__(self, attr):
if attr in ('stream', '__getstate__'):
raise AttributeError(attr)
return getattr(self.stream,attr)
def writeln(self, arg=None):
if arg:
self.write(arg)
self.write('\n') # text-mode streams translate to \r\n if needed
class TextTestResult(result.TestResult):
"""A test result class that can print formatted text results to a stream.
Used by TextTestRunner.
"""
separator1 = '=' * 70
separator2 = '-' * 70
def __init__(self, stream, descriptions, verbosity):
super(TextTestResult, self).__init__()
self.stream = stream
self.showAll = verbosity > 1
self.dots = verbosity == 1
self.descriptions = descriptions
def getDescription(self, test):
doc_first_line = test.shortDescription()
if self.descriptions and doc_first_line:
return '\n'.join((str(test), doc_first_line))
else:
return str(test)
def startTest(self, test):
super(TextTestResult, self).startTest(test)
if self.showAll:
self.stream.write(self.getDescription(test))
self.stream.write(" ... ")
self.stream.flush()
def addSuccess(self, test):
super(TextTestResult, self).addSuccess(test)
if self.showAll:
self.stream.writeln("ok")
elif self.dots:
self.stream.write('.')
self.stream.flush()
def addError(self, test, err):
super(TextTestResult, self).addError(test, err)
if self.showAll:
self.stream.writeln("ERROR")
elif self.dots:
self.stream.write('E')
self.stream.flush()
def addFailure(self, test, err):
super(TextTestResult, self).addFailure(test, err)
if self.showAll:
self.stream.writeln("FAIL")
elif self.dots:
self.stream.write('F')
self.stream.flush()
def addSkip(self, test, reason):
super(TextTestResult, self).addSkip(test, reason)
if self.showAll:
self.stream.writeln("skipped {0!r}".format(reason))
elif self.dots:
self.stream.write("s")
self.stream.flush()
def addExpectedFailure(self, test, err):
super(TextTestResult, self).addExpectedFailure(test, err)
if self.showAll:
self.stream.writeln("expected failure")
elif self.dots:
self.stream.write("x")
self.stream.flush()
def addUnexpectedSuccess(self, test):
super(TextTestResult, self).addUnexpectedSuccess(test)
if self.showAll:
self.stream.writeln("unexpected success")
elif self.dots:
self.stream.write("u")
self.stream.flush()
def printErrors(self):
if self.dots or self.showAll:
self.stream.writeln()
self.printErrorList('ERROR', self.errors)
self.printErrorList('FAIL', self.failures)
def printErrorList(self, flavour, errors):
for test, err in errors:
self.stream.writeln(self.separator1)
self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
self.stream.writeln(self.separator2)
self.stream.writeln("%s" % err)
class TextTestRunner(object):
"""A test runner class that displays results in textual form.
It prints out the names of tests as they are run, errors as they
occur, and a summary of the results at the end of the test run.
"""
resultclass = TextTestResult
def __init__(self, stream=sys.stderr, descriptions=True, verbosity=1,
failfast=False, buffer=False, resultclass=None):
self.stream = _WritelnDecorator(stream)
self.descriptions = descriptions
self.verbosity = verbosity
self.failfast = failfast
self.buffer = buffer
if resultclass is not None:
self.resultclass = resultclass
def _makeResult(self):
return self.resultclass(self.stream, self.descriptions, self.verbosity)
def run(self, test):
"Run the given test case or test suite."
result = self._makeResult()
registerResult(result)
result.failfast = self.failfast
result.buffer = self.buffer
startTime = time.time()
startTestRun = getattr(result, 'startTestRun', None)
if startTestRun is not None:
startTestRun()
try:
test(result)
finally:
stopTestRun = getattr(result, 'stopTestRun', None)
if stopTestRun is not None:
stopTestRun()
stopTime = time.time()
timeTaken = stopTime - startTime
result.printErrors()
if hasattr(result, 'separator2'):
self.stream.writeln(result.separator2)
run = result.testsRun
self.stream.writeln("Ran %d test%s in %.3fs" %
(run, run != 1 and "s" or "", timeTaken))
self.stream.writeln()
expectedFails = unexpectedSuccesses = skipped = 0
try:
results = map(len, (result.expectedFailures,
result.unexpectedSuccesses,
result.skipped))
except AttributeError:
pass
else:
expectedFails, unexpectedSuccesses, skipped = results
infos = []
if not result.wasSuccessful():
self.stream.write("FAILED")
failed, errored = map(len, (result.failures, result.errors))
if failed:
infos.append("failures=%d" % failed)
if errored:
infos.append("errors=%d" % errored)
else:
self.stream.write("OK")
if skipped:
infos.append("skipped=%d" % skipped)
if expectedFails:
infos.append("expected failures=%d" % expectedFails)
if unexpectedSuccesses:
infos.append("unexpected successes=%d" % unexpectedSuccesses)
if infos:
self.stream.writeln(" (%s)" % (", ".join(infos),))
else:
self.stream.write("\n")
return result
| gpl-2.0 |
sandipbgt/nodeshot | nodeshot/networking/links/models/link.py | 5 | 12283 | from django.contrib.gis.db import models
from django.contrib.gis.geos import LineString
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from django.db.models import Q
from django_hstore.fields import DictionaryField, ReferencesField
from netaddr import valid_ipv4, valid_ipv6, valid_mac
from nodeshot.core.base.managers import HStoreGeoAccessLevelManager as LinkManager
from nodeshot.core.base.models import BaseAccessLevel
from nodeshot.core.base.utils import choicify
from nodeshot.core.nodes.models import Node
from nodeshot.core.layers.models import Layer
from nodeshot.networking.net.models import Interface, Ip
from nodeshot.networking.net.models.choices import INTERFACE_TYPES
from .choices import METRIC_TYPES, LINK_STATUS, LINK_TYPES
from .topology import Topology
from ..exceptions import LinkDataNotFound, LinkNotFound
class Link(BaseAccessLevel):
"""
Link Model
Designed for both wireless and wired links
"""
type = models.SmallIntegerField(_('type'), null=True, blank=True,
choices=choicify(LINK_TYPES), default=LINK_TYPES.get('radio'))
# in most cases these two fields are mandatory, except for "planned" links
interface_a = models.ForeignKey(Interface, verbose_name=_('from interface'),
related_name='link_interface_from', blank=True, null=True,
help_text=_('mandatory except for "planned" links (in planned links you might not have any device installed yet)'))
interface_b = models.ForeignKey(Interface, verbose_name=_('to interface'),
related_name='link_interface_to', blank=True, null=True,
help_text=_('mandatory except for "planned" links (in planned links you might not have any device installed yet)'))
topology = models.ForeignKey(Topology, blank=True, null=True,
help_text=_('mandatory to draw the link dinamically'))
# in "planned" links these two fields are necessary
# while in all the other status they serve as a shortcut
node_a = models.ForeignKey(Node, verbose_name=_('from node'),
related_name='link_node_from', blank=True, null=True,
help_text=_('leave blank (except for planned nodes) as it will be filled in automatically'))
node_b = models.ForeignKey(Node, verbose_name=_('to node'),
related_name='link_node_to', blank=True, null=True,
help_text=_('leave blank (except for planned nodes) as it will be filled in automatically'))
# shortcut
layer = models.ForeignKey(Layer, verbose_name=_('layer'), blank=True, null=True,
help_text=_('leave blank - it will be filled in automatically'))
# geospatial info
line = models.LineStringField(blank=True, null=True, help_text=_('leave blank and the line will be drawn automatically'))
# monitoring info
status = models.SmallIntegerField(_('status'), choices=choicify(LINK_STATUS), default=LINK_STATUS.get('planned'))
first_seen = models.DateTimeField(_('first time seen on'), blank=True, null=True, default=None)
last_seen = models.DateTimeField(_('last time seen on'), blank=True, null=True, default=None)
# technical info
metric_type = models.CharField(_('metric type'), max_length=6,
choices=choicify(METRIC_TYPES), blank=True, null=True)
metric_value = models.FloatField(_('metric value'), blank=True, null=True)
max_rate = models.IntegerField(_('Maximum BPS'), null=True, default=None, blank=True)
min_rate = models.IntegerField(_('Minimum BPS'), null=True, default=None, blank=True)
# wireless specific info
dbm = models.IntegerField(_('dBm average'), null=True, default=None, blank=True)
noise = models.IntegerField(_('noise average'), null=True, default=None, blank=True)
# additional data
data = DictionaryField(_('extra data'), null=True, blank=True,
help_text=_('store extra attributes in JSON string'))
shortcuts = ReferencesField(null=True, blank=True)
# django manager
objects = LinkManager()
class Meta:
app_label = 'links'
def __unicode__(self):
return _(u'%s <> %s') % (self.node_a_name, self.node_b_name)
def clean(self, *args, **kwargs):
"""
Custom validation
1. interface_a and interface_b mandatory except for planned links
2. planned links should have at least node_a and node_b filled in
3. dbm and noise fields can be filled only for radio links
4. interface_a and interface_b must differ
5. interface a and b type must match
"""
if self.status != LINK_STATUS.get('planned'):
if self.interface_a is None or self.interface_b is None:
raise ValidationError(_('fields "from interface" and "to interface" are mandatory in this case'))
if (self.interface_a_id == self.interface_b_id) or (self.interface_a == self.interface_b):
msg = _('link cannot have same "from interface" and "to interface: %s"') % self.interface_a
raise ValidationError(msg)
if self.status == LINK_STATUS.get('planned') and (self.node_a is None or self.node_b is None):
raise ValidationError(_('fields "from node" and "to node" are mandatory for planned links'))
if self.type != LINK_TYPES.get('radio') and (self.dbm is not None or self.noise is not None):
raise ValidationError(_('Only links of type "radio" can contain "dbm" and "noise" information'))
def save(self, *args, **kwargs):
"""
Custom save does the following:
* determine link type if not specified
* automatically fill 'node_a' and 'node_b' fields if necessary
* draw line between two nodes
* fill shortcut properties node_a_name and node_b_name
"""
if not self.type:
if self.interface_a.type == INTERFACE_TYPES.get('wireless'):
self.type = LINK_TYPES.get('radio')
elif self.interface_a.type == INTERFACE_TYPES.get('ethernet'):
self.type = LINK_TYPES.get('ethernet')
else:
self.type = LINK_TYPES.get('virtual')
if self.interface_a_id:
self.interface_a = Interface.objects.get(pk=self.interface_a_id)
if self.interface_b_id:
self.interface_b = Interface.objects.get(pk=self.interface_b_id)
# fill in node_a and node_b
if self.node_a is None and self.interface_a is not None:
self.node_a = self.interface_a.node
if self.node_b is None and self.interface_b is not None:
self.node_b = self.interface_b.node
# fill layer from node_a
if self.layer is None:
self.layer = self.node_a.layer
# draw linestring
if not self.line:
self.line = LineString(self.node_a.point, self.node_b.point)
# fill properties
if self.data.get('node_a_name', None) is None:
self.data['node_a_name'] = self.node_a.name
self.data['node_b_name'] = self.node_b.name
if self.data.get('node_a_slug', None) is None or self.data.get('node_b_slug', None) is None:
self.data['node_a_slug'] = self.node_a.slug
self.data['node_b_slug'] = self.node_b.slug
if self.interface_a and self.data.get('interface_a_mac', None) is None:
self.data['interface_a_mac'] = self.interface_a.mac
if self.interface_b and self.data.get('interface_b_mac', None) is None:
self.data['interface_b_mac'] = self.interface_b.mac
if self.data.get('layer_slug') != self.layer.slug:
self.data['layer_slug'] = self.layer.slug
super(Link, self).save(*args, **kwargs)
@classmethod
def get_link(cls, source, target, topology=None):
"""
Find link between source and target, (or vice versa, order is irrelevant).
:param source: ip or mac addresses
:param target: ip or mac addresses
:param topology: optional topology relation
:returns: Link object
:raises: LinkNotFound
"""
a = source
b = target
# ensure parameters are coherent
if not (valid_ipv4(a) and valid_ipv4(b)) and not (valid_ipv6(a) and valid_ipv6(b)) and not (valid_mac(a) and valid_mac(b)):
raise ValueError('Expecting valid ipv4, ipv6 or mac address')
# get interfaces
a = cls._get_link_interface(a)
b = cls._get_link_interface(b)
# raise LinkDataNotFound if an interface is not found
not_found = []
if a is None:
not_found.append(source)
if b is None:
not_found.append(target)
if not_found:
msg = 'the following interfaces could not be found: {0}'.format(', '.join(not_found))
raise LinkDataNotFound(msg)
# find link with interfaces
# inverse order is also ok
q = (Q(interface_a=a, interface_b=b) | Q(interface_a=b, interface_b=a))
# add topology to lookup
if topology:
q = q & Q(topology=topology)
link = Link.objects.filter(q).first()
if link is None:
raise LinkNotFound('Link matching query does not exist',
interface_a=a,
interface_b=b,
topology=topology)
return link
@classmethod
def _get_link_interface(self, string_id):
if valid_ipv4(string_id) or valid_ipv6(string_id):
try:
return Ip.objects.get(address=string_id).interface
except Ip.DoesNotExist as e:
return None
else:
try:
return Interface.objects.get(mac=string_id)
except Interface.DoesNotExist as e:
return None
@classmethod
def get_or_create(cls, source, target, cost, topology=None):
"""
Tries to find a link with get_link, creates a new link if link not found.
"""
try:
return cls.get_link(source, target, topology)
except LinkNotFound as e:
pass
# create link
link = Link(interface_a=e.interface_a,
interface_b=e.interface_b,
status=LINK_STATUS['active'],
metric_value=cost,
topology=topology)
link.full_clean()
link.save()
return link
@property
def node_a_name(self):
return self.data.get('node_a_name', None)
@property
def node_b_name(self):
return self.data.get('node_b_name', None)
@property
def node_a_slug(self):
return self.data.get('node_a_slug', None)
@property
def node_b_slug(self):
return self.data.get('node_b_slug', None)
@property
def interface_a_mac(self):
return self.data.get('interface_a_mac', None)
@property
def interface_b_mac(self):
return self.data.get('interface_b_mac', None)
@property
def layer_slug(self):
return self.data.get('layer_slug', None)
@property
def quality(self):
"""
Quality is a number between 1 and 6 that rates the quality of the link.
The way quality is calculated might be overridden by settings.
0 means unknown
"""
if self.metric_value is None:
return 0
# PLACEHOLDER
return 6
def ensure(self, status, cost):
"""
ensure link properties correspond to the specified ones
perform save operation only if necessary
"""
changed = False
status_id = LINK_STATUS[status]
if self.status != status_id:
self.status = status_id
changed = True
if self.metric_value != cost:
self.metric_value = cost
changed = True
if changed:
self.save()
| gpl-3.0 |
jskew/gnuradio | gr-digital/python/digital/qa_diff_encoder.py | 57 | 3099 | #!/usr/bin/env python
#
# Copyright 2006,2007,2010,2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
import random
from gnuradio import gr, gr_unittest, digital, blocks
def make_random_int_tuple(L, min, max):
result = []
for x in range(L):
result.append(random.randint(min, max))
return tuple(result)
class test_diff_encoder(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_diff_encdec_000(self):
random.seed(0)
modulus = 2
src_data = make_random_int_tuple(1000, 0, modulus-1)
expected_result = src_data
src = blocks.vector_source_b(src_data)
enc = digital.diff_encoder_bb(modulus)
dec = digital.diff_decoder_bb(modulus)
dst = blocks.vector_sink_b()
self.tb.connect(src, enc, dec, dst)
self.tb.run() # run the graph and wait for it to finish
actual_result = dst.data() # fetch the contents of the sink
self.assertEqual(expected_result, actual_result)
def test_diff_encdec_001(self):
random.seed(0)
modulus = 4
src_data = make_random_int_tuple(1000, 0, modulus-1)
expected_result = src_data
src = blocks.vector_source_b(src_data)
enc = digital.diff_encoder_bb(modulus)
dec = digital.diff_decoder_bb(modulus)
dst = blocks.vector_sink_b()
self.tb.connect(src, enc, dec, dst)
self.tb.run() # run the graph and wait for it to finish
actual_result = dst.data() # fetch the contents of the sink
self.assertEqual(expected_result, actual_result)
def test_diff_encdec_002(self):
random.seed(0)
modulus = 8
src_data = make_random_int_tuple(40000, 0, modulus-1)
expected_result = src_data
src = blocks.vector_source_b(src_data)
enc = digital.diff_encoder_bb(modulus)
dec = digital.diff_decoder_bb(modulus)
dst = blocks.vector_sink_b()
self.tb.connect(src, enc, dec, dst)
self.tb.run() # run the graph and wait for it to finish
actual_result = dst.data() # fetch the contents of the sink
self.assertEqual(expected_result, actual_result)
if __name__ == '__main__':
gr_unittest.run(test_diff_encoder, "test_diff_encoder.xml")
| gpl-3.0 |
Soya93/Extract-Refactoring | python/lib/Lib/site-packages/django/contrib/messages/storage/__init__.py | 393 | 1183 | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_storage(import_path):
"""
Imports the message storage class described by import_path, where
import_path is the full Python path to the class.
"""
try:
dot = import_path.rindex('.')
except ValueError:
raise ImproperlyConfigured("%s isn't a Python path." % import_path)
module, classname = import_path[:dot], import_path[dot + 1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error importing module %s: "%s"' %
(module, e))
try:
return getattr(mod, classname)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a "%s" '
'class.' % (module, classname))
# Callable with the same interface as the storage classes i.e. accepts a
# 'request' object. It is wrapped in a lambda to stop 'settings' being used at
# the module level
default_storage = lambda request: get_storage(settings.MESSAGE_STORAGE)(request)
| apache-2.0 |
methoxid/micropystat | tests/bytecode/pylib-tests/keyword.py | 761 | 2049 | #! /usr/bin/env python3
"""Keywords (from "graminit.c")
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:
./python Lib/keyword.py
"""
__all__ = ["iskeyword", "kwlist"]
kwlist = [
#--start keywords--
'False',
'None',
'True',
'and',
'as',
'assert',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield',
#--end keywords--
]
iskeyword = frozenset(kwlist).__contains__
def main():
import sys, re
args = sys.argv[1:]
iptfile = args and args[0] or "Python/graminit.c"
if len(args) > 1: optfile = args[1]
else: optfile = "Lib/keyword.py"
# scan the source file for keywords
with open(iptfile) as fp:
strprog = re.compile('"([^"]+)"')
lines = []
for line in fp:
if '{1, "' in line:
match = strprog.search(line)
if match:
lines.append(" '" + match.group(1) + "',\n")
lines.sort()
# load the output skeleton from the target
with open(optfile) as fp:
format = fp.readlines()
# insert the lines of keywords
try:
start = format.index("#--start keywords--\n") + 1
end = format.index("#--end keywords--\n")
format[start:end] = lines
except ValueError:
sys.stderr.write("target does not contain format markers\n")
sys.exit(1)
# write the output file
fp = open(optfile, 'w')
fp.write(''.join(format))
fp.close()
if __name__ == "__main__":
main()
| mit |
GladeRom/android_external_chromium_org | tools/remove_stale_pyc_files.py | 106 | 1093 | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
def RemoveAllStalePycFiles(base_dir):
"""Scan directories for old .pyc files without a .py file and delete them."""
for dirname, _, filenames in os.walk(base_dir):
if '.svn' in dirname or '.git' in dirname:
continue
for filename in filenames:
root, ext = os.path.splitext(filename)
if ext != '.pyc':
continue
pyc_path = os.path.join(dirname, filename)
py_path = os.path.join(dirname, root + '.py')
try:
if not os.path.exists(py_path):
os.remove(pyc_path)
except OSError:
# Wrap OS calls in try/except in case another process touched this file.
pass
try:
os.removedirs(dirname)
except OSError:
# Wrap OS calls in try/except in case another process touched this dir.
pass
if __name__ == '__main__':
for path in sys.argv[1:]:
RemoveAllStalePycFiles(path)
| bsd-3-clause |
lituan/tools | pisa/ccp4_pisa.py | 1 | 2552 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
run pisa to parse interfaces in PDBs
first install CCP4 and change the following variables
"""
import os
import sys
import subprocess
import cPickle as pickle
from multiprocessing import Pool
os.environ['CCP4_SCR'] = 'C:\\ccp4temp'
os.environ['CCP4I_TCLTK'] = 'C:\\CCP4-7\\TclTk84\\bin'
os.environ['CBIN'] = 'C:\\CCP4-7\\7.0\\bin'
os.environ['CLIB'] = 'C:\\CCP4-7\\lib'
os.environ['CLIBD'] = 'C:\\CCP4-7\\lib\\data'
os.environ['CEXAM'] = 'C:\\CCP4-7\\examples'
os.environ['CHTML'] = 'C:\\CCP4-7\\html'
os.environ['CINCL'] = 'C:\\CCP4-7\\include'
os.environ['CCP4I_TOP'] = 'C:\\CCP4-7\\share\\ccp4i'
os.environ['CLIBD_MON'] = 'C:\\CCP4-7\\lib\\data\\monomers\\'
os.environ['MMCIFDIC'] = 'C:\\CCP4-7\\lib\\ccp4\\cif_mmdic.lib'
os.environ['CRANK'] = 'C:\\CCP4-7\\share\\ccp4i\\crank'
os.environ['CCP4_OPEN'] = 'unknown'
os.environ['GFORTRAN_UNBUFFERED_PRECONNECTED'] = 'Y'
os.environ['PATH'] = 'C:\\CCP4-7\\7.0\\bin'
os.environ['PISA_CONF_FILE'] = 'C:\\CCP4-7\\7.0\\share\\pisa\\pisa.cfg'
def pisa(f):
if not os.path.exists('detail'):
os.makedirs('detail')
if not os.path.exists('interface_xml'):
os.makedirs('interface_xml')
if not os.path.exists('assemble_xml'):
os.makedirs('assemble_xml')
pdbid = f[-8:-4].lower()
subprocess.call(['pisa',pdbid,'-analyse',f])
interface_xml_fname = os.path.join('interface_xml',pdbid+'_inteface.xml')
assemble_xml_fname = os.path.join('assemble_xml',pdbid+'_assemble.xml')
subprocess.call(['pisa',pdbid,'-xml','interfaces','>',interface_xml_fname],shell=True)
subprocess.call(['pisa',pdbid,'-xml','assemblies','>',assemble_xml_fname],shell=True)
# output = subprocess.check_output(['pisa',pdbid,'-detail','interfaces',str(interface_num)],shell=True)
for interface_num in range(100,200):
try:
output = subprocess.check_output(['pisa',pdbid,'-detail','interfaces',str(interface_num)],shell=True)
detail_fname = os.path.join('detail',pdbid+'_'+str(interface_num)+'_detail.txt')
subprocess.call(['pisa',pdbid,'-detail','interfaces',str(interface_num),'>',detail_fname],shell=True)
except:
continue
def main():
parameters = []
for root,dirs,files in os.walk(sys.argv[-1]):
for f in files:
if f[-4:] == '.pdb' and len(f) == 8:
f = os.path.join(root,f)
parameters.append(f)
p = Pool(8)
p.map(pisa,parameters)
p.close()
if __name__ == "__main__":
main()
| cc0-1.0 |
adngdb/socorro | socorro/external/postgresql/fakedata.py | 3 | 37384 | #!/usr/bin/python
#
# Generate fake data for Socorro.
#
# Products, versions, number of days to generate data for, etc. are
# configurable, and test data is randomized using configurable probability
# but deterministic (within reason.)
import datetime
import uuid
import random
import json
crash_ids = []
def date_range(start_date, end_date, delta=None):
if delta is None:
delta = datetime.timedelta(days=1)
if start_date > end_date:
raise Exception('start_date must be <= end_date')
while start_date <= end_date:
yield start_date
start_date += delta
# based on http://code.activestate.com/recipes/117241
def weighted_choice(items):
"""items is a list of tuples in the form (item, weight)"""
weight_total = sum((item[1] for item in items))
n = random.uniform(0, weight_total)
for item, weight in items:
if n < weight:
return item
n = n - weight
return item
class BaseTable(object):
def __init__(self, days=None):
# use a known seed for PRNG to get deterministic behavior.
random.seed(5)
self.days = days or 7
self.end_date = datetime.datetime.utcnow()
self.start_date = self.end_date - datetime.timedelta(self.days)
self.releases = {
'WaterWolf': {
'channels': {
'ESR': {
'versions': [{
'number': '1.0',
'probability': 0.5,
'buildid': '%s000000'
}],
'adu': '100',
'repository': 'esr',
'throttle': '1'
},
'Release': {
'versions': [{
'number': '2.0',
'probability': 0.5,
'buildid': '%s000001'
}, {
'number': '2.1',
'probability': 0.5,
'buildid': '%s000002'
}],
'adu': '10000',
'repository': 'release',
'throttle': '0.1'
},
'Beta': {
'versions': [{
'number': '3.0',
'probability': 0.06,
'buildid': '%s000099',
'beta_number': '99'
}, {
'number': '3.0',
'probability': 0.06,
'buildid': '%s000015',
'beta_number': '1'
}, {
'number': '3.1',
'probability': 0.02,
'buildid': '%s000004',
'beta_number': '1'
}],
'adu': '100',
'repository': 'beta',
'throttle': '1'
},
'Aurora': {
'versions': [{
'number': '4.0a2',
'probability': 0.03,
'buildid': '%s000005'
}, {
'number': '3.0a2',
'probability': 0.01,
'buildid': '%s000006'
}],
'adu': '100',
'repository': 'dev',
'throttle': '1'
},
'Nightly': {
'versions': [{
'number': '5.0a1',
'probability': 0.01,
'buildid': '%s000007'
}, {
'number': '4.0a1',
'probability': 0.001,
'buildid': '%s000008'
}],
'adu': '100',
'repository': 'dev',
'throttle': '1'
}
},
'crashes_per_hour': '100',
'guid': '{waterwolf@example.com}'
},
'NightTrain': {
'channels': {
'ESR': {
'versions': [{
'number': '1.0',
'probability': 0.5,
'buildid': '%s000010'
}],
'adu': '10',
'repository': 'esr',
'throttle': '1'
},
'Release': {
'versions': [{
'number': '2.0',
'probability': 0.5,
'buildid': '%s000011'
}, {
'number': '2.1',
'probability': 0.5,
'buildid': '%s000012'
}],
'adu': '1000',
'repository': 'release',
'throttle': '0.1'
},
'Beta': {
'versions': [{
'number': '3.0',
'probability': 0.06,
'buildid': '%s000013',
'beta_number': '2'
}, {
'number': '3.1',
'probability': 0.02,
'buildid': '%s000014',
'beta_number': '1'
}],
'adu': '10',
'repository': 'beta',
'throttle': '1'
},
'Aurora': {
'versions': [{
'number': '4.0a2',
'probability': 0.03,
'buildid': '%s000015'
}, {
'number': '3.0a2',
'probability': 0.01,
'buildid': '%s000016'
}],
'adu': '10',
'repository': 'dev',
'throttle': '1'
},
'Nightly': {
'versions': [{
'number': '5.0a1',
'probability': 0.01,
'buildid': '%s000017'
}, {
'number': '4.0a1',
'probability': 0.001,
'buildid': '%s000018'
}],
'adu': '10',
'repository': 'dev',
'throttle': '1'
}
},
'crashes_per_hour': '50',
'guid': '{nighttrain@example.com}'
},
'B2G': {
'channels': {
'Nightly': {
'versions': [{
'number': '18.0',
'probability': 0.5,
'buildid': '%s000020'
}],
'adu': '10',
'repository': 'nightly',
'throttle': '1',
'update_channel': 'nightly',
},
'Default': {
'versions': [{
'number': '18.0',
'probability': 0.1,
'buildid': '%s000021'
}],
'adu': '10',
'repository': 'nightly',
'throttle': '1',
'update_channel': 'default',
}
},
'crashes_per_hour': '50',
'guid': '{b2g@example.com}'
}
}
self.oses = {
'Linux': {
'short_name': 'lin',
'versions': {
'Linux': {
'major': '2',
'minor': '6'}
}
},
'Mac OS X': {
'short_name': 'mac',
'versions': {
'OS X 10.8': {
'major': '10',
'minor': '8'
}
}
},
'Windows': {
'short_name': 'win',
'versions': {
'Windows NT(4)': {
'major': '3',
'minor': '5'
},
'Windows NT(3)': {
'major': '4',
'minor': '0'
},
'Windows 98': {
'major': '4',
'minor': '1'
},
'Windows Me': {
'major': '4',
'minor': '9'
},
'Windows 2000': {
'major': '4',
'minor': '1'
},
'Windows XP': {
'major': '5',
'minor': '1'
},
'Windows Vista': {
'major': '6',
'minor': '0'
},
'Windows 7': {
'major': '6',
'minor': '1'
}
}
}
}
# signature name and probability.
self.signatures = {
'': 0.25,
'FakeSignature1': 0.25,
'FakeSignature2': 0.15,
'FakeSignature3': 0.10,
'FakeSignature4': 0.05,
'FakeSignature5': 0.05,
'FakeSignature6': 0.05,
'FakeSignature7': 0.05,
'FakeSignature8': 0.025,
'FakeSignature9': 0.025
}
# flash version and probability.
self.flash_versions = {
'1.1.1.1': 0.25,
'1.1.1.2': 0.25,
'1.1.1.3': 0.25,
'1.1.1.4': 0.25
}
# crash type and probability.
self.process_types = {
'browser': 0.5,
'plugin': 0.25,
'content': 0.25
}
# crash reason and probability.
self.crash_reasons = {
'reason0': 0.1,
'reason1': 0.1,
'reason2': 0.1,
'reason3': 0.1,
'reason4': 0.1,
'reason5': 0.1,
'reason6': 0.1,
'reason7': 0.1,
'reason8': 0.1,
'reason9': 0.1
}
# URL and probability.
self.urls = [
('%s/%s' % ('http://example.com', random.getrandbits(16)), 0.7)
for x in range(100)]
# email address and probability.
self.email_addresses = [
('socorro-%s@%s' % (random.getrandbits(16), 'restmail.net'), 0.01)
for x in range(10)]
self.email_addresses.append((None, 0.9))
# crash user comments and probability.
self.comments = {
'comment0': 0.1,
'comment1': 0.1,
'comment2': 0.1,
'comment3': 0.1,
'comment4': 0.1,
'comment5': 0.1,
'comment6': 0.1,
'comment7': 0.1,
'comment8': 0.1,
'comment9': 0.1
}
# this should be overridden when fake data is to be generated.
# it will work for static data as-is.
def generate_rows(self):
return iter(self.rows)
# this uses random instead of simply using uuid to get deterministic
# behavior, since random is seeded
def generate_crashid(self, timestamp):
crashid = str(uuid.UUID(int=random.getrandbits(128)))
depth = 0
final_crashid = "%s%d%02d%02d%02d" % (crashid[:-7],
depth,
timestamp.year % 100,
timestamp.month,
timestamp.day)
crash_ids.append((final_crashid, timestamp))
return final_crashid
def buildid(self, fragment, format='%Y%m%d', days=None):
days = days or self.days
builddate = self.end_date - datetime.timedelta(days=days)
return fragment % builddate.strftime(format)
# nightly and aurora have releases posted every night
def daily_builds(self, fragment, channel, days=None):
buildids = []
days = days or self.days
if channel == 'Nightly' or channel == 'Aurora':
for day in xrange(0, self.days):
buildids.append(self.buildid(fragment, days=day))
else:
buildids.append(self.buildid(fragment))
return buildids
def generate_processed_crash_rows(self):
count = 0
for product in self.releases:
cph = self.releases[product]['crashes_per_hour']
delta = datetime.timedelta(minutes=(60.0 / int(cph)))
for timestamp in date_range(self.start_date, self.end_date, delta):
choices = []
for channel in self.releases[product]['channels']:
versions = self.releases[product][
'channels'][channel]['versions']
adu = self.releases[product]['channels'][channel]['adu']
for version in versions:
probability = float(version['probability'])
self.releases[product]['channels'][
channel]['name'] = channel
choice = (version, adu, channel)
choices.append((choice, probability))
(version, adu, channel_name) = weighted_choice(choices)
number = version['number']
buildids = self.daily_builds(version['buildid'], channel_name)
product_guid = self.releases[product]['guid']
# TODO enumerate correct values
exploitability = 'medium'
for os_name in self.oses:
# TODO need to review, want to fake more of these
client_crash_date = timestamp.strftime(
'%Y-%m-%d %H:%M:%S+00:00')
date_processed = str(timestamp)
signature = weighted_choice([(
x, self.signatures[x]) for x in self.signatures])
amt = 1
for i in xrange(amt):
url = weighted_choice(self.urls)
install_age = '1234'
last_crash = '1234'
uptime = '1234'
cpu_name = 'x86'
cpu_info = '...'
reason = weighted_choice([
(x, self.crash_reasons[x])
for x in self.crash_reasons
])
address = '0xdeadbeef'
os_version = '1.2.3.4'
email = weighted_choice(self.email_addresses)
user_id = ''
started_datetime = str(timestamp)
completed_datetime = str(timestamp)
success = 't'
truncated = 'f'
processor_notes = '...'
user_comments = None
# if there is an email, always include a comment
if email:
user_comments = weighted_choice([
(x, self.comments[x])
for x in self.comments
])
app_notes = ''
distributor = ''
distributor_version = ''
topmost_filenames = ''
addons_checked = 'f'
flash_version = weighted_choice([
(x, self.flash_versions[x])
for x in self.flash_versions])
hangid = ''
process_type = weighted_choice([
(x, self.process_types[x])
for x in self.process_types])
for buildid in buildids:
row = [str(count),
client_crash_date,
date_processed,
self.generate_crashid(timestamp),
product,
number,
buildid,
signature,
url,
install_age,
last_crash,
uptime,
cpu_name,
cpu_info,
reason,
address,
os_name,
os_version,
email,
user_id,
started_datetime,
completed_datetime,
success,
truncated,
processor_notes,
user_comments,
app_notes,
distributor,
distributor_version,
topmost_filenames,
addons_checked,
flash_version,
hangid,
process_type,
channel_name,
product_guid,
exploitability,
channel_name]
yield row
count += 1
class Products(BaseTable):
table = 'products'
columns = ['product_name', 'sort', 'rapid_release_version',
'release_name', 'rapid_beta_version']
def generate_rows(self):
for i, product in enumerate(self.releases):
row = [product, str(i), 1.0, product.lower(), 3.0]
yield row
class ProductBuildTypes(BaseTable):
table = 'product_build_types' # replaces product_release_channels
columns = ['product_name', 'build_type', 'throttle']
def generate_rows(self):
for product in self.releases:
for channel in self.releases[product]['channels']:
if channel == 'Default':
continue
throttle = self.releases[product][
'channels'][channel]['throttle']
row = [product, channel.lower(), throttle]
yield row
# DEPRECATED
class ProductReleaseChannels(BaseTable):
table = 'product_release_channels'
columns = ['product_name', 'release_channel', 'throttle']
def generate_rows(self):
for product in self.releases:
for channel in self.releases[product]['channels']:
# FIXME hackaround for B2G
if product == 'B2G' and channel == 'Nightly':
channel = 'Release'
throttle = '1'
else:
if channel == 'Default':
continue
throttle = self.releases[product][
'channels'][channel]['throttle']
row = [product, channel, throttle]
yield row
class RawADI(BaseTable):
table = 'raw_adi'
columns = ['adi_count', 'date', 'product_name', 'product_os_platform',
'product_os_version', 'product_version', 'build',
'product_guid', 'received_at', 'update_channel']
def generate_rows(self):
for timestamp in date_range(self.start_date, self.end_date):
received_at = timestamp.today() - datetime.timedelta(days=1)
for product in self.releases:
for channel in self.releases[product]['channels']:
versions = self.releases[product][
'channels'][channel]['versions']
for version in versions:
number = version['number']
buildids = self.daily_builds(
version['buildid'], channel)
adu = self.releases[product][
'channels'][channel]['adu']
product_guid = self.releases[product]['guid']
for os_name in self.oses:
for buildid in buildids:
row = [adu, str(timestamp), product, os_name,
os_name, number, buildid,
product_guid, str(received_at),
channel.lower()]
yield row
class ReleasesRaw(BaseTable):
table = 'releases_raw'
columns = ['product_name', 'version', 'platform', 'build_id',
'update_channel', 'beta_number', 'repository',
'build_type', 'version_build']
def generate_rows(self):
for product in self.releases:
for channel in self.releases[product]['channels']:
for os_name in self.oses:
versions = self.releases[product][
'channels'][channel]['versions']
for version in versions:
buildids = self.daily_builds(
version['buildid'], channel)
number = version['number']
if 'esr' in number:
number = number.split('esr')[0]
beta_number = 0
if 'beta_number' in version:
beta_number = version['beta_number']
repository = self.releases[product][
'channels'][channel]['repository']
update_channel = channel
if channel == 'esr':
update_channel = 'Release'
version_build = beta_number
if channel == 'beta' and version['beta_number'] == 99:
version_build = 'build1'
for buildid in buildids:
row = [product.lower(), number, os_name,
buildid, update_channel.lower(),
beta_number, repository,
update_channel.lower(),
version_build]
yield row
class Reports(BaseTable):
table = 'reports'
columns = ['id', 'client_crash_date', 'date_processed', 'uuid', 'product',
'version', 'build', 'signature', 'url', 'install_age',
'last_crash', 'uptime', 'cpu_name', 'cpu_info', 'reason',
'address', 'os_name', 'os_version', 'email', 'user_id',
'started_datetime', 'completed_datetime', 'success',
'truncated', 'processor_notes', 'user_comments', 'app_notes',
'distributor', 'distributor_version', 'topmost_filenames',
'addons_checked', 'flash_version', 'hangid', 'process_type',
'release_channel', 'productid', 'exploitability',
'update_channel']
def generate_rows(self):
return self.generate_processed_crash_rows()
class ProductProductidMap(BaseTable):
table = 'product_productid_map'
columns = ['product_name', 'productid', 'rewrite', 'version_began',
'version_ended']
rows = [
['WaterWolf', '{waterwolf@example.org}', 'f', '1.0', '1.0'],
['B2G', '{3c2e2abc-06d4-11e1-ac3b-374f68613e61}', 'f', '1.0', '1.0'],
]
class RawCrashes(BaseTable):
table = 'raw_crashes'
columns = ['uuid', 'raw_crash', 'date_processed']
def generate_rows(self):
vendors = [u'0x8086', u'0x1002', u'0x10de']
devices = [u'0x2972', u'0x9804', u'0xa011']
android = [
{
'manufacturer': 'samsung',
'model': 'GT-P5100',
'android_version': '16 (REL)',
'cpu_abi': ' armeabi-v7a',
'b2g_os_version': '1.0.1.0-prerelease',
'product_name': 'B2G',
'release_channel': 'nightly',
'version': '18.0'
},
{
'manufacturer': 'asus',
'model': 'Nexus 7',
'android_version': '15 (REL)',
'cpu_abi': ' armeabi-v7a',
'b2g_os_version': '1.0.1.0-prerelease',
'product_name': 'B2G',
'release_channel': 'nightly',
'version': '18.0'
},
{
'manufacturer': 'samsung',
'model': ' GT-N8020',
'android_version': '16 (REL)',
'cpu_abi': ' armeabi-v7a',
'b2g_os_version': '1.0.1.0-prerelease',
'product_name': 'B2G',
'release_channel': 'nightly',
'version': '18.0'
},
{
'manufacturer': 'ZTE',
'model': ' roamer2',
'android_version': '15 (REL)',
'cpu_abi': ' armeabi-v7a',
'b2g_os_version': '1.0.1.0-prerelease',
'product_name': 'B2G',
'release_channel': 'nightly',
'version': '18.0'
},
]
for crashid, date_processed, in crash_ids:
android_device = random.choice(android)
raw_crash = {
"uuid": crashid,
"IsGarbageCollecting": "1",
"AdapterVendorID": random.choice(vendors),
"AdapterDeviceID": random.choice(devices),
"Android_CPU_ABI": android_device['cpu_abi'],
"Android_Manufacturer": android_device['manufacturer'],
"Android_Model": android_device['model'],
"Android_Version": android_device['android_version'],
"B2G_OS_Version": android_device['b2g_os_version'],
"ProductName": android_device['product_name'],
"ReleaseChannel": android_device['release_channel'],
"Version": android_device['version']
}
row = [crashid, json.dumps(raw_crash), date_processed]
yield row
class UpdateChannelMap(BaseTable):
table = 'update_channel_map'
columns = ['update_channel', 'productid', 'version_field', 'rewrite']
def generate_rows(self):
buildids = self.daily_builds('%s000020', 'Nightly')
rewrite = {
"Android_Manufacturer": "ZTE",
"Android_Model": " roamer2",
"Android_Version": "15 (REL)",
"B2G_OS_Version": "1.0.1.0-prerelease",
"BuildID": buildids,
"ProductName": "B2G",
"ReleaseChannel": "nightly",
"Version": "18.0",
"rewrite_update_channel_to": "release-zte",
"rewrite_build_type_to": "release"
}
row = [['nightly', '{3c2e2abc-06d4-11e1-ac3b-374f68613e61}',
'B2G_OS_Version', json.dumps(rewrite)]]
return row
class ProcessedCrashes(BaseTable):
table = 'processed_crashes'
columns = ['uuid', 'processed_crash', 'date_processed']
def generate_rows(self):
for data in self.generate_processed_crash_rows():
processed_crash = dict(zip((
'id', 'client_crash_date', 'date_processed', 'uuid', 'product',
'version', 'build', 'signature', 'url', 'install_age',
'last_crash', 'uptime', 'cpu_name', 'cpu_info', 'reason',
'address', 'os_name', 'os_version', 'email', 'user_id',
'started_datetime', 'completed_datetime', 'success',
'truncated', 'processor_notes', 'user_comments', 'app_notes',
'distributor', 'distributor_version', 'topmost_filenames',
'addons_checked', 'flash_version', 'hangid', 'process_type',
'release_channel', 'productid', 'exploitability',
'update_channel'
), data))
processed_crash.update({ # noqa
"ReleaseChannel": "release",
"Winsock_LSP": "",
"additional_minidumps": [],
"addons": [
[
"WebSiteRecommendation@weliketheweb.com",
"1.1.1"
],
[
"{972ce4c6-7e08-4474-a285-3208198ce6fd}",
"24.3.0"
]
],
"completeddatetime": "2014-02-19 00:00:17.670013",
"crash_time": 1392767976,
"crashedThread": 0,
"hang_type": 0,
"java_stack_trace": None,
"json_dump": {
"crash_info": {
"address": "0x60943b3c",
"crashing_thread": 0,
"type": "EXCEPTION_ACCESS_VIOLATION_READ"
},
"crashing_thread": {
"frames": [
{
"file": "f:/dd/vctools/crt_bld/SELF_X86/crt/src/INTEL/memcpy.asm",
"frame": 0,
"function": "memcpy",
"function_offset": "0x154",
"line": 319,
"module": "msvcr100.dll",
"module_offset": "0x1fd4",
"offset": "0x6ce51fd4",
"trust": "context"
},
{
"file": (
"hg:hg.mozilla.org/releases/mozilla-esr24:xpcom"
"/string/src/nsTSubstring.cpp:d06a17a96fa2"
),
"frame": 1,
"function": (
"nsACString_internal::Assign(nsCSubstringTuple "
"const &,mozilla::fallible_t const &)"
),
"function_offset": "0xa4",
"line": 416,
"module": "xul.dll",
"module_offset": "0xe2884",
"offset": "0x63892884",
"trust": "frame_pointer"
},
{
"file": (
"hg:hg.mozilla.org/releases/mozilla-esr24:xpcom/"
"string/src/nsTSubstring.cpp:d06a17a96fa2"
),
"frame": 2,
"function": (
"nsACString_internal::Assign(nsCSubstringTuple const &)"
),
"function_offset": "0x6",
"line": 392,
"module": "xul.dll",
"module_offset": "0x1293ac",
"offset": "0x638d93ac",
"trust": "cfi"
}
],
"threads_index": 0,
"total_frames": 2
},
"largest_free_vm_block": "0x70df0000",
"main_module": 0,
"modules": [
{
"base_addr": "0x950000",
"debug_file": "firefox.pdb",
"debug_id": "2B38B86A9FD04FABB58EF77C7CD654092",
"end_addr": "0x994000",
"filename": "firefox.exe",
"version": "24.3.0.5144"
},
{
"base_addr": "0x2c60000",
"debug_file": "kswebshield.pdb",
"debug_id": "056410AE957A40038EAA8984EAD6EC1A1",
"end_addr": "0x2d4f000",
"filename": "kswebshield.dll",
"missing_symbols": True,
"version": "2013.4.9.86"
},
],
"sensitive": {
"exploitability": "low"
},
"status": "OK",
"system_info": {
"cpu_arch": "x86",
"cpu_count": 4,
"cpu_info": "GenuineIntel family 6 model 58 stepping 9",
"os": "Windows NT",
"os_ver": "6.1.7601 Service Pack 1"
},
"thread_count": 50,
"threads": [
{
"frame_count": 2,
"frames": [
{
"file": (
"f:/dd/vctools/crt_bld/SELF_X86/crt/src/INTEL/memcpy.asm"
),
"frame": 0,
"function": "memcpy",
"function_offset": "0x154",
"line": 319,
"module": "msvcr100.dll",
"module_offset": "0x1fd4",
"offset": "0x6ce51fd4",
"trust": "context"
},
{
"file": (
"hg:hg.mozilla.org/releases/mozilla-esr24:xpcom"
"/string/src/nsTSubstring.cpp:d06a17a96fa2"
),
"frame": 1,
"function": (
"nsACString_internal::Assign(nsCSubstringTuple "
"const &,mozilla::fallible_t const &)"
),
"function_offset": "0xa4",
"line": 416,
"module": "xul.dll",
"module_offset": "0xe2884",
"offset": "0x63892884",
"trust": "frame_pointer"
},
]
},
],
},
"pluginFilename": None,
"pluginName": None,
"pluginVersion": None,
})
row = [
processed_crash['uuid'],
json.dumps(processed_crash),
processed_crash['date_processed']
]
yield row
# the order that tables are loaded is important.
tables = [Products, ProductReleaseChannels, ProductBuildTypes,
RawADI, ReleasesRaw, Reports, RawCrashes, UpdateChannelMap,
ProcessedCrashes, ProductProductidMap]
# FIXME this could be built up from BaseTable's releases dict, instead
featured_versions = ('5.0a1', '4.0a2', '3.1b1', '2.1')
| mpl-2.0 |
kisna72/django | django/template/defaulttags.py | 17 | 53746 | """Default tags used by the template system, available to all templates."""
from __future__ import unicode_literals
import os
import re
import sys
import warnings
from datetime import datetime
from itertools import cycle as itertools_cycle, groupby
from django.conf import settings
from django.utils import six, timezone
from django.utils.deprecation import RemovedInDjango110Warning
from django.utils.encoding import force_text, smart_text
from django.utils.html import conditional_escape, format_html
from django.utils.lorem_ipsum import paragraphs, words
from django.utils.safestring import mark_safe
from .base import (
BLOCK_TAG_END, BLOCK_TAG_START, COMMENT_TAG_END, COMMENT_TAG_START,
SINGLE_BRACE_END, SINGLE_BRACE_START, VARIABLE_ATTRIBUTE_SEPARATOR,
VARIABLE_TAG_END, VARIABLE_TAG_START, Context, Node, NodeList, Template,
TemplateSyntaxError, VariableDoesNotExist, kwarg_re,
render_value_in_context, token_kwargs,
)
from .defaultfilters import date
from .library import Library
from .smartif import IfParser, Literal
register = Library()
class AutoEscapeControlNode(Node):
"""Implements the actions of the autoescape tag."""
def __init__(self, setting, nodelist):
self.setting, self.nodelist = setting, nodelist
def render(self, context):
old_setting = context.autoescape
context.autoescape = self.setting
output = self.nodelist.render(context)
context.autoescape = old_setting
if self.setting:
return mark_safe(output)
else:
return output
class CommentNode(Node):
def render(self, context):
return ''
class CsrfTokenNode(Node):
def render(self, context):
csrf_token = context.get('csrf_token')
if csrf_token:
if csrf_token == 'NOTPROVIDED':
return format_html("")
else:
return format_html("<input type='hidden' name='csrfmiddlewaretoken' value='{}' />", csrf_token)
else:
# It's very probable that the token is missing because of
# misconfiguration, so we raise a warning
if settings.DEBUG:
warnings.warn(
"A {% csrf_token %} was used in a template, but the context "
"did not provide the value. This is usually caused by not "
"using RequestContext."
)
return ''
class CycleNode(Node):
def __init__(self, cyclevars, variable_name=None, silent=False):
self.cyclevars = cyclevars
self.variable_name = variable_name
self.silent = silent
def render(self, context):
if self not in context.render_context:
# First time the node is rendered in template
context.render_context[self] = itertools_cycle(self.cyclevars)
cycle_iter = context.render_context[self]
value = next(cycle_iter).resolve(context)
if self.variable_name:
context[self.variable_name] = value
if self.silent:
return ''
return render_value_in_context(value, context)
class DebugNode(Node):
def render(self, context):
from pprint import pformat
output = [force_text(pformat(val)) for val in context]
output.append('\n\n')
output.append(force_text(pformat(sys.modules)))
return ''.join(output)
class FilterNode(Node):
def __init__(self, filter_expr, nodelist):
self.filter_expr, self.nodelist = filter_expr, nodelist
def render(self, context):
output = self.nodelist.render(context)
# Apply filters.
with context.push(var=output):
return self.filter_expr.resolve(context)
class FirstOfNode(Node):
def __init__(self, variables, asvar=None):
self.vars = variables
self.asvar = asvar
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
first = render_value_in_context(value, context)
if self.asvar:
context[self.asvar] = first
return ''
return first
return ''
class ForNode(Node):
child_nodelists = ('nodelist_loop', 'nodelist_empty')
def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None):
self.loopvars, self.sequence = loopvars, sequence
self.is_reversed = is_reversed
self.nodelist_loop = nodelist_loop
if nodelist_empty is None:
self.nodelist_empty = NodeList()
else:
self.nodelist_empty = nodelist_empty
def __repr__(self):
reversed_text = ' reversed' if self.is_reversed else ''
return "<For Node: for %s in %s, tail_len: %d%s>" % \
(', '.join(self.loopvars), self.sequence, len(self.nodelist_loop),
reversed_text)
def __iter__(self):
for node in self.nodelist_loop:
yield node
for node in self.nodelist_empty:
yield node
def render(self, context):
if 'forloop' in context:
parentloop = context['forloop']
else:
parentloop = {}
with context.push():
try:
values = self.sequence.resolve(context, True)
except VariableDoesNotExist:
values = []
if values is None:
values = []
if not hasattr(values, '__len__'):
values = list(values)
len_values = len(values)
if len_values < 1:
return self.nodelist_empty.render(context)
nodelist = []
if self.is_reversed:
values = reversed(values)
num_loopvars = len(self.loopvars)
unpack = num_loopvars > 1
# Create a forloop value in the context. We'll update counters on each
# iteration just below.
loop_dict = context['forloop'] = {'parentloop': parentloop}
for i, item in enumerate(values):
# Shortcuts for current loop iteration number.
loop_dict['counter0'] = i
loop_dict['counter'] = i + 1
# Reverse counter iteration numbers.
loop_dict['revcounter'] = len_values - i
loop_dict['revcounter0'] = len_values - i - 1
# Boolean values designating first and last times through loop.
loop_dict['first'] = (i == 0)
loop_dict['last'] = (i == len_values - 1)
pop_context = False
if unpack:
# If there are multiple loop variables, unpack the item into
# them.
# To complete this deprecation, remove from here to the
# try/except block as well as the try/except itself,
# leaving `unpacked_vars = ...` and the "else" statements.
if not isinstance(item, (list, tuple)):
len_item = 1
else:
len_item = len(item)
# Check loop variable count before unpacking
if num_loopvars != len_item:
warnings.warn(
"Need {} values to unpack in for loop; got {}. "
"This will raise an exception in Django 1.10."
.format(num_loopvars, len_item),
RemovedInDjango110Warning)
try:
unpacked_vars = dict(zip(self.loopvars, item))
except TypeError:
pass
else:
pop_context = True
context.update(unpacked_vars)
else:
context[self.loopvars[0]] = item
for node in self.nodelist_loop:
nodelist.append(node.render_annotated(context))
if pop_context:
# The loop variables were pushed on to the context so pop them
# off again. This is necessary because the tag lets the length
# of loopvars differ to the length of each set of items and we
# don't want to leave any vars from the previous loop on the
# context.
context.pop()
return mark_safe(''.join(force_text(n) for n in nodelist))
class IfChangedNode(Node):
child_nodelists = ('nodelist_true', 'nodelist_false')
def __init__(self, nodelist_true, nodelist_false, *varlist):
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
self._varlist = varlist
def render(self, context):
# Init state storage
state_frame = self._get_context_stack_frame(context)
if self not in state_frame:
state_frame[self] = None
nodelist_true_output = None
try:
if self._varlist:
# Consider multiple parameters. This automatically behaves
# like an OR evaluation of the multiple variables.
compare_to = [var.resolve(context, True) for var in self._varlist]
else:
# The "{% ifchanged %}" syntax (without any variables) compares the rendered output.
compare_to = nodelist_true_output = self.nodelist_true.render(context)
except VariableDoesNotExist:
compare_to = None
if compare_to != state_frame[self]:
state_frame[self] = compare_to
# render true block if not already rendered
return nodelist_true_output or self.nodelist_true.render(context)
elif self.nodelist_false:
return self.nodelist_false.render(context)
return ''
def _get_context_stack_frame(self, context):
# The Context object behaves like a stack where each template tag can create a new scope.
# Find the place where to store the state to detect changes.
if 'forloop' in context:
# Ifchanged is bound to the local for loop.
# When there is a loop-in-loop, the state is bound to the inner loop,
# so it resets when the outer loop continues.
return context['forloop']
else:
# Using ifchanged outside loops. Effectively this is a no-op because the state is associated with 'self'.
return context.render_context
class IfEqualNode(Node):
child_nodelists = ('nodelist_true', 'nodelist_false')
def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
self.var1, self.var2 = var1, var2
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
self.negate = negate
def __repr__(self):
return "<IfEqualNode>"
def render(self, context):
val1 = self.var1.resolve(context, True)
val2 = self.var2.resolve(context, True)
if (self.negate and val1 != val2) or (not self.negate and val1 == val2):
return self.nodelist_true.render(context)
return self.nodelist_false.render(context)
class IfNode(Node):
def __init__(self, conditions_nodelists):
self.conditions_nodelists = conditions_nodelists
def __repr__(self):
return "<IfNode>"
def __iter__(self):
for _, nodelist in self.conditions_nodelists:
for node in nodelist:
yield node
@property
def nodelist(self):
return NodeList(node for _, nodelist in self.conditions_nodelists for node in nodelist)
def render(self, context):
for condition, nodelist in self.conditions_nodelists:
if condition is not None: # if / elif clause
try:
match = condition.eval(context)
except VariableDoesNotExist:
match = None
else: # else clause
match = True
if match:
return nodelist.render(context)
return ''
class LoremNode(Node):
def __init__(self, count, method, common):
self.count, self.method, self.common = count, method, common
def render(self, context):
try:
count = int(self.count.resolve(context))
except (ValueError, TypeError):
count = 1
if self.method == 'w':
return words(count, common=self.common)
else:
paras = paragraphs(count, common=self.common)
if self.method == 'p':
paras = ['<p>%s</p>' % p for p in paras]
return '\n\n'.join(paras)
class RegroupNode(Node):
def __init__(self, target, expression, var_name):
self.target, self.expression = target, expression
self.var_name = var_name
def resolve_expression(self, obj, context):
# This method is called for each object in self.target. See regroup()
# for the reason why we temporarily put the object in the context.
context[self.var_name] = obj
return self.expression.resolve(context, True)
def render(self, context):
obj_list = self.target.resolve(context, True)
if obj_list is None:
# target variable wasn't found in context; fail silently.
context[self.var_name] = []
return ''
# List of dictionaries in the format:
# {'grouper': 'key', 'list': [list of contents]}.
context[self.var_name] = [
{'grouper': key, 'list': list(val)}
for key, val in
groupby(obj_list, lambda obj: self.resolve_expression(obj, context))
]
return ''
def include_is_allowed(filepath, allowed_include_roots):
filepath = os.path.abspath(filepath)
for root in allowed_include_roots:
if filepath.startswith(root):
return True
return False
class SsiNode(Node):
def __init__(self, filepath, parsed):
self.filepath = filepath
self.parsed = parsed
def render(self, context):
filepath = self.filepath.resolve(context)
if not include_is_allowed(filepath, context.template.engine.allowed_include_roots):
if settings.DEBUG:
return "[Didn't have permission to include file]"
else:
return '' # Fail silently for invalid includes.
try:
with open(filepath, 'r') as fp:
output = fp.read()
except IOError:
output = ''
if self.parsed:
try:
t = Template(output, name=filepath, engine=context.template.engine)
return t.render(context)
except TemplateSyntaxError as e:
if settings.DEBUG:
return "[Included template had syntax error: %s]" % e
else:
return '' # Fail silently for invalid included templates.
return output
class LoadNode(Node):
def render(self, context):
return ''
class NowNode(Node):
def __init__(self, format_string, asvar=None):
self.format_string = format_string
self.asvar = asvar
def render(self, context):
tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None
formatted = date(datetime.now(tz=tzinfo), self.format_string)
if self.asvar:
context[self.asvar] = formatted
return ''
else:
return formatted
class SpacelessNode(Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
from django.utils.html import strip_spaces_between_tags
return strip_spaces_between_tags(self.nodelist.render(context).strip())
class TemplateTagNode(Node):
mapping = {'openblock': BLOCK_TAG_START,
'closeblock': BLOCK_TAG_END,
'openvariable': VARIABLE_TAG_START,
'closevariable': VARIABLE_TAG_END,
'openbrace': SINGLE_BRACE_START,
'closebrace': SINGLE_BRACE_END,
'opencomment': COMMENT_TAG_START,
'closecomment': COMMENT_TAG_END,
}
def __init__(self, tagtype):
self.tagtype = tagtype
def render(self, context):
return self.mapping.get(self.tagtype, '')
class URLNode(Node):
def __init__(self, view_name, args, kwargs, asvar):
self.view_name = view_name
self.args = args
self.kwargs = kwargs
self.asvar = asvar
def render(self, context):
from django.core.urlresolvers import reverse, NoReverseMatch
args = [arg.resolve(context) for arg in self.args]
kwargs = {
smart_text(k, 'ascii'): v.resolve(context)
for k, v in self.kwargs.items()
}
view_name = self.view_name.resolve(context)
try:
current_app = context.request.current_app
except AttributeError:
# Change the fallback value to None when the deprecation path for
# Context.current_app completes in Django 1.10.
current_app = context.current_app
# Try to look up the URL twice: once given the view name, and again
# relative to what we guess is the "main" app. If they both fail,
# re-raise the NoReverseMatch unless we're using the
# {% url ... as var %} construct in which case return nothing.
url = ''
try:
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
except NoReverseMatch:
exc_info = sys.exc_info()
if settings.SETTINGS_MODULE:
project_name = settings.SETTINGS_MODULE.split('.')[0]
try:
url = reverse(project_name + '.' + view_name,
args=args, kwargs=kwargs,
current_app=current_app)
except NoReverseMatch:
if self.asvar is None:
# Re-raise the original exception, not the one with
# the path relative to the project. This makes a
# better error message.
six.reraise(*exc_info)
else:
if self.asvar is None:
raise
if self.asvar:
context[self.asvar] = url
return ''
else:
if context.autoescape:
url = conditional_escape(url)
return url
class VerbatimNode(Node):
def __init__(self, content):
self.content = content
def render(self, context):
return self.content
class WidthRatioNode(Node):
def __init__(self, val_expr, max_expr, max_width, asvar=None):
self.val_expr = val_expr
self.max_expr = max_expr
self.max_width = max_width
self.asvar = asvar
def render(self, context):
try:
value = self.val_expr.resolve(context)
max_value = self.max_expr.resolve(context)
max_width = int(self.max_width.resolve(context))
except VariableDoesNotExist:
return ''
except (ValueError, TypeError):
raise TemplateSyntaxError("widthratio final argument must be a number")
try:
value = float(value)
max_value = float(max_value)
ratio = (value / max_value) * max_width
result = str(int(round(ratio)))
except ZeroDivisionError:
return '0'
except (ValueError, TypeError, OverflowError):
return ''
if self.asvar:
context[self.asvar] = result
return ''
else:
return result
class WithNode(Node):
def __init__(self, var, name, nodelist, extra_context=None):
self.nodelist = nodelist
# var and name are legacy attributes, being left in case they are used
# by third-party subclasses of this Node.
self.extra_context = extra_context or {}
if name:
self.extra_context[name] = var
def __repr__(self):
return "<WithNode>"
def render(self, context):
values = {key: val.resolve(context) for key, val in
six.iteritems(self.extra_context)}
with context.push(**values):
return self.nodelist.render(context)
@register.tag
def autoescape(parser, token):
"""
Force autoescape behavior for this block.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
if len(args) != 2:
raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.")
arg = args[1]
if arg not in ('on', 'off'):
raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'")
nodelist = parser.parse(('endautoescape',))
parser.delete_first_token()
return AutoEscapeControlNode((arg == 'on'), nodelist)
@register.tag
def comment(parser, token):
"""
Ignores everything between ``{% comment %}`` and ``{% endcomment %}``.
"""
parser.skip_past('endcomment')
return CommentNode()
@register.tag
def cycle(parser, token):
"""
Cycles among the given strings each time this tag is encountered.
Within a loop, cycles among the given strings each time through
the loop::
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
Outside of a loop, give the values a unique name the first time you call
it, then use that name each successive time through::
<tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr>
<tr class="{% cycle rowcolors %}">...</tr>
<tr class="{% cycle rowcolors %}">...</tr>
You can use any number of values, separated by spaces. Commas can also
be used to separate values; if a comma is used, the cycle values are
interpreted as literal strings.
The optional flag "silent" can be used to prevent the cycle declaration
from returning any value::
{% for o in some_list %}
{% cycle 'row1' 'row2' as rowcolors silent %}
<tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr>
{% endfor %}
"""
# Note: This returns the exact same node on each {% cycle name %} call;
# that is, the node object returned from {% cycle a b c as name %} and the
# one returned from {% cycle name %} are the exact same object. This
# shouldn't cause problems (heh), but if it does, now you know.
#
# Ugly hack warning: This stuffs the named template dict into parser so
# that names are only unique within each template (as opposed to using
# a global variable, which would make cycle names have to be unique across
# *all* templates.
args = token.split_contents()
if len(args) < 2:
raise TemplateSyntaxError("'cycle' tag requires at least two arguments")
if ',' in args[1]:
warnings.warn(
"The old {% cycle %} syntax with comma-separated arguments is deprecated.",
RemovedInDjango110Warning,
)
# Backwards compatibility: {% cycle a,b %} or {% cycle a,b as foo %}
# case.
args[1:2] = ['"%s"' % arg for arg in args[1].split(",")]
if len(args) == 2:
# {% cycle foo %} case.
name = args[1]
if not hasattr(parser, '_namedCycleNodes'):
raise TemplateSyntaxError("No named cycles in template. '%s' is not defined" % name)
if name not in parser._namedCycleNodes:
raise TemplateSyntaxError("Named cycle '%s' does not exist" % name)
return parser._namedCycleNodes[name]
as_form = False
if len(args) > 4:
# {% cycle ... as foo [silent] %} case.
if args[-3] == "as":
if args[-1] != "silent":
raise TemplateSyntaxError("Only 'silent' flag is allowed after cycle's name, not '%s'." % args[-1])
as_form = True
silent = True
args = args[:-1]
elif args[-2] == "as":
as_form = True
silent = False
if as_form:
name = args[-1]
values = [parser.compile_filter(arg) for arg in args[1:-2]]
node = CycleNode(values, name, silent=silent)
if not hasattr(parser, '_namedCycleNodes'):
parser._namedCycleNodes = {}
parser._namedCycleNodes[name] = node
else:
values = [parser.compile_filter(arg) for arg in args[1:]]
node = CycleNode(values)
return node
@register.tag
def csrf_token(parser, token):
return CsrfTokenNode()
@register.tag
def debug(parser, token):
"""
Outputs a whole load of debugging information, including the current
context and imported modules.
Sample usage::
<pre>
{% debug %}
</pre>
"""
return DebugNode()
@register.tag('filter')
def do_filter(parser, token):
"""
Filters the contents of the block through variable filters.
Filters can also be piped through each other, and they can have
arguments -- just like in variable syntax.
Sample usage::
{% filter force_escape|lower %}
This text will be HTML-escaped, and will appear in lowercase.
{% endfilter %}
Note that the ``escape`` and ``safe`` filters are not acceptable arguments.
Instead, use the ``autoescape`` tag to manage autoescaping for blocks of
template code.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
_, rest = token.contents.split(None, 1)
filter_expr = parser.compile_filter("var|%s" % (rest))
for func, unused in filter_expr.filters:
filter_name = getattr(func, '_filter_name', None)
if filter_name in ('escape', 'safe'):
raise TemplateSyntaxError('"filter %s" is not permitted. Use the "autoescape" tag instead.' % filter_name)
nodelist = parser.parse(('endfilter',))
parser.delete_first_token()
return FilterNode(filter_expr, nodelist)
@register.tag
def firstof(parser, token):
"""
Outputs the first variable passed that is not False, without escaping.
Outputs nothing if all the passed variables are False.
Sample usage::
{% firstof var1 var2 var3 as myvar %}
This is equivalent to::
{% if var1 %}
{{ var1|safe }}
{% elif var2 %}
{{ var2|safe }}
{% elif var3 %}
{{ var3|safe }}
{% endif %}
but obviously much cleaner!
You can also use a literal string as a fallback value in case all
passed variables are False::
{% firstof var1 var2 var3 "fallback value" %}
If you want to disable auto-escaping of variables you can use::
{% autoescape off %}
{% firstof var1 var2 var3 "<strong>fallback value</strong>" %}
{% autoescape %}
Or if only some variables should be escaped, you can use::
{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %}
"""
bits = token.split_contents()[1:]
asvar = None
if len(bits) < 1:
raise TemplateSyntaxError("'firstof' statement requires at least one argument")
if len(bits) >= 2 and bits[-2] == 'as':
asvar = bits[-1]
bits = bits[:-2]
return FirstOfNode([parser.compile_filter(bit) for bit in bits], asvar)
@register.tag('for')
def do_for(parser, token):
"""
Loops over each item in an array.
For example, to display a list of athletes given ``athlete_list``::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
You can loop over a list in reverse by using
``{% for obj in list reversed %}``.
You can also unpack multiple values from a two-dimensional array::
{% for key,value in dict.items %}
{{ key }}: {{ value }}
{% endfor %}
The ``for`` tag can take an optional ``{% empty %}`` clause that will
be displayed if the given array is empty or could not be found::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>Sorry, no athletes in this list.</li>
{% endfor %}
<ul>
The above is equivalent to -- but shorter, cleaner, and possibly faster
than -- the following::
<ul>
{% if althete_list %}
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
{% else %}
<li>Sorry, no athletes in this list.</li>
{% endif %}
</ul>
The for loop sets a number of variables available within the loop:
========================== ================================================
Variable Description
========================== ================================================
``forloop.counter`` The current iteration of the loop (1-indexed)
``forloop.counter0`` The current iteration of the loop (0-indexed)
``forloop.revcounter`` The number of iterations from the end of the
loop (1-indexed)
``forloop.revcounter0`` The number of iterations from the end of the
loop (0-indexed)
``forloop.first`` True if this is the first time through the loop
``forloop.last`` True if this is the last time through the loop
``forloop.parentloop`` For nested loops, this is the loop "above" the
current one
========================== ================================================
"""
bits = token.split_contents()
if len(bits) < 4:
raise TemplateSyntaxError("'for' statements should have at least four"
" words: %s" % token.contents)
is_reversed = bits[-1] == 'reversed'
in_index = -3 if is_reversed else -2
if bits[in_index] != 'in':
raise TemplateSyntaxError("'for' statements should use the format"
" 'for x in y': %s" % token.contents)
loopvars = re.split(r' *, *', ' '.join(bits[1:in_index]))
for var in loopvars:
if not var or ' ' in var:
raise TemplateSyntaxError("'for' tag received an invalid argument:"
" %s" % token.contents)
sequence = parser.compile_filter(bits[in_index + 1])
nodelist_loop = parser.parse(('empty', 'endfor',))
token = parser.next_token()
if token.contents == 'empty':
nodelist_empty = parser.parse(('endfor',))
parser.delete_first_token()
else:
nodelist_empty = None
return ForNode(loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty)
def do_ifequal(parser, token, negate):
bits = list(token.split_contents())
if len(bits) != 3:
raise TemplateSyntaxError("%r takes two arguments" % bits[0])
end_tag = 'end' + bits[0]
nodelist_true = parser.parse(('else', end_tag))
token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse((end_tag,))
parser.delete_first_token()
else:
nodelist_false = NodeList()
val1 = parser.compile_filter(bits[1])
val2 = parser.compile_filter(bits[2])
return IfEqualNode(val1, val2, nodelist_true, nodelist_false, negate)
@register.tag
def ifequal(parser, token):
"""
Outputs the contents of the block if the two arguments equal each other.
Examples::
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
{% ifnotequal user.id comment.user_id %}
...
{% else %}
...
{% endifnotequal %}
"""
return do_ifequal(parser, token, False)
@register.tag
def ifnotequal(parser, token):
"""
Outputs the contents of the block if the two arguments are not equal.
See ifequal.
"""
return do_ifequal(parser, token, True)
class TemplateLiteral(Literal):
def __init__(self, value, text):
self.value = value
self.text = text # for better error messages
def display(self):
return self.text
def eval(self, context):
return self.value.resolve(context, ignore_failures=True)
class TemplateIfParser(IfParser):
error_class = TemplateSyntaxError
def __init__(self, parser, *args, **kwargs):
self.template_parser = parser
super(TemplateIfParser, self).__init__(*args, **kwargs)
def create_var(self, value):
return TemplateLiteral(self.template_parser.compile_filter(value), value)
@register.tag('if')
def do_if(parser, token):
"""
The ``{% if %}`` tag evaluates a variable, and if that variable is "true"
(i.e., exists, is not empty, and is not a false boolean value), the
contents of the block are output:
::
{% if athlete_list %}
Number of athletes: {{ athlete_list|count }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
In the above, if ``athlete_list`` is not empty, the number of athletes will
be displayed by the ``{{ athlete_list|count }}`` variable.
As you can see, the ``if`` tag may take one or several `` {% elif %}``
clauses, as well as an ``{% else %}`` clause that will be displayed if all
previous conditions fail. These clauses are optional.
``if`` tags may use ``or``, ``and`` or ``not`` to test a number of
variables or to negate a given variable::
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes, or there are some coaches.
{% endif %}
{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}
Comparison operators are also available, and the use of filters is also
allowed, for example::
{% if articles|length >= 5 %}...{% endif %}
Arguments and operators _must_ have a space between them, so
``{% if 1>2 %}`` is not a valid if tag.
All supported operators are: ``or``, ``and``, ``in``, ``not in``
``==``, ``!=``, ``>``, ``>=``, ``<`` and ``<=``.
Operator precedence follows Python.
"""
# {% if ... %}
bits = token.split_contents()[1:]
condition = TemplateIfParser(parser, bits).parse()
nodelist = parser.parse(('elif', 'else', 'endif'))
conditions_nodelists = [(condition, nodelist)]
token = parser.next_token()
# {% elif ... %} (repeatable)
while token.contents.startswith('elif'):
bits = token.split_contents()[1:]
condition = TemplateIfParser(parser, bits).parse()
nodelist = parser.parse(('elif', 'else', 'endif'))
conditions_nodelists.append((condition, nodelist))
token = parser.next_token()
# {% else %} (optional)
if token.contents == 'else':
nodelist = parser.parse(('endif',))
conditions_nodelists.append((None, nodelist))
token = parser.next_token()
# {% endif %}
assert token.contents == 'endif'
return IfNode(conditions_nodelists)
@register.tag
def ifchanged(parser, token):
"""
Checks if a value has changed from the last iteration of a loop.
The ``{% ifchanged %}`` block tag is used within a loop. It has two
possible uses.
1. Checks its own rendered contents against its previous state and only
displays the content if it has changed. For example, this displays a
list of days, only displaying the month if it changes::
<h1>Archive for {{ year }}</h1>
{% for date in days %}
{% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
<a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
{% endfor %}
2. If given one or more variables, check whether any variable has changed.
For example, the following shows the date every time it changes, while
showing the hour if either the hour or the date has changed::
{% for date in days %}
{% ifchanged date.date %} {{ date.date }} {% endifchanged %}
{% ifchanged date.hour date.date %}
{{ date.hour }}
{% endifchanged %}
{% endfor %}
"""
bits = token.split_contents()
nodelist_true = parser.parse(('else', 'endifchanged'))
token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse(('endifchanged',))
parser.delete_first_token()
else:
nodelist_false = NodeList()
values = [parser.compile_filter(bit) for bit in bits[1:]]
return IfChangedNode(nodelist_true, nodelist_false, *values)
@register.tag
def ssi(parser, token):
"""
Outputs the contents of a given file into the page.
Like a simple "include" tag, the ``ssi`` tag includes the contents
of another file -- which must be specified using an absolute path --
in the current page::
{% ssi "/home/html/ljworld.com/includes/right_generic.html" %}
If the optional "parsed" parameter is given, the contents of the included
file are evaluated as template code, with the current context::
{% ssi "/home/html/ljworld.com/includes/right_generic.html" parsed %}
"""
warnings.warn(
"The {% ssi %} tag is deprecated. Use the {% include %} tag instead.",
RemovedInDjango110Warning,
)
bits = token.split_contents()
parsed = False
if len(bits) not in (2, 3):
raise TemplateSyntaxError("'ssi' tag takes one argument: the path to"
" the file to be included")
if len(bits) == 3:
if bits[2] == 'parsed':
parsed = True
else:
raise TemplateSyntaxError("Second (optional) argument to %s tag"
" must be 'parsed'" % bits[0])
filepath = parser.compile_filter(bits[1])
return SsiNode(filepath, parsed)
def find_library(parser, name):
try:
return parser.libraries[name]
except KeyError:
raise TemplateSyntaxError(
"'%s' is not a registered tag library. Must be one of:\n%s" % (
name, "\n".join(sorted(parser.libraries.keys())),
),
)
def load_from_library(library, label, names):
"""
Return a subset of tags and filters from a library.
"""
subset = Library()
for name in names:
found = False
if name in library.tags:
found = True
subset.tags[name] = library.tags[name]
if name in library.filters:
found = True
subset.filters[name] = library.filters[name]
if found is False:
raise TemplateSyntaxError(
"'%s' is not a valid tag or filter in tag library '%s'" % (
name, label,
),
)
return subset
@register.tag
def load(parser, token):
"""
Loads a custom template tag library into the parser.
For example, to load the template tags in
``django/templatetags/news/photos.py``::
{% load news.photos %}
Can also be used to load an individual tag/filter from
a library::
{% load byline from news %}
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
bits = token.contents.split()
if len(bits) >= 4 and bits[-2] == "from":
# from syntax is used; load individual tags from the library
name = bits[-1]
lib = find_library(parser, name)
subset = load_from_library(lib, name, bits[1:-2])
parser.add_library(subset)
else:
# one or more libraries are specified; load and add them to the parser
for name in bits[1:]:
lib = find_library(parser, name)
parser.add_library(lib)
return LoadNode()
@register.tag
def lorem(parser, token):
"""
Creates random Latin text useful for providing test data in templates.
Usage format::
{% lorem [count] [method] [random] %}
``count`` is a number (or variable) containing the number of paragraphs or
words to generate (default is 1).
``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for
plain-text paragraph blocks (default is ``b``).
``random`` is the word ``random``, which if given, does not use the common
paragraph (starting "Lorem ipsum dolor sit amet, consectetuer...").
Examples:
* ``{% lorem %}`` will output the common "lorem ipsum" paragraph
* ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
and two random paragraphs each wrapped in HTML ``<p>`` tags
* ``{% lorem 2 w random %}`` will output two random latin words
"""
bits = list(token.split_contents())
tagname = bits[0]
# Random bit
common = bits[-1] != 'random'
if not common:
bits.pop()
# Method bit
if bits[-1] in ('w', 'p', 'b'):
method = bits.pop()
else:
method = 'b'
# Count bit
if len(bits) > 1:
count = bits.pop()
else:
count = '1'
count = parser.compile_filter(count)
if len(bits) != 1:
raise TemplateSyntaxError("Incorrect format for %r tag" % tagname)
return LoremNode(count, method, common)
@register.tag
def now(parser, token):
"""
Displays the date, formatted according to the given string.
Uses the same format as PHP's ``date()`` function; see http://php.net/date
for all the possible values.
Sample usage::
It is {% now "jS F Y H:i" %}
"""
bits = token.split_contents()
asvar = None
if len(bits) == 4 and bits[-2] == 'as':
asvar = bits[-1]
bits = bits[:-2]
if len(bits) != 2:
raise TemplateSyntaxError("'now' statement takes one argument")
format_string = bits[1][1:-1]
return NowNode(format_string, asvar)
@register.tag
def regroup(parser, token):
"""
Regroups a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that
``people`` is a list of ``Person`` objects that have ``first_name``,
``last_name``, and ``gender`` attributes, and you'd like to display a list
that looks like:
* Male:
* George Bush
* Bill Clinton
* Female:
* Margaret Thatcher
* Colendeeza Rice
* Unknown:
* Pat Smith
The following snippet of template code would accomplish this dubious task::
{% regroup people by gender as grouped %}
<ul>
{% for group in grouped %}
<li>{{ group.grouper }}
<ul>
{% for item in group.list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
As you can see, ``{% regroup %}`` populates a variable with a list of
objects with ``grouper`` and ``list`` attributes. ``grouper`` contains the
item that was grouped by; ``list`` contains the list of objects that share
that ``grouper``. In this case, ``grouper`` would be ``Male``, ``Female``
and ``Unknown``, and ``list`` is the list of people with those genders.
Note that ``{% regroup %}`` does not work when the list to be grouped is not
sorted by the key you are grouping by! This means that if your list of
people was not sorted by gender, you'd need to make sure it is sorted
before using it, i.e.::
{% regroup people|dictsort:"gender" by gender as grouped %}
"""
bits = token.split_contents()
if len(bits) != 6:
raise TemplateSyntaxError("'regroup' tag takes five arguments")
target = parser.compile_filter(bits[1])
if bits[2] != 'by':
raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'")
if bits[4] != 'as':
raise TemplateSyntaxError("next-to-last argument to 'regroup' tag must"
" be 'as'")
var_name = bits[5]
# RegroupNode will take each item in 'target', put it in the context under
# 'var_name', evaluate 'var_name'.'expression' in the current context, and
# group by the resulting value. After all items are processed, it will
# save the final result in the context under 'var_name', thus clearing the
# temporary values. This hack is necessary because the template engine
# doesn't provide a context-aware equivalent of Python's getattr.
expression = parser.compile_filter(var_name +
VARIABLE_ATTRIBUTE_SEPARATOR +
bits[3])
return RegroupNode(target, expression, var_name)
@register.tag
def spaceless(parser, token):
"""
Removes whitespace between HTML tags, including tab and newline characters.
Example usage::
{% spaceless %}
<p>
<a href="foo/">Foo</a>
</p>
{% endspaceless %}
This example would return this HTML::
<p><a href="foo/">Foo</a></p>
Only space between *tags* is normalized -- not space between tags and text.
In this example, the space around ``Hello`` won't be stripped::
{% spaceless %}
<strong>
Hello
</strong>
{% endspaceless %}
"""
nodelist = parser.parse(('endspaceless',))
parser.delete_first_token()
return SpacelessNode(nodelist)
@register.tag
def templatetag(parser, token):
"""
Outputs one of the bits used to compose template tags.
Since the template system has no concept of "escaping", to display one of
the bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
================== =======
Argument Outputs
================== =======
``openblock`` ``{%``
``closeblock`` ``%}``
``openvariable`` ``{{``
``closevariable`` ``}}``
``openbrace`` ``{``
``closebrace`` ``}``
``opencomment`` ``{#``
``closecomment`` ``#}``
================== =======
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
bits = token.contents.split()
if len(bits) != 2:
raise TemplateSyntaxError("'templatetag' statement takes one argument")
tag = bits[1]
if tag not in TemplateTagNode.mapping:
raise TemplateSyntaxError("Invalid templatetag argument: '%s'."
" Must be one of: %s" %
(tag, list(TemplateTagNode.mapping)))
return TemplateTagNode(tag)
@register.tag
def url(parser, token):
"""
Returns an absolute URL matching given view with its parameters.
This is a way to define links that aren't tied to a particular URL
configuration::
{% url "path.to.some_view" arg1 arg2 %}
or
{% url "path.to.some_view" name1=value1 name2=value2 %}
The first argument is a path to a view. It can be an absolute Python path
or just ``app_name.view_name`` without the project name if the view is
located inside the project.
Other arguments are space-separated values that will be filled in place of
positional and keyword arguments in the URL. Don't mix positional and
keyword arguments.
All arguments for the URL should be present.
For example if you have a view ``app_name.client`` taking client's id and
the corresponding line in a URLconf looks like this::
('^client/(\d+)/$', 'app_name.client')
and this app's URLconf is included into the project's URLconf under some
path::
('^clients/', include('project_name.app_name.urls'))
then in a template you can create a link for a certain client like this::
{% url "app_name.client" client.id %}
The URL will look like ``/clients/client/123/``.
The first argument can also be a named URL instead of the Python path to
the view callable. For example if the URLconf entry looks like this::
url('^client/(\d+)/$', name='client-detail-view')
then in the template you can use::
{% url "client-detail-view" client.id %}
There is even another possible value type for the first argument. It can be
the name of a template variable that will be evaluated to obtain the view
name or the URL name, e.g.::
{% with view_path="app_name.client" %}
{% url view_path client.id %}
{% endwith %}
or,
{% with url_name="client-detail-view" %}
{% url url_name client.id %}
{% endwith %}
"""
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes at least one argument"
" (path to a view)" % bits[0])
viewname = parser.compile_filter(bits[1])
args = []
kwargs = {}
asvar = None
bits = bits[2:]
if len(bits) >= 2 and bits[-2] == 'as':
asvar = bits[-1]
bits = bits[:-2]
if len(bits):
for bit in bits:
match = kwarg_re.match(bit)
if not match:
raise TemplateSyntaxError("Malformed arguments to url tag")
name, value = match.groups()
if name:
kwargs[name] = parser.compile_filter(value)
else:
args.append(parser.compile_filter(value))
return URLNode(viewname, args, kwargs, asvar)
@register.tag
def verbatim(parser, token):
"""
Stops the template engine from rendering the contents of this block tag.
Usage::
{% verbatim %}
{% don't process this %}
{% endverbatim %}
You can also designate a specific closing tag block (allowing the
unrendered use of ``{% endverbatim %}``)::
{% verbatim myblock %}
...
{% endverbatim myblock %}
"""
nodelist = parser.parse(('endverbatim',))
parser.delete_first_token()
return VerbatimNode(nodelist.render(Context()))
@register.tag
def widthratio(parser, token):
"""
For creating bar charts and such, this tag calculates the ratio of a given
value to a maximum value, and then applies that ratio to a constant.
For example::
<img src="bar.png" alt="Bar"
height="10" width="{% widthratio this_value max_value max_width %}" />
If ``this_value`` is 175, ``max_value`` is 200, and ``max_width`` is 100,
the image in the above example will be 88 pixels wide
(because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).
In some cases you might want to capture the result of widthratio in a
variable. It can be useful for instance in a blocktrans like this::
{% widthratio this_value max_value max_width as width %}
{% blocktrans %}The width is: {{ width }}{% endblocktrans %}
"""
bits = token.split_contents()
if len(bits) == 4:
tag, this_value_expr, max_value_expr, max_width = bits
asvar = None
elif len(bits) == 6:
tag, this_value_expr, max_value_expr, max_width, as_, asvar = bits
if as_ != 'as':
raise TemplateSyntaxError("Invalid syntax in widthratio tag. Expecting 'as' keyword")
else:
raise TemplateSyntaxError("widthratio takes at least three arguments")
return WidthRatioNode(parser.compile_filter(this_value_expr),
parser.compile_filter(max_value_expr),
parser.compile_filter(max_width),
asvar=asvar)
@register.tag('with')
def do_with(parser, token):
"""
Adds one or more values to the context (inside of this block) for caching
and easy access.
For example::
{% with total=person.some_sql_method %}
{{ total }} object{{ total|pluralize }}
{% endwith %}
Multiple values can be added to the context::
{% with foo=1 bar=2 %}
...
{% endwith %}
The legacy format of ``{% with person.some_sql_method as total %}`` is
still accepted.
"""
bits = token.split_contents()
remaining_bits = bits[1:]
extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)
if not extra_context:
raise TemplateSyntaxError("%r expected at least one variable "
"assignment" % bits[0])
if remaining_bits:
raise TemplateSyntaxError("%r received an invalid token: %r" %
(bits[0], remaining_bits[0]))
nodelist = parser.parse(('endwith',))
parser.delete_first_token()
return WithNode(None, None, nodelist, extra_context=extra_context)
| bsd-3-clause |
Innovahn/odoo.old | addons/payment_ogone/tests/test_ogone.py | 430 | 9309 | # -*- coding: utf-8 -*-
from lxml import objectify
import time
import urlparse
from openerp.addons.payment.models.payment_acquirer import ValidationError
from openerp.addons.payment.tests.common import PaymentAcquirerCommon
from openerp.addons.payment_ogone.controllers.main import OgoneController
from openerp.tools import mute_logger
class OgonePayment(PaymentAcquirerCommon):
def setUp(self):
super(OgonePayment, self).setUp()
cr, uid = self.cr, self.uid
self.base_url = self.registry('ir.config_parameter').get_param(cr, uid, 'web.base.url')
# get the adyen account
model, self.ogone_id = self.registry('ir.model.data').get_object_reference(cr, uid, 'payment_ogone', 'payment_acquirer_ogone')
def test_10_ogone_form_render(self):
cr, uid, context = self.cr, self.uid, {}
# be sure not to do stupid thing
ogone = self.payment_acquirer.browse(self.cr, self.uid, self.ogone_id, None)
self.assertEqual(ogone.environment, 'test', 'test without test environment')
# ----------------------------------------
# Test: button direct rendering + shasign
# ----------------------------------------
form_values = {
'PSPID': 'dummy',
'ORDERID': 'test_ref0',
'AMOUNT': '1',
'CURRENCY': 'EUR',
'LANGUAGE': 'en_US',
'CN': 'Norbert Buyer',
'EMAIL': 'norbert.buyer@example.com',
'OWNERZIP': '1000',
'OWNERADDRESS': 'Huge Street 2/543',
'OWNERCTY': 'Belgium',
'OWNERTOWN': 'Sin City',
'OWNERTELNO': '0032 12 34 56 78',
'SHASIGN': '815f67b8ff70d234ffcf437c13a9fa7f807044cc',
'ACCEPTURL': '%s' % urlparse.urljoin(self.base_url, OgoneController._accept_url),
'DECLINEURL': '%s' % urlparse.urljoin(self.base_url, OgoneController._decline_url),
'EXCEPTIONURL': '%s' % urlparse.urljoin(self.base_url, OgoneController._exception_url),
'CANCELURL': '%s' % urlparse.urljoin(self.base_url, OgoneController._cancel_url),
}
# render the button
res = self.payment_acquirer.render(
cr, uid, self.ogone_id,
'test_ref0', 0.01, self.currency_euro_id,
partner_id=None,
partner_values=self.buyer_values,
context=context)
# check form result
tree = objectify.fromstring(res)
self.assertEqual(tree.get('action'), 'https://secure.ogone.com/ncol/test/orderstandard.asp', 'ogone: wrong form POST url')
for form_input in tree.input:
if form_input.get('name') in ['submit']:
continue
self.assertEqual(
form_input.get('value'),
form_values[form_input.get('name')],
'ogone: wrong value for input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')])
)
# ----------------------------------------
# Test2: button using tx + validation
# ----------------------------------------
# create a new draft tx
tx_id = self.payment_transaction.create(
cr, uid, {
'amount': 0.01,
'acquirer_id': self.ogone_id,
'currency_id': self.currency_euro_id,
'reference': 'test_ref0',
'partner_id': self.buyer_id,
}, context=context
)
# render the button
res = self.payment_acquirer.render(
cr, uid, self.ogone_id,
'should_be_erased', 0.01, self.currency_euro,
tx_id=tx_id,
partner_id=None,
partner_values=self.buyer_values,
context=context)
# check form result
tree = objectify.fromstring(res)
self.assertEqual(tree.get('action'), 'https://secure.ogone.com/ncol/test/orderstandard.asp', 'ogone: wrong form POST url')
for form_input in tree.input:
if form_input.get('name') in ['submit']:
continue
self.assertEqual(
form_input.get('value'),
form_values[form_input.get('name')],
'ogone: wrong value for form input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')])
)
@mute_logger('openerp.addons.payment_ogone.models.ogone', 'ValidationError')
def test_20_ogone_form_management(self):
cr, uid, context = self.cr, self.uid, {}
# be sure not to do stupid thing
ogone = self.payment_acquirer.browse(self.cr, self.uid, self.ogone_id, None)
self.assertEqual(ogone.environment, 'test', 'test without test environment')
# typical data posted by ogone after client has successfully paid
ogone_post_data = {
'orderID': u'test_ref_2',
'STATUS': u'9',
'CARDNO': u'XXXXXXXXXXXX0002',
'PAYID': u'25381582',
'CN': u'Norbert Buyer',
'NCERROR': u'0',
'TRXDATE': u'11/15/13',
'IP': u'85.201.233.72',
'BRAND': u'VISA',
'ACCEPTANCE': u'test123',
'currency': u'EUR',
'amount': u'1.95',
'SHASIGN': u'7B7B0ED9CBC4A85543A9073374589033A62A05A5',
'ED': u'0315',
'PM': u'CreditCard'
}
# should raise error about unknown tx
with self.assertRaises(ValidationError):
self.payment_transaction.ogone_form_feedback(cr, uid, ogone_post_data, context=context)
# create tx
tx_id = self.payment_transaction.create(
cr, uid, {
'amount': 1.95,
'acquirer_id': self.ogone_id,
'currency_id': self.currency_euro_id,
'reference': 'test_ref_2',
'partner_name': 'Norbert Buyer',
'partner_country_id': self.country_france_id,
}, context=context
)
# validate it
self.payment_transaction.ogone_form_feedback(cr, uid, ogone_post_data, context=context)
# check state
tx = self.payment_transaction.browse(cr, uid, tx_id, context=context)
self.assertEqual(tx.state, 'done', 'ogone: validation did not put tx into done state')
self.assertEqual(tx.ogone_payid, ogone_post_data.get('PAYID'), 'ogone: validation did not update tx payid')
# reset tx
tx.write({'state': 'draft', 'date_validate': False, 'ogone_payid': False})
# now ogone post is ok: try to modify the SHASIGN
ogone_post_data['SHASIGN'] = 'a4c16bae286317b82edb49188d3399249a784691'
with self.assertRaises(ValidationError):
self.payment_transaction.ogone_form_feedback(cr, uid, ogone_post_data, context=context)
# simulate an error
ogone_post_data['STATUS'] = 2
ogone_post_data['SHASIGN'] = 'a4c16bae286317b82edb49188d3399249a784691'
self.payment_transaction.ogone_form_feedback(cr, uid, ogone_post_data, context=context)
# check state
tx = self.payment_transaction.browse(cr, uid, tx_id, context=context)
self.assertEqual(tx.state, 'error', 'ogone: erroneous validation did not put tx into error state')
def test_30_ogone_s2s(self):
test_ref = 'test_ref_%.15f' % time.time()
cr, uid, context = self.cr, self.uid, {}
# be sure not to do stupid thing
ogone = self.payment_acquirer.browse(self.cr, self.uid, self.ogone_id, None)
self.assertEqual(ogone.environment, 'test', 'test without test environment')
# create a new draft tx
tx_id = self.payment_transaction.create(
cr, uid, {
'amount': 0.01,
'acquirer_id': self.ogone_id,
'currency_id': self.currency_euro_id,
'reference': test_ref,
'partner_id': self.buyer_id,
'type': 'server2server',
}, context=context
)
# create an alias
res = self.payment_transaction.ogone_s2s_create_alias(
cr, uid, tx_id, {
'expiry_date_mm': '01',
'expiry_date_yy': '2015',
'holder_name': 'Norbert Poilu',
'number': '4000000000000002',
'brand': 'VISA',
}, context=context)
# check an alias is set, containing at least OPENERP
tx = self.payment_transaction.browse(cr, uid, tx_id, context=context)
self.assertIn('OPENERP', tx.partner_reference, 'ogone: wrong partner reference after creating an alias')
res = self.payment_transaction.ogone_s2s_execute(cr, uid, tx_id, {}, context=context)
# print res
# {
# 'orderID': u'reference',
# 'STATUS': u'9',
# 'CARDNO': u'XXXXXXXXXXXX0002',
# 'PAYID': u'24998692',
# 'CN': u'Norbert Poilu',
# 'NCERROR': u'0',
# 'TRXDATE': u'11/05/13',
# 'IP': u'85.201.233.72',
# 'BRAND': u'VISA',
# 'ACCEPTANCE': u'test123',
# 'currency': u'EUR',
# 'amount': u'1.95',
# 'SHASIGN': u'EFDC56879EF7DE72CCF4B397076B5C9A844CB0FA',
# 'ED': u'0314',
# 'PM': u'CreditCard'
# }
| agpl-3.0 |
scowcron/ImagesOfNetwork | images_of/entrypoints/audit_mods.py | 1 | 1450 | import click
from images_of import command, settings, Reddit
@command
@click.option('--print-mods', is_flag=True, help='List the non-default moderators for all subreddits')
def main(print_mods):
"""Find subs without mods and disenfranchised mods"""
mods = settings.DEFAULT_MODS
r = Reddit('Moderator Auditor v0.1')
r.oauth()
subs = sorted([sub['name'] for sub in settings.CHILD_SUBS])
empty_subs = list()
orphan_mods = dict()
s = r.get_subreddit(settings.PARENT_SUB)
main_sub_mods = [u.name for u in s.get_moderators()]
for sub in subs:
s = r.get_subreddit(sub)
cur_mods = [u.name for u in s.get_moderators()]
real_mods = [m for m in cur_mods if m not in mods]
if not real_mods:
empty_subs.append(sub)
else:
if print_mods:
print('{} : {}'.format(sub, real_mods))
for m in [i for i in real_mods if i not in main_sub_mods]:
orphan_mods[m] = orphan_mods.get(m, []) + [sub]
print()
print('Unmoderated Subreddits: {}'.format(len(empty_subs)))
print('-----------------------')
for sub in sorted(empty_subs):
print(sub)
print()
print('Orphaned Moderators: {}'.format(len(orphan_mods)))
print('-------------------------')
for m, s in orphan_mods.items():
print('{} : {}'.format(m, s))
if __name__ == '__main__':
main()
| mit |
zhangpf/vbox | src/VBox/ValidationKit/common/constants/result.py | 4 | 1355 | # -*- coding: utf-8 -*-
# $Id$
"""
Test statuses.
"""
__copyright__ = \
"""
Copyright (C) 2012-2014 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
The contents of this file may alternatively be used under the terms
of the Common Development and Distribution License Version 1.0
(CDDL) only, as it comes in the "COPYING.CDDL" file of the
VirtualBox OSE distribution, in which case the provisions of the
CDDL are applicable instead of those of the GPL.
You may elect to license modified versions of this file under the
terms and conditions of either the GPL or the CDDL or both.
"""
__version__ = "$Revision$"
PASSED = 'PASSED';
SKIPPED = 'SKIPPED';
ABORTED = 'ABORTED';
BAD_TESTBOX = 'BAD_TESTBOX';
FAILED = 'FAILED';
TIMED_OUT = 'TIMED_OUT';
REBOOTED = 'REBOOTED';
## List of valid result valies.
g_kasValidResults = [ PASSED, SKIPPED, ABORTED, BAD_TESTBOX, FAILED, TIMED_OUT, REBOOTED, ];
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.