repo_name
stringlengths 5
92
| path
stringlengths 4
232
| copies
stringclasses 19
values | size
stringlengths 4
7
| content
stringlengths 721
1.04M
| license
stringclasses 15
values | hash
int64 -9,223,277,421,539,062,000
9,223,102,107B
| line_mean
float64 6.51
99.9
| line_max
int64 15
997
| alpha_frac
float64 0.25
0.97
| autogenerated
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|
bkad/python-stylus | stylus/__init__.py | 1 | 2479 | #!/usr/bin/env python
import os
from os import path
import execjs
import io
node_modules = path.abspath("node_modules")
if "NODE_PATH" not in os.environ:
os.environ["NODE_PATH"] = node_modules
elif node_modules not in os.environ["NODE_PATH"]:
os.pathsep.join((os.environ["NODE_PATH"], node_modules))
class Stylus(object):
def __init__(self, compress=False, paths=[], imports=[], plugins={}):
"""
compress: Whether the resulting css should be compressed.
paths: List of stylesheet load paths.
imports: Stylesheets to import on every compile.
plugins: List of plugins to use.
"""
self.compress = compress
self.paths = list(paths)
self.imports = list(imports)
self.plugins = dict(plugins)
self._context = None
self._backend = None
def use(self, plugin, arguments={}):
"""Add plugin to use during compilation.
plugin: Plugin to include.
arguments: Dictionary of arguments to pass to the import.
"""
self.plugins[plugin] = dict(arguments)
return self.plugins
def compile(self, source, options={}):
"""Compile stylus into css
source: A string containing the stylus code
options: A dictionary of arguments to pass to the compiler
Returns a string of css resulting from the compilation
"""
options = dict(options)
if "paths" in options:
options["paths"] += self.paths
else:
options["paths"] = self.paths
if "compress" not in options:
options["compress"] = self.compress
return self.context.call("compiler", source, options, self.plugins, self.imports)
# INTERNAL METHODS BELOW
@property
def context(self):
"Internal property that returns the stylus compiler"
if self._context is None:
with io.open(path.join(path.abspath(path.dirname(__file__)), "compiler.js")) as compiler_file:
compiler_source = compiler_file.read()
self._context = self.backend.compile(compiler_source)
return self._context
@property
def backend(self):
"Internal property that returns the Node script running harness"
if self._backend is None:
with io.open(path.join(path.abspath(path.dirname(__file__)), "runner.js")) as runner_file:
runner_source = runner_file.read()
self._backend = execjs.ExternalRuntime(name="Node.js (V8)",
command=["node"],
runner_source=runner_source)
return self._backend
| mit | 1,651,126,679,889,479,700 | 30.379747 | 100 | 0.654296 | false |
tcstewar/graph_based_models | gbm/models/demand.py | 1 | 1478 | import numpy as np
from gbm.models.core import Parameter, Line, GraphBasedModel
class DemandCurve(GraphBasedModel):
def __init__(self):
super(DemandCurve, self).__init__(name='Demand Curve',
ylabel='price ($)',
xlabel='amount produced (%)')
self.add(Parameter('p_max', 5, min=0, max=20,
desc='Maximum Price'))
self.add(Parameter('p_min', 0, min=0, max=20,
desc='Minimum Price'))
self.add(Parameter('slope', 0, min=0, max=100,
desc='Price reduction', decimals=2))
self.add(Parameter('quantity', 50, min=0, max=100,
desc='Quantity'))
def generate_data(self, p):
steps = 200
qq = np.linspace(0, 100, steps)
price = -p.slope * p.p_max * 0.001 * qq + p.p_max
price = np.maximum(price, p.p_min)
target_price = -p.slope * p.p_max * 0.001 * p.quantity + p.p_max
target_price = np.maximum(target_price, p.p_min)
results = [
Line(qq, price, color='green', label='demand'),
Line([0, p.quantity], [target_price, target_price], color='blue', label='price'),
Line([p.quantity, p.quantity], [0, target_price], color='red', label='quantity'),
]
return results
if __name__ == '__main__':
m = DemandCurve()
r = m.run()
m.plot_pylab(r)
| gpl-2.0 | 7,159,270,203,059,533,000 | 35.04878 | 93 | 0.509472 | false |
kenchen12/TelegramCamBot | TelegramCamBot.py | 1 | 10925 | #pinagem do pir = vcc|signal|gnd com os pinos proximos ao observador
from telegram.ext import Updater, CommandHandler, RegexHandler, MessageHandler, Filters, ConversationHandler, CallbackQueryHandler
from subprocess import call
from telegram import KeyboardButton, InlineKeyboardButton, ReplyKeyboardMarkup, InlineKeyboardMarkup
import _thread
import logging
import re
import time
import RPi.GPIO as GPIO
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',filename='example.log',level=logging.INFO)
logger = logging.getLogger(__name__)
my_token = None
users = set()
#o pino 12, no modo board, da raspberry deve ser conectado ao pino de saída de sinal do pir. Outro pino pode ser escolhido, sempre levando em conta as limitações de hardware
pir_pin = 12
pir_active = False
bot_instance = None
WHICH, PIR, SOUND, NOTIFICATIONS = range(4)
audio_name = None
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
#Informa as funções do bot
def start(bot, update):
keyboard = [[KeyboardButton("Enviar foto")],[KeyboardButton("Screenshot")],[KeyboardButton("Configurar")]]
reply_markup1 = ReplyKeyboardMarkup(keyboard,resize_keyboard=True)
update.message.reply_text("Bem Vindo ao CamBot. Se uma câmera estiver disponível, você será capaz de solicitar que uma foto seja capturada e enviada para você. Se um sensor de movimento estiver disponível, você poderá solicitar que uma foto seja enviada sempre que algo se mover. Além disso, você pode enviar uma mensagem de áudio para que ela seja reproduzida imediatamente ou configurar para que a mensagem de voz seja reproduzida sempre que algo se mover. Também é possível solicitar uma screenshot do hardware que está hospedando este bot.", reply_markup=reply_markup1)
logger.info('User "%s" started using this bot' % (update.effective_user.username))
#função executada quando uma mensagem de voz é recebida
#faz o download do arquivo de voz no formato oga, reproduz usando o omxplayer e registra o ocorrido
def audio_message(bot, update):
voice = bot.get_file(update.message.voice.file_id)
name = 'audio '+time.strftime("%c", time.localtime())+'.oga'
voice.download(custom_path=name)
call(["omxplayer", "-o", "alsa", name])
logger.info('User "%s" sent a the audio "%s" for runonce' % (update.effective_user.username, name))
#função executada durante a "conversa gerenciada" configurar
#faz o download do áudio recebido, define audio_name (variável que define o áudio reproduzido em caso de movimento), envia ao usuário confirmação e regristra o ocorrido
def define_sound(bot, update):
voice = bot.get_file(update.message.voice.file_id)
audio_name = 'audio '+time.strftime("%c", time.localtime())+'.oga'
voice.download(custom_path=audio_name)
update.message.reply_text("O audio enviado será reproduzido quando houver movimentação.")
logger.info('User "%s" sent a the audio "%s" for run on movement' % (update.effective_user.username, audio_name))
return ConversationHandler.END;
#salva uma captura de tela e envia para quem a solicitou e registra o ocorrido
def send_screenshot(bot, update):
name = 'screen '+time.strftime("%c", time.localtime())+'.png'
print(name)
print(call(["scrot", name]))
print(bot_instance.send_photo(chat_id=update.message.chat_id, photo=open(name, 'rb')))
logger.info('User "%s" requested a screenshot' % (update.effective_user.username))
#salva uma captura da webcam, caso tenha sido solicitada por um usuário, envia-a ao usuário que a solicitou. Caso contrário, foi chamada devido a detecção de algum movimento; Então, envia a captura a todos os usuários inscritos
def send_webcam(bot = None, update = None):
name = time.strftime("%c", time.localtime())+'.jpg'
print("send_cam")
call(["fswebcam", "-r", "640x480", name])
if update != None:
print(bot_instance.send_photo(chat_id=update.message.chat_id, photo=open(name, 'rb')))
logger.info('Picture sent to "%s" due to request' % (update.effective_user.username))
elif len(users) != 0:
if audio_name != None:
call(["omxplayer", "-o", "alsa", audio_name])
for user in users:
try:
print(bot_instance.send_photo(chat_id=user, photo=open(name, 'rb')))
logger.info('Picture sent to "%s" due to movement detected' % (user))
except:
print('unexpected error:', sys.exc_info()[0])
raise
#envia as opções de configuração
def setup(bot, update):
print("setup")
keyboard = [[InlineKeyboardButton("Configurar Notificações", callback_data='1')],[InlineKeyboardButton("Configurar PIR", callback_data='2')],[InlineKeyboardButton("Configurar Som", callback_data='3')], [InlineKeyboardButton("Cancelar", callback_data= "cancelar")]]
reply_markup1 = InlineKeyboardMarkup(keyboard)
update.message.reply_text("Escolha o que deseja configurar", reply_markup=reply_markup1)
return WHICH;
#envia as opções de configuração de som
def setup_sound(bot, update):
keyboard = [[InlineKeyboardButton("Desativar", callback_data='desativar')],[InlineKeyboardButton("Cancelar", callback_data='cancelar')]]
reply_markup1 = InlineKeyboardMarkup(keyboard)
bot.edit_message_text(text="Envie uma mensagem de áudio para que ela seja reproduzida sempre que algo se mover ou use a opção de desativar esta funcionalidade.", chat_id=update.effective_user.id, message_id= update.effective_message.message_id)
bot.edit_message_reply_markup(message_id = update.effective_message.message_id, chat_id=update.effective_user.id, reply_markup=reply_markup1)
return SOUND;
#define o áudio que deve ser reproduzido em caso de movimento para None e registra
def deactivate_sound(bot, update):
audio_name = None
bot.edit_message_text(text="A reprodução automática de audio foi desativada.", chat_id=update.effective_user.id, message_id= update.effective_message.message_id)
logger.info('Audio reproduction disabled by user "%s"' % (update.effective_user.username))
return ConversationHandler.END;
#oferece as opções de configuração do sensor de movimento
def setup_pir(bot, update):
keyboard = [[InlineKeyboardButton("Ativar Pir", callback_data='ativado')],[InlineKeyboardButton("Desativar Pir", callback_data='desativado')], [InlineKeyboardButton("Cancelar", callback_data = "cancelar")]]
reply_markup1 = InlineKeyboardMarkup(keyboard)
text1 = "Atualmente o sensor de movimento está "
if pir_active == True:
text1 += "ativado"
else:
text1 += "desativado"
#só pode editar mensagens enviadas pelo bot!
bot.edit_message_text(text=text1, chat_id=update.effective_user.id, message_id= update.effective_message.message_id)
bot.edit_message_reply_markup(message_id = update.effective_message.message_id, chat_id=update.effective_user.id, reply_markup=reply_markup1)
return PIR;
#altera o estado da detecção de movimento
def switch_pir(bot, update):
if update.callback_query.data == 'ativado':
pir_active = True
GPIO.add_event_detect(pir_pin, GPIO.RISING, callback=send_webcam, bouncetime=3000)
logger.info('Pir enabled by user "%s"' % (update.effective_user.username))
if update.callback_query.data == 'desativado':
pir_active = False
GPIO.remove_event_detect(pir_pin)
logger.info('Pir disabled by user "%s"' % (update.effective_user.username))
bot.edit_message_text(text="O sensor foi " + update.callback_query.data, chat_id=update.effective_user.id, message_id= update.effective_message.message_id)
return ConversationHandler.END;
#cancela a configuração: remove os teclados e mensagens e teclados de configuração; Sai da conversa gerenciada sobre configuração
def cancel(bot, update):
bot.edit_message_text(text="Ok", chat_id=update.effective_user.id, message_id= update.effective_message.message_id)
return ConversationHandler.END;
print("Cancel")
#oferece opções sobre notificações
def setup_notifications(bot, update):
keyboard = [[InlineKeyboardButton("Ativar notificações", callback_data='ativadas')], [InlineKeyboardButton("Desativar notificações", callback_data='desativadas')],[InlineKeyboardButton("Cancelar", callback_data='cancelar')]]
reply_markup1 = InlineKeyboardMarkup(keyboard)
if update.effective_user.id in users:
text = "Suas notificações estão ativas"
else:
text = "Suas notificações estão inativas"
bot.edit_message_text(text=text, chat_id=update.effective_user.id, message_id= update.effective_message.message_id)
bot.edit_message_reply_markup(message_id = update.effective_message.message_id, chat_id=update.effective_user.id, reply_markup=reply_markup1)
return NOTIFICATIONS;
#define o estado da configuração de notificação
def switch_notifications(bot, update):
if update.callback_query.data == 'ativadas':
if update.effective_user.id not in users:
users.add(update.effective_user.id)
logger.info('User "%s" subscribed to receive notifications' % (update.effective_user.username))
if update.callback_query.data == 'desativadas':
if update.effective_user.id in users:
users.remove(update.effective_user.id)
logger.info('User "%s" unsubscribed to receive notifications' % (update.effective_user.username))
text = "Suas notificações estão "
bot.edit_message_text(text="As notificações estão " + update.callback_query.data, chat_id=update.effective_user.id, message_id= update.effective_message.message_id)
return ConversationHandler.END;
def main():
if my_token == None:
print ("O Token NÃO FOI DEFINIDO, defina-o usando a variável my_id.")
exit();
#configuração dos pinos de GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pir_pin, GPIO.IN)
#O Token dado pelo BotFather na criação do seu bot
updater = Updater(my_token)
#definição da variável global bot_instance, referência para o seu bot
global bot_instance
bot_instance = updater.bot
#Cria uma "conversa gerenciada", que é iniciada pelo recebimento do texto Configurar
conv_handler = ConversationHandler(entry_points = [RegexHandler("^Configurar$", setup)],
states={
WHICH: [CallbackQueryHandler(setup_notifications, pattern = "^1$"), CallbackQueryHandler(setup_pir, pattern = "^2$"), CallbackQueryHandler(setup_sound, pattern = "^3$")],
PIR: [CallbackQueryHandler(switch_pir)],
SOUND: [MessageHandler(Filters.voice, define_sound), CallbackQueryHandler(deactivate_sound, pattern = "^desativar$")],
NOTIFICATIONS: [CallbackQueryHandler(switch_notifications)]
},
fallbacks = [CallbackQueryHandler(cancel, pattern = "^cancelar$")],
)
#dispatcher é responsável por "despachar" as atualizações que chegam
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(conv_handler);
dp.add_handler(RegexHandler("^Enviar foto$", send_webcam))
dp.add_handler(RegexHandler("^Screenshot", send_screenshot))
dp.add_handler(MessageHandler(Filters.voice, audio_message))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
| gpl-3.0 | 5,757,682,782,751,062,000 | 50.741627 | 574 | 0.755502 | false |
adamwiggins/cocos2d | test/test_transition_fadetr.py | 2 | 1038 | # This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
import cocos
from cocos.director import director
from cocos.actions import *
from cocos.layer import *
from cocos.scenes import *
from cocos.sprite import *
import pyglet
from pyglet.gl import *
class BackgroundLayer( cocos.layer.Layer ):
def __init__(self):
super( BackgroundLayer, self ).__init__()
self.img = pyglet.resource.image('background_image.png')
def draw( self ):
glPushMatrix()
self.transform()
self.img.blit(0,0)
glPopMatrix()
if __name__ == "__main__":
director.init( resizable=True )
scene1 = cocos.scene.Scene()
scene2 = cocos.scene.Scene()
colorl = ColorLayer(32,32,255,255)
sprite = Sprite( 'grossini.png', (320,240) )
colorl.add( sprite )
scene1.add( BackgroundLayer(), z=0 )
scene2.add( colorl, z=0 )
director.run( FadeTRTransition( scene1, 2, scene2) )
| bsd-3-clause | -5,831,127,975,114,752,000 | 24.317073 | 72 | 0.655106 | false |
nusenu/tor-compass | compass.py | 1 | 27881 | #!/usr/bin/env python
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
FAST_EXIT_BANDWIDTH_RATE = 95 * 125 * 1024 # 95 Mbit/s
FAST_EXIT_ADVERTISED_BANDWIDTH = 5000 * 1024 # 5000 kB/s
FAST_EXIT_PORTS = [80, 443, 554, 1755]
FAST_EXIT_MAX_PER_NETWORK = 2
ALMOST_FAST_EXIT_BANDWIDTH_RATE = 80 * 125 * 1024 # 80 Mbit/s
ALMOST_FAST_EXIT_ADVERTISED_BANDWIDTH = 2000 * 1024 # 2000 kB/s
ALMOST_FAST_EXIT_PORTS = [80, 443]
import json
import operator
import sys
import util
import os
from optparse import OptionParser, OptionGroup
import urllib
import re
import itertools
class BaseFilter(object):
def accept(self, relay):
raise NotImplementedError("This isn't implemented by the subclass")
def load(self, relays):
return filter(self.accept, relays)
class RunningFilter(BaseFilter):
def accept(self, relay):
return relay['running']
class FamilyFilter(BaseFilter):
def __init__(self, family, all_relays):
self._family_fingerprint = None
self._family_nickname = None
self._family_relays = []
found_relay = None
for relay in all_relays:
if len(family) == 40 and relay['fingerprint'] == family:
found_relay = relay
break
if len(family) < 20 and 'Named' in relay['flags'] and relay['nickname'] == family:
found_relay = relay
break
if found_relay:
self._family_fingerprint = '$%s' % found_relay['fingerprint']
if 'Named' in found_relay['flags']:
self._family_nickname = found_relay['nickname']
self._family_relays = [self._family_fingerprint] + found_relay.get('family', [])
def accept(self, relay):
fingerprint = '$%s' % relay['fingerprint']
mentions = [fingerprint] + relay.get('family', [])
# Only show families as accepted by consensus (mutually listed relays)
listed = fingerprint in self._family_relays
listed = listed or 'Named' in relay['flags'] and relay['nickname'] in self._family_relays
mentioned = self._family_fingerprint in mentions
mentioned = mentioned or self._family_nickname in mentions
if listed and mentioned:
return True
return False
class CountryFilter(BaseFilter):
def __init__(self, countries=[]):
self._countries = [x.lower() for x in countries]
def accept(self, relay):
return relay.get('country', None) in self._countries
class ASFilter(BaseFilter):
def __init__(self, as_sets=[]):
self._as_sets = [x if not x.isdigit() else "AS" + x for x in as_sets]
def accept(self, relay):
return relay.get('as_number', None) in self._as_sets
class NickFilter(BaseFilter):
def __init__(self, nickregex):
self._nickregex = nickregex
def accept(self, relay):
if re.match(self._nickregex, relay['nickname']):
return True
class ExitFilter(BaseFilter):
def accept(self, relay):
return relay.get('exit_probability', -1) > 0.0
class GuardFilter(BaseFilter):
def accept(self, relay):
return relay.get('guard_probability', -1) > 0.0
class FastExitFilter(BaseFilter):
class Relay(object):
def __init__(self, relay):
self.exit = relay.get('exit_probability')
self.fp = relay.get('fingerprint')
self.relay = relay
def __init__(self, bandwidth_rate=FAST_EXIT_BANDWIDTH_RATE,
advertised_bandwidth=FAST_EXIT_ADVERTISED_BANDWIDTH,
ports=FAST_EXIT_PORTS):
self.bandwidth_rate = bandwidth_rate
self.advertised_bandwidth = advertised_bandwidth
self.ports = ports
def load(self, all_relays):
# First, filter relays based on bandwidth and port requirements.
matching_relays = []
for relay in all_relays:
if relay.get('bandwidth_rate', -1) < self.bandwidth_rate:
continue
if relay.get('advertised_bandwidth', -1) < self.advertised_bandwidth:
continue
relevant_ports = set(self.ports)
summary = relay.get('exit_policy_summary', {})
if 'accept' in summary:
portlist = summary['accept']
elif 'reject' in summary:
portlist = summary['reject']
else:
continue
ports = []
for p in portlist:
if '-' in p:
ports.extend(range(int(p.split('-')[0]),
int(p.split('-')[1]) + 1))
else:
ports.append(int(p))
policy_ports = set(ports)
if 'accept' in summary and not relevant_ports.issubset(policy_ports):
continue
if 'reject' in summary and not relevant_ports.isdisjoint(policy_ports):
continue
matching_relays.append(relay)
return matching_relays
class SameNetworkFilter(BaseFilter):
def __init__(self, orig_filter, max_per_network=FAST_EXIT_MAX_PER_NETWORK):
self.orig_filter = orig_filter
self.max_per_network = max_per_network
def load(self, all_relays):
network_data = {}
for relay in self.orig_filter.load(all_relays):
or_addresses = relay.get("or_addresses")
no_of_addresses = 0
for ip in or_addresses:
ip, port = ip.rsplit(':', 1)
# skip if ipv6
if ':' in ip:
continue
no_of_addresses += 1
if no_of_addresses > 1:
print "[WARNING] - %s has more than one IPv4 OR address - %s" % relay.get("fingerprint"), or_addresses
network = ip.rsplit('.', 1)[0]
if network_data.has_key(network):
if len(network_data[network]) >= FAST_EXIT_MAX_PER_NETWORK:
# assume current relay to have smallest exit_probability
min_exit = relay.get('exit_probability')
min_id = -1
for id, value in enumerate(network_data[network]):
if value.get('exit_probability') < min_exit:
min_exit = value.get('exit_probability')
min_id = id
if min_id != -1:
del network_data[network][min_id]
network_data[network].append(relay)
else:
network_data[network].append(relay)
else:
network_data[network] = [relay]
return list(itertools.chain.from_iterable(network_data.values()))
class InverseFilter(BaseFilter):
def __init__(self, orig_filter):
self.orig_filter = orig_filter
def load(self, all_relays):
matching_relays = self.orig_filter.load(all_relays)
inverse_relays = []
for relay in all_relays:
if relay not in matching_relays:
inverse_relays.append(relay)
return inverse_relays
def get_network_family(relay):
addresses = relay.get('or_addresses', [])
if len(addresses) == 0:
return None
# Guaranteed by Onionoo. Currently restricted to IPv4 by the network design.
primary_ip, _ = addresses[0].split(':')
# Network family is /16, so let's take the first two bytes by regex
return "%s.0.0/16" % re.match(r'^([0-9]+\.[0-9]+)\.', primary_ip).group(1)
def get_family(relay):
if relay.get('family') == None:
return relay['fingerprint']
family = list(relay.get('family'))
fingerprint = str(relay['fingerprint'])
if fingerprint not in family:
family.append('$'+fingerprint)
return "".join(sorted(family))
def get_os(relay):
platform = relay.get('platform', None)
if len(unicode(platform)) == 0:
return None
# we expect the OS string to start with the 4. word (space separated)
# and go until the end of the platform string
# example "Tor 0.2.6.3-alpha on Windows XP" -> Windows XP
rawos = " ".join(unicode(platform).split()[3:])
# lets merge Linux*, Windows*, *BSD (TODO: make this opt-out)
if re.match("^Linux", rawos):
return "Linux"
if re.match(".*Windows", rawos):
return "Windows"
if re.match(".*BSD$", rawos) or re.match("^NetBSD", rawos) or rawos == 'Bitrig' or rawos == 'DragonFly':
return "*BSD"
return " ".join(unicode(platform).split()[3:])
def get_version(relay):
platform = relay.get('platform', None)
if len(platform) == 0:
return None
return platform.split()[1]
class RelayStats(object):
def __init__(self, options, custom_datafile="details.json"):
self._data = None
self._datafile_name = custom_datafile
self._filters = self._create_filters(options)
self._get_group = self._get_group_function(options)
self._relays = None
@property
def data(self):
if not self._data:
self._data = json.load(file(os.path.join(os.path.dirname(os.path.abspath(__file__)), self._datafile_name)))
return self._data
@property
def relays(self):
if self._relays:
return self._relays
self._relays = {}
relays = self.data['relays']
for f in self._filters:
relays = f.load(relays)
for relay in relays:
self.add_relay(relay)
return self._relays
def _create_filters(self, options):
filters = []
if not options.inactive:
filters.append(RunningFilter())
if options.family:
filters.append(FamilyFilter(options.family, self.data['relays']))
if options.nickregex:
filters.append(NickFilter(options.nickregex))
if options.country:
filters.append(CountryFilter(options.country))
if options.ases:
filters.append(ASFilter(options.ases))
if options.exits_only:
filters.append(ExitFilter())
if options.guards_only:
filters.append(GuardFilter())
if options.exit_filter == 'all_relays':
pass
elif options.exit_filter == 'fast_exits_only':
filters.append(SameNetworkFilter(FastExitFilter()))
elif options.exit_filter == 'almost_fast_exits_only':
filters.append(FastExitFilter(ALMOST_FAST_EXIT_BANDWIDTH_RATE,
ALMOST_FAST_EXIT_ADVERTISED_BANDWIDTH,
ALMOST_FAST_EXIT_PORTS))
filters.append(InverseFilter(SameNetworkFilter(FastExitFilter())))
elif options.exit_filter == 'fast_exits_only_any_network':
filters.append(FastExitFilter())
return filters
def _get_group_function(self, options):
funcs = []
if options.by_country:
funcs.append(lambda relay: relay.get('country', None))
if options.by_as:
funcs.append(lambda relay: relay.get('as_number', None))
if options.by_family:
funcs.append(get_family)
if options.by_network_family:
funcs.append(get_network_family)
if options.by_os:
funcs.append(get_os)
if options.by_version:
funcs.append(get_version)
if options.by_contact:
funcs.append(lambda relay: relay.get('contact', None))
# Default on grouping by fingerprint
if len(funcs) == 0:
funcs.append(lambda relay: relay.get('fingerprint'))
return lambda relay: tuple([func(relay) for func in funcs])
def add_relay(self, relay):
key = self._get_group(relay)
if key not in self._relays:
self._relays[key] = []
self._relays[key].append(relay)
WEIGHTS = ['consensus_weight_fraction', 'advertised_bandwidth', 'guard_probability', 'middle_probability', 'exit_probability']
def print_selection(self,selection,options):
"""
Print the selection returned by sort_and_reduce relays into a
string for the command line version.
"""
column_widths = [9,10,10,10,10,42,80 if options.links else 42,7,7,4,16,11]
headings = ["CW","adv_bw","P_guard","P_middle", "P_exit", "Nickname",
"Link" if options.links else "Fingerprint",
"Exit","Guard","CC", "IPv4", "Autonomous System"]
#Print the header
header = "".join(word.ljust(column_widths[i]) for i,word in enumerate(headings))
print(header[:options.short])
for relay in selection['results']:
line = "".join(field.ljust(column_widths[i])
for i,field in
enumerate(relay.printable_fields(options.links)))
print(line[:options.short])
#Print the 'excluded' set if we have it
if selection['excluded']:
line = "".join(field.ljust(column_widths[i])
for i,field in
enumerate(selection['excluded'].printable_fields()))
print(line[:options.short])
#Print the 'total' set if we have it
if selection['total']:
line = "".join(field.ljust(column_widths[i])
for i,field in
enumerate(selection['total'].printable_fields()))
print(line[:options.short])
def sort_and_reduce(self, relay_set, options):
"""
Take a set of relays (has already been grouped and
filtered), sort it and return the ones requested
in the 'top' option. Add index numbers to them as well.
Returns a hash with three values:
*results*: A list of Result objects representing the selected
relays
*excluded*: A Result object representing the stats for the
filtered out relays. May be None
*total*: A Result object representing the stats for all of the
relays in this filterset.
"""
output_relays = list()
excluded_relays = None
total_relays = None
# We need a simple sorting key function
def sort_fn(r):
return getattr(r,options.sort)
relay_set.sort(key=sort_fn,reverse=options.sort_reverse)
if options.top < 0:
options.top = len(relay_set)
# Set up to handle the special lines at the bottom
excluded_relays = util.Result(zero_probs=True)
total_relays = util.Result(zero_probs=True)
if options.by_country or options.by_as or options.by_network_family or options.by_contact or options.by_os or options.by_version or options.by_family:
filtered = "relay groups"
else:
filtered = "relays"
# Add selected relays to the result set
for i,relay in enumerate(relay_set):
# We have no links if we're grouping
if options.by_country or options.by_as or options.by_network_family or options.by_contact or options.by_os or options.by_version or options.by_family:
relay.link = False
if i < options.top:
relay.index = i + 1
output_relays.append(relay)
if i >= options.top:
excluded_relays.p_guard += relay.p_guard
excluded_relays.p_exit += relay.p_exit
excluded_relays.p_middle += relay.p_middle
excluded_relays.adv_bw += relay.adv_bw
excluded_relays.cw += relay.cw
total_relays.p_guard += relay.p_guard
total_relays.p_exit += relay.p_exit
total_relays.p_middle += relay.p_middle
total_relays.adv_bw += relay.adv_bw
total_relays.cw += relay.cw
excluded_relays.nick = "(%d other %s)" % (
len(relay_set) - options.top,
filtered)
total_relays.nick = "(total in selection)"
# Only include the excluded line if
if len(relay_set) <= options.top:
excluded_relays = None
# Only include the last line if
if total_relays.cw > 99.9:
total_relays = None
return {
'results': output_relays,
'excluded': excluded_relays,
'total': total_relays
}
def select_relays(self, grouped_relays, options):
"""
Return a Pythonic representation of the relays result set. Return it as a set of Result objects.
"""
results = []
for group in grouped_relays.itervalues():
#Initialize some stuff
group_weights = dict.fromkeys(RelayStats.WEIGHTS, 0)
relays_in_group, exits_in_group, guards_in_group = 0, 0, 0
ases_in_group = set()
countries_in_group = set()
network_families_in_group = set()
result = util.Result()
for relay in group:
for weight in RelayStats.WEIGHTS:
group_weights[weight] += relay.get(weight, 0)
result.nick = relay['nickname']
result.fp = relay['fingerprint']
result.link = options.links
if 'Exit' in set(relay['flags']) and not 'BadExit' in set(relay['flags']):
result.exit = 'Exit'
exits_in_group += 1
else:
result.exit = '-'
if 'Guard' in set(relay['flags']):
result.guard = 'Guard'
guards_in_group += 1
else:
result.guard = '-'
result.cc = relay.get('country', '??').upper()
countries_in_group.add(result.cc)
result.primary_ip = relay.get('or_addresses', ['??:0'])[0].split(':')[0]
network_families_in_group.add(get_network_family(relay))
result.as_no = relay.get('as_number', '??')
result.as_name = relay.get('as_name', '??')
result.as_info = "%s %s" %(result.as_no, result.as_name)
ases_in_group.add(result.as_info)
relays_in_group += 1
# If we want to group by things, we need to handle some fields
# specially
if options.by_country or options.by_as or options.by_network_family or options.by_contact or options.by_os or options.by_version or options.by_family:
result.nick = "*"
#lets use the nick column
if options.by_contact or options.by_family:
nick = str(relay.get('contact', None))[:39]
result.nick = nick.replace('|','')
if options.by_os:
result.nick = get_os(relay)
if options.by_version:
result.nick = get_version(relay)
if options.by_os and options.by_version:
result.nick = get_version(relay) + " on " + get_os(relay)
if options.by_network_family:
result.nick = get_network_family(relay)
if relays_in_group > 1:
result.fp = "(%d relays)" % relays_in_group
result.exit = "(%d)" % exits_in_group
result.guard = "(%d)" % guards_in_group
if not options.by_as and not options.ases and not len(ases_in_group) == 1:
result.as_info = "(%d)" % len(ases_in_group)
if not options.by_country and not options.country and not len(countries_in_group) == 1:
result.cc = "(%d)" % len(countries_in_group)
if not options.by_network_family:
result.primary_ip = "(%d)" % len(network_families_in_group)
else:
result.primary_ip = network_families_in_group.pop()
#Include our weight values
for weight in group_weights.iterkeys():
result['cw'] = group_weights['consensus_weight_fraction'] * 100.0
result['adv_bw'] = group_weights['advertised_bandwidth'] * 8 / 1000000
result['p_guard'] = group_weights['guard_probability'] * 100.0
result['p_middle'] = group_weights['middle_probability'] * 100.0
result['p_exit'] = group_weights['exit_probability'] * 100.0
results.append(result)
return results
def create_option_parser():
parser = OptionParser()
parser.add_option("-d", "--download", action="store_true",
help="download details.json from Onionoo service")
group = OptionGroup(parser, "Filtering options")
group.add_option("-i", "--inactive", action="store_true", default=False,
help="include relays in selection that aren't currently running")
group.add_option("-a", "--as", dest="ases", action="append",
help="select only relays from autonomous system number AS",
metavar="AS")
group.add_option("-n", "--nickregex", action="store", type="string", metavar="REGEX",
help="select only relays whos nicknames match the given regex")
group.add_option("-c", "--country", action="append",
help="select only relays from country with code CC", metavar="CC")
group.add_option("-e", "--exits-only", action="store_true",
help="select only relays suitable for exit position")
group.add_option("-f", "--family", action="store", type="string", metavar="RELAY",
help="select family by fingerprint or nickname (for named relays)")
group.add_option("-g", "--guards-only", action="store_true",
help="select only relays suitable for guard position")
group.add_option("--exit-filter",type="choice", dest="exit_filter",
choices=["fast_exits_only","almost_fast_exits_only",
"all_relays","fast_exits_only_any_network"],
metavar="{fast_exits_only|almost_fast_exits_only|all_relays|fast_exits_only_any_network}",
default='all_relays')
group.add_option("--fast-exits-only", action="store_true",
help="select only fast exits (%d+ Mbit/s, %d+ KB/s, %s, %d- per /24)" %
(FAST_EXIT_BANDWIDTH_RATE / (125 * 1024),
FAST_EXIT_ADVERTISED_BANDWIDTH / 1024,
'/'.join(map(str, FAST_EXIT_PORTS)),
FAST_EXIT_MAX_PER_NETWORK))
group.add_option("--almost-fast-exits-only", action="store_true",
help="select only almost fast exits (%d+ Mbit/s, %d+ KB/s, %s, not in set of fast exits)" %
(ALMOST_FAST_EXIT_BANDWIDTH_RATE / (125 * 1024),
ALMOST_FAST_EXIT_ADVERTISED_BANDWIDTH / 1024,
'/'.join(map(str, ALMOST_FAST_EXIT_PORTS))))
group.add_option("--fast-exits-only-any-network", action="store_true",
help="select only fast exits without network restriction (%d+ Mbit/s, %d+ KB/s, %s)" %
(FAST_EXIT_BANDWIDTH_RATE / (125 * 1024),
FAST_EXIT_ADVERTISED_BANDWIDTH / 1024,
'/'.join(map(str, FAST_EXIT_PORTS))))
parser.add_option_group(group)
group = OptionGroup(parser, "Grouping options")
group.add_option("-A", "--by-as", action="store_true", default=False,
help="group relays by AS")
group.add_option("-F", "--by-family", action="store_true", default=False,
help="group relays by family")
group.add_option("-C", "--by-country", action="store_true", default=False,
help="group relays by country")
group.add_option("-N", "--by-network-family", action="store_true", default=False,
help="group relays by network family (/16 IPv4)")
group.add_option("-O", "--by-os", action="store_true", default=False,
help="group relays by operating system")
group.add_option("-V", "--by-version", action="store_true", default=False,
help="group relays by tor version")
group.add_option("-T", "--by-contact", action="store_true", default=False,
help="group relays by ContactInfo")
parser.add_option_group(group)
group = OptionGroup(parser, "Sorting options")
group.add_option("--sort", type="choice",
choices=["cw","adv_bw","p_guard","p_exit","p_middle",
"nick","fp"],
metavar="{cw|adv_bw|p_guard|p_exit|p_middle|nick|fp}",
default="cw",
help="sort by this field")
group.add_option("--sort_reverse", action="store_true", default=True,
help="invert the sorting order")
parser.add_option_group(group)
group = OptionGroup(parser, "Display options")
group.add_option("-l", "--links", action="store_true",
help="display links to the Atlas service instead of fingerprints")
group.add_option("-t", "--top", type="int", default=10, metavar="NUM",
help="display only the top results (default: %default; -1 for all)")
group.add_option("-s", "--short", action="store_const",dest='short',const=70,
help="cut the length of the line output at 70 chars")
group.add_option("-j", "--json", action="store_true",
help="output in JSON rather than human-readable format")
group.add_option("--datafile", default="details.json",
help="use a custom datafile (Default: 'details.json')")
parser.add_option_group(group)
return parser
def download_details_file():
url = urllib.urlopen('https://onionoo.torproject.org/details?type=relay')
details_file = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'details.json'), 'w')
details_file.write(url.read())
url.close()
details_file.close()
def fix_exit_filter_options(options):
"""
Translate the old-style exit filter options into
the new format (as received on the front end).
"""
if options.exit_filter != "all_relays":
# We just accept this option's value
return options
fast_exit_options = 0
if options.fast_exits_only:
options.exit_filter = "fast_exits_only"
fast_exit_options += 1
if options.almost_fast_exits_only:
options.exit_filter = "almost_fast_exits_only"
fast_exit_options += 1
if options.fast_exits_only_any_network:
options.exit_filter = "fast_exits_only_any_network"
fast_exit_options += 1
if fast_exit_options > 1:
raise Exception
return options
if '__main__' == __name__:
parser = create_option_parser()
(options, args) = parser.parse_args()
if len(args) > 0:
parser.error("Did not understand positional argument(s), use options instead.")
if options.family and not re.match(r'^[A-F0-9]{40}$', options.family) and not re.match(r'^[A-Za-z0-9]{1,19}$', options.family):
parser.error("Not a valid fingerprint or nickname: %s" % options.family)
try:
options = fix_exit_filter_options(options)
except:
parser.error("Can only filter by one fast-exit option.")
if options.download:
download_details_file()
print "Downloaded details.json. Re-run without --download option."
exit()
if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'details.json')):
parser.error("Did not find details.json. Re-run with --download.")
stats = RelayStats(options,options.datafile)
results = stats.select_relays(stats.relays,options)
sorted_results = stats.sort_and_reduce(results,options)
if options.json:
print(json.dumps(sorted_results,cls=util.ResultEncoder))
else:
stats.print_selection(sorted_results,options)
| mit | 1,551,160,011,918,299,400 | 41.37234 | 158 | 0.581615 | false |
zeeman/cyder | cyder/cydhcp/build/tests/build_tests.py | 1 | 4749 | import os
from django.test import TestCase
from cyder.base.eav.models import Attribute
from cyder.base.utils import copy_tree, remove_dir_contents
from cyder.base.vcs import GitRepo, GitRepoManager, SanityCheckFailure
from cyder.core.ctnr.models import Ctnr
from cyder.core.system.models import System
from cyder.cydhcp.build.builder import DHCPBuilder
from cyder.cydhcp.interface.dynamic_intr.models import DynamicInterface
from cyder.cydhcp.network.models import Network, NetworkAV
from cyder.cydhcp.range.models import Range
DHCPBUILD = {
'stage_dir': '/tmp/cyder_dhcp_test/stage',
'prod_dir': '/tmp/cyder_dhcp_test/prod',
'lock_file': '/tmp/cyder_dhcp_test.lock',
'pid_file': '/tmp/cyder_dhcp_test.pid',
'target_file': 'dhcpd.conf.data',
'check_file': 'dhcpd.conf',
'line_change_limit': 500,
'line_removal_limit': None,
'stop_file': '/tmp/cyder_dhcp_test.stop',
'stop_file_email_interval': None, # never
}
PROD_ORIGIN_DIR = '/tmp/cyder_dhcp_test/prod_origin'
class DHCPBuildTest(TestCase):
fixtures = ['dhcp_build_test.json']
def setUp(self):
if not os.path.isdir(DHCPBUILD['stage_dir']):
os.makedirs(DHCPBUILD['stage_dir'])
if not os.path.isdir(DHCPBUILD['prod_dir']):
os.makedirs(DHCPBUILD['prod_dir'])
remove_dir_contents(DHCPBUILD['prod_dir'])
if not os.path.isdir(PROD_ORIGIN_DIR):
os.makedirs(PROD_ORIGIN_DIR)
remove_dir_contents(PROD_ORIGIN_DIR)
mgr = GitRepoManager(config={
'user.name': 'test',
'user.email': 'test',
})
mgr.init(PROD_ORIGIN_DIR, bare=True)
mgr.clone(PROD_ORIGIN_DIR, DHCPBUILD['prod_dir'])
self.builder = DHCPBuilder(verbose=False, debug=False, **DHCPBUILD)
self.builder.repo.commit_and_push(
empty=True, message='Initial commit')
copy_tree('cyder/cydhcp/build/tests/files/', DHCPBUILD['stage_dir'])
super(DHCPBuildTest, self).setUp()
def test_build_and_push(self):
"""Test that adding data triggers a rebuild"""
self.builder.build()
self.builder.push(sanity_check=False)
rev1 = self.builder.repo.get_revision()
self.builder.build()
self.builder.push(sanity_check=False)
rev2 = self.builder.repo.get_revision()
self.assertEqual(rev1, rev2)
NetworkAV.objects.create(
entity=Network.objects.get(network_str='192.168.0.0/16'),
attribute=Attribute.objects.get(attribute_type='o',
name='routers'),
value='192.168.0.1',
)
self.builder.build()
self.builder.push(sanity_check=False)
rev3 = self.builder.repo.get_revision()
self.assertNotEqual(rev2, rev3)
def test_sanity_check1(self):
"""Test that the sanity check fails when too many lines are changed"""
self.builder.repo.line_change_limit = 1
self.builder.repo.line_removal_limit = 100
self.builder.build()
self.builder.push(sanity_check=False)
d = DynamicInterface.objects.create(
system=System.objects.get(name='Test_system_5'),
mac='ab:cd:ef:ab:cd:ef',
range=Range.objects.get(name='Test range 1'),
ctnr=Ctnr.objects.get(name='Global'),
)
self.builder.build()
self.assertRaises(
SanityCheckFailure, self.builder.push, sanity_check=True)
def test_sanity_check2(self):
"""Test that the sanity check fails when too many lines are removed"""
self.builder.repo.line_change_limit = 100
self.builder.repo.line_removal_limit = 1
self.builder.build()
self.builder.push(sanity_check=False)
DynamicInterface.objects.filter(
mac__in=('010204081020', 'aabbccddeeff')).delete()
self.builder.build()
self.assertRaises(
SanityCheckFailure, self.builder.push, sanity_check=True)
def test_sanity_check3(self):
"""Test that the sanity check succeeds when changes are sane"""
self.builder.repo.line_change_limit = 100
self.builder.repo.line_removal_limit = 100
self.builder.build()
self.builder.push(sanity_check=False)
DynamicInterface.objects.filter(
mac__in=('010204081020', 'aabbccddeeff')).delete()
d = DynamicInterface.objects.create(
system=System.objects.get(name='Test_system_5'),
mac='ab:cd:ef:ab:cd:ef',
range=Range.objects.get(name='Test range 1'),
ctnr=Ctnr.objects.get(name='Global'),
)
self.builder.build()
self.builder.push(sanity_check=True)
| bsd-3-clause | 1,228,734,177,426,527,000 | 31.527397 | 78 | 0.629606 | false |
hickmank/pyda | pyda/analysis_generator/analysis_generator_class.py | 1 | 1952 | import inspect
import numpy as np
class AnalysisGeneratorClass(object):
# This serves as a template for the user of pyda to implement
# their own analysis generation. The initial conditions and
# parameters used in the ensemble are contained passed to the
# analysis scheme in one array. Hence the initialization
# conditions are treated as parameters.
# When the analysis is used it must MINIMALLY be passed
# information about:
# - ensemble array
# - ensemble observation
# - data array
# - data covariance
# - parameter/initialization array
# INPUT: {numpy arrays}
# <Data Array> = (measurement size)x(ensemble size)
# <Data Covariance> = (measurement size)x(measurement size)
# <Ensemble Array> = (simulation size)x(ensemble size)
# <Parameter Array> = (parameter size)x(ensemble size)
# <Ensemble Observation Array> = (measurement size)x(ensemble size)
#
# RETURN: {numpy arrays}
# <Analysis Array> = (simulation size)x(ensemble size)
# <Analysis Parameter Array> = (parameter size)x(ensemble size)
def __init__(self):
self.Name = 'Analysis Scheme Name'
# Returns the analysis ensemble array and the analysis parameter array.
# AnsArray = (Ntimestep*SimulationDimension)x(EnSize) numpy array
# AnsParamArray = (Parameter Size + Initialization Size)x(EnSize) numpy array
def create_analysis(self,Data,DataCov,ParamArray,EnsArray,ObsArray):
# For an example implementation look at
# enkf*.py.
self.ParamArray = ParamArray
self.EnSize = ParamArray.shape[1]
self.Data = Data
self.DataCov = DataCov
self.ObsArray = ObsArray
self.EnsArray
# return [AnsArray,AnsParamArray]
raise NotImplementedError(inspect.stack()[0][3])
| apache-2.0 | 53,836,932,768,927,810 | 41.434783 | 81 | 0.638832 | false |
RPGOne/Skynet | pytorch-master/torch/legacy/nn/SpatialClassNLLCriterion.py | 1 | 1214 | import torch
from .Criterion import Criterion
class SpatialClassNLLCriterion(Criterion):
def __init__(self, weights=None, sizeAverage=True):
assert weights is None or weights.dim() == 1
super(SpatialClassNLLCriterion, self).__init__()
self.sizeAverage = sizeAverage
self.weights = weights
self.output_tensor = torch.zeros(1)
self.total_weight_tensor = torch.ones(1)
def updateOutput(self, input, target):
self._backend.SpatialClassNLLCriterion_updateOutput(
self._backend.library_state,
input,
target,
self.output_tensor,
self.sizeAverage,
self.weights,
self.total_weight_tensor
)
self.output = self.output_tensor[0]
return self.output
def updateGradInput(self, input, target):
self.gradInput.resize_as_(input).zero_()
self._backend.SpatialClassNLLCriterion_updateGradInput(
self._backend.library_state,
input,
target,
self.gradInput,
self.sizeAverage,
self.weights,
self.total_weight_tensor
)
return self.gradInput
| bsd-3-clause | -8,486,290,289,196,009,000 | 29.35 | 63 | 0.599671 | false |
linkhub-sdk/popbill.fax.example.py | resendFAX_multi.py | 1 | 2525 | # -*- coding: utf-8 -*-
# code for console Encoding difference. Dont' mind on it
import sys
import imp
imp.reload(sys)
try:
sys.setdefaultencoding('UTF8')
except Exception as E:
pass
import testValue
from popbill import FaxService, PopbillException
faxService = FaxService(testValue.LinkID, testValue.SecretKey)
faxService.IsTest = testValue.IsTest
faxService.IPRestrictOnOff = testValue.IPRestrictOnOff
faxService.UseStaticIP = testValue.UseStaticIP
faxService.UseLocalTimeYN = testValue.UseLocalTimeYN
'''
[대량전송] 팩스를 재전송합니다.
- 접수일로부터 60일이 경과되지 않은 팩스전송건만 재전송할 수 있습니다.
- 팩스 재전송 요청시 포인트가 차감됩니다. (전송실패시 환불처리)
- https://docs.popbill.com/fax/python/api#ResendFAX_Multi
'''
try:
print("=" * 15 + " 팩스 동보 재전송. (최대 1000건) " + "=" * 15)
# 팝빌회원 사업자번호
CorpNum = testValue.testCorpNum
# 팝빌회원 아이디
UserID = testValue.testUserID
# 팩스 접수번호
ReceiptNum = '019012313543100001'
# 발신번호, 공백처리시 기존전송정보로 재전송
Sender = '010111222'
# 발신자명, 공백처리시 기존전송정보로 재전송
SenderName = '발신자명'
# 예약전송시간, 공백시 즉시전송, 작성형태 yyyyMMddHHmmss
ReserveDT = ''
# 수신정보 배열 None 처리시 기존전송정보로 전송
Receivers = None
# 팩스제목
Title = '팩스 동보 재전송'
# 수신자 정보가 기존전송정보와 다를경우 아래의 코드 참조
"""
Receivers = [] # 수신정보 배열, 최대 1000개
for x in range(0, 10):
Receivers.append(
FaxReceiver(
receiveNum = '010111222', # 수신번호
receiveName = '수신자명'+str(x), # 수신자명
)
)
"""
# 전송요청번호
# 파트너가 전송 건에 대해 관리번호를 구성하여 관리하는 경우 사용.
# 1~36자리로 구성. 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 팝빌 회원별로 중복되지 않도록 할당.
RequestNum = ""
receiptNum = faxService.resendFax_multi(CorpNum, ReceiptNum, Sender,
SenderName, Receivers, ReserveDT, UserID, Title, RequestNum)
print("receiptNum : %s" % receiptNum)
except PopbillException as PE:
print("Exception Occur : [%d] %s" % (PE.code, PE.message))
| mit | -5,737,052,494,094,964,000 | 23.341772 | 104 | 0.634945 | false |
uber/pyro | examples/vae/ss_vae_M2.py | 1 | 20186 | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import argparse
import torch
import torch.nn as nn
from visdom import Visdom
import pyro
import pyro.distributions as dist
from pyro.contrib.examples.util import print_and_log
from pyro.infer import SVI, JitTrace_ELBO, JitTraceEnum_ELBO, Trace_ELBO, TraceEnum_ELBO, config_enumerate
from pyro.optim import Adam
from utils.custom_mlp import MLP, Exp
from utils.mnist_cached import MNISTCached, mkdir_p, setup_data_loaders
from utils.vae_plots import mnist_test_tsne_ssvae, plot_conditional_samples_ssvae
class SSVAE(nn.Module):
"""
This class encapsulates the parameters (neural networks) and models & guides needed to train a
semi-supervised variational auto-encoder on the MNIST image dataset
:param output_size: size of the tensor representing the class label (10 for MNIST since
we represent the class labels as a one-hot vector with 10 components)
:param input_size: size of the tensor representing the image (28*28 = 784 for our MNIST dataset
since we flatten the images and scale the pixels to be in [0,1])
:param z_dim: size of the tensor representing the latent random variable z
(handwriting style for our MNIST dataset)
:param hidden_layers: a tuple (or list) of MLP layers to be used in the neural networks
representing the parameters of the distributions in our model
:param use_cuda: use GPUs for faster training
:param aux_loss_multiplier: the multiplier to use with the auxiliary loss
"""
def __init__(self, output_size=10, input_size=784, z_dim=50, hidden_layers=(500,),
config_enum=None, use_cuda=False, aux_loss_multiplier=None):
super().__init__()
# initialize the class with all arguments provided to the constructor
self.output_size = output_size
self.input_size = input_size
self.z_dim = z_dim
self.hidden_layers = hidden_layers
self.allow_broadcast = config_enum == 'parallel'
self.use_cuda = use_cuda
self.aux_loss_multiplier = aux_loss_multiplier
# define and instantiate the neural networks representing
# the paramters of various distributions in the model
self.setup_networks()
def setup_networks(self):
z_dim = self.z_dim
hidden_sizes = self.hidden_layers
# define the neural networks used later in the model and the guide.
# these networks are MLPs (multi-layered perceptrons or simple feed-forward networks)
# where the provided activation parameter is used on every linear layer except
# for the output layer where we use the provided output_activation parameter
self.encoder_y = MLP([self.input_size] + hidden_sizes + [self.output_size],
activation=nn.Softplus,
output_activation=nn.Softmax,
allow_broadcast=self.allow_broadcast,
use_cuda=self.use_cuda)
# a split in the final layer's size is used for multiple outputs
# and potentially applying separate activation functions on them
# e.g. in this network the final output is of size [z_dim,z_dim]
# to produce loc and scale, and apply different activations [None,Exp] on them
self.encoder_z = MLP([self.input_size + self.output_size] +
hidden_sizes + [[z_dim, z_dim]],
activation=nn.Softplus,
output_activation=[None, Exp],
allow_broadcast=self.allow_broadcast,
use_cuda=self.use_cuda)
self.decoder = MLP([z_dim + self.output_size] +
hidden_sizes + [self.input_size],
activation=nn.Softplus,
output_activation=nn.Sigmoid,
allow_broadcast=self.allow_broadcast,
use_cuda=self.use_cuda)
# using GPUs for faster training of the networks
if self.use_cuda:
self.cuda()
def model(self, xs, ys=None):
"""
The model corresponds to the following generative process:
p(z) = normal(0,I) # handwriting style (latent)
p(y|x) = categorical(I/10.) # which digit (semi-supervised)
p(x|y,z) = bernoulli(loc(y,z)) # an image
loc is given by a neural network `decoder`
:param xs: a batch of scaled vectors of pixels from an image
:param ys: (optional) a batch of the class labels i.e.
the digit corresponding to the image(s)
:return: None
"""
# register this pytorch module and all of its sub-modules with pyro
pyro.module("ss_vae", self)
batch_size = xs.size(0)
options = dict(dtype=xs.dtype, device=xs.device)
with pyro.plate("data"):
# sample the handwriting style from the constant prior distribution
prior_loc = torch.zeros(batch_size, self.z_dim, **options)
prior_scale = torch.ones(batch_size, self.z_dim, **options)
zs = pyro.sample("z", dist.Normal(prior_loc, prior_scale).to_event(1))
# if the label y (which digit to write) is supervised, sample from the
# constant prior, otherwise, observe the value (i.e. score it against the constant prior)
alpha_prior = torch.ones(batch_size, self.output_size, **options) / (1.0 * self.output_size)
ys = pyro.sample("y", dist.OneHotCategorical(alpha_prior), obs=ys)
# Finally, score the image (x) using the handwriting style (z) and
# the class label y (which digit to write) against the
# parametrized distribution p(x|y,z) = bernoulli(decoder(y,z))
# where `decoder` is a neural network. We disable validation
# since the decoder output is a relaxed Bernoulli value.
loc = self.decoder.forward([zs, ys])
pyro.sample("x", dist.Bernoulli(loc, validate_args=False).to_event(1),
obs=xs)
# return the loc so we can visualize it later
return loc
def guide(self, xs, ys=None):
"""
The guide corresponds to the following:
q(y|x) = categorical(alpha(x)) # infer digit from an image
q(z|x,y) = normal(loc(x,y),scale(x,y)) # infer handwriting style from an image and the digit
loc, scale are given by a neural network `encoder_z`
alpha is given by a neural network `encoder_y`
:param xs: a batch of scaled vectors of pixels from an image
:param ys: (optional) a batch of the class labels i.e.
the digit corresponding to the image(s)
:return: None
"""
# inform Pyro that the variables in the batch of xs, ys are conditionally independent
with pyro.plate("data"):
# if the class label (the digit) is not supervised, sample
# (and score) the digit with the variational distribution
# q(y|x) = categorical(alpha(x))
if ys is None:
alpha = self.encoder_y.forward(xs)
ys = pyro.sample("y", dist.OneHotCategorical(alpha))
# sample (and score) the latent handwriting-style with the variational
# distribution q(z|x,y) = normal(loc(x,y),scale(x,y))
loc, scale = self.encoder_z.forward([xs, ys])
pyro.sample("z", dist.Normal(loc, scale).to_event(1))
def classifier(self, xs):
"""
classify an image (or a batch of images)
:param xs: a batch of scaled vectors of pixels from an image
:return: a batch of the corresponding class labels (as one-hots)
"""
# use the trained model q(y|x) = categorical(alpha(x))
# compute all class probabilities for the image(s)
alpha = self.encoder_y.forward(xs)
# get the index (digit) that corresponds to
# the maximum predicted class probability
res, ind = torch.topk(alpha, 1)
# convert the digit(s) to one-hot tensor(s)
ys = torch.zeros_like(alpha).scatter_(1, ind, 1.0)
return ys
def model_classify(self, xs, ys=None):
"""
this model is used to add an auxiliary (supervised) loss as described in the
Kingma et al., "Semi-Supervised Learning with Deep Generative Models".
"""
# register all pytorch (sub)modules with pyro
pyro.module("ss_vae", self)
# inform Pyro that the variables in the batch of xs, ys are conditionally independent
with pyro.plate("data"):
# this here is the extra term to yield an auxiliary loss that we do gradient descent on
if ys is not None:
alpha = self.encoder_y.forward(xs)
with pyro.poutine.scale(scale=self.aux_loss_multiplier):
pyro.sample("y_aux", dist.OneHotCategorical(alpha), obs=ys)
def guide_classify(self, xs, ys=None):
"""
dummy guide function to accompany model_classify in inference
"""
pass
def run_inference_for_epoch(data_loaders, losses, periodic_interval_batches):
"""
runs the inference algorithm for an epoch
returns the values of all losses separately on supervised and unsupervised parts
"""
num_losses = len(losses)
# compute number of batches for an epoch
sup_batches = len(data_loaders["sup"])
unsup_batches = len(data_loaders["unsup"])
batches_per_epoch = sup_batches + unsup_batches
# initialize variables to store loss values
epoch_losses_sup = [0.] * num_losses
epoch_losses_unsup = [0.] * num_losses
# setup the iterators for training data loaders
sup_iter = iter(data_loaders["sup"])
unsup_iter = iter(data_loaders["unsup"])
# count the number of supervised batches seen in this epoch
ctr_sup = 0
for i in range(batches_per_epoch):
# whether this batch is supervised or not
is_supervised = (i % periodic_interval_batches == 1) and ctr_sup < sup_batches
# extract the corresponding batch
if is_supervised:
(xs, ys) = next(sup_iter)
ctr_sup += 1
else:
(xs, ys) = next(unsup_iter)
# run the inference for each loss with supervised or un-supervised
# data as arguments
for loss_id in range(num_losses):
if is_supervised:
new_loss = losses[loss_id].step(xs, ys)
epoch_losses_sup[loss_id] += new_loss
else:
new_loss = losses[loss_id].step(xs)
epoch_losses_unsup[loss_id] += new_loss
# return the values of all losses
return epoch_losses_sup, epoch_losses_unsup
def get_accuracy(data_loader, classifier_fn, batch_size):
"""
compute the accuracy over the supervised training set or the testing set
"""
predictions, actuals = [], []
# use the appropriate data loader
for (xs, ys) in data_loader:
# use classification function to compute all predictions for each batch
predictions.append(classifier_fn(xs))
actuals.append(ys)
# compute the number of accurate predictions
accurate_preds = 0
for pred, act in zip(predictions, actuals):
for i in range(pred.size(0)):
v = torch.sum(pred[i] == act[i])
accurate_preds += (v.item() == 10)
# calculate the accuracy between 0 and 1
accuracy = (accurate_preds * 1.0) / (len(predictions) * batch_size)
return accuracy
def visualize(ss_vae, viz, test_loader):
if viz:
plot_conditional_samples_ssvae(ss_vae, viz)
mnist_test_tsne_ssvae(ssvae=ss_vae, test_loader=test_loader)
def main(args):
"""
run inference for SS-VAE
:param args: arguments for SS-VAE
:return: None
"""
if args.seed is not None:
pyro.set_rng_seed(args.seed)
viz = None
if args.visualize:
viz = Visdom()
mkdir_p("./vae_results")
# batch_size: number of images (and labels) to be considered in a batch
ss_vae = SSVAE(z_dim=args.z_dim,
hidden_layers=args.hidden_layers,
use_cuda=args.cuda,
config_enum=args.enum_discrete,
aux_loss_multiplier=args.aux_loss_multiplier)
# setup the optimizer
adam_params = {"lr": args.learning_rate, "betas": (args.beta_1, 0.999)}
optimizer = Adam(adam_params)
# set up the loss(es) for inference. wrapping the guide in config_enumerate builds the loss as a sum
# by enumerating each class label for the sampled discrete categorical distribution in the model
guide = config_enumerate(ss_vae.guide, args.enum_discrete, expand=True)
Elbo = JitTraceEnum_ELBO if args.jit else TraceEnum_ELBO
elbo = Elbo(max_plate_nesting=1, strict_enumeration_warning=False)
loss_basic = SVI(ss_vae.model, guide, optimizer, loss=elbo)
# build a list of all losses considered
losses = [loss_basic]
# aux_loss: whether to use the auxiliary loss from NIPS 14 paper (Kingma et al)
if args.aux_loss:
elbo = JitTrace_ELBO() if args.jit else Trace_ELBO()
loss_aux = SVI(ss_vae.model_classify, ss_vae.guide_classify, optimizer, loss=elbo)
losses.append(loss_aux)
try:
# setup the logger if a filename is provided
logger = open(args.logfile, "w") if args.logfile else None
data_loaders = setup_data_loaders(MNISTCached, args.cuda, args.batch_size, sup_num=args.sup_num)
# how often would a supervised batch be encountered during inference
# e.g. if sup_num is 3000, we would have every 16th = int(50000/3000) batch supervised
# until we have traversed through the all supervised batches
periodic_interval_batches = int(MNISTCached.train_data_size / (1.0 * args.sup_num))
# number of unsupervised examples
unsup_num = MNISTCached.train_data_size - args.sup_num
# initializing local variables to maintain the best validation accuracy
# seen across epochs over the supervised training set
# and the corresponding testing set and the state of the networks
best_valid_acc, corresponding_test_acc = 0.0, 0.0
# run inference for a certain number of epochs
for i in range(0, args.num_epochs):
# get the losses for an epoch
epoch_losses_sup, epoch_losses_unsup = \
run_inference_for_epoch(data_loaders, losses, periodic_interval_batches)
# compute average epoch losses i.e. losses per example
avg_epoch_losses_sup = map(lambda v: v / args.sup_num, epoch_losses_sup)
avg_epoch_losses_unsup = map(lambda v: v / unsup_num, epoch_losses_unsup)
# store the loss and validation/testing accuracies in the logfile
str_loss_sup = " ".join(map(str, avg_epoch_losses_sup))
str_loss_unsup = " ".join(map(str, avg_epoch_losses_unsup))
str_print = "{} epoch: avg losses {}".format(i, "{} {}".format(str_loss_sup, str_loss_unsup))
validation_accuracy = get_accuracy(data_loaders["valid"], ss_vae.classifier, args.batch_size)
str_print += " validation accuracy {}".format(validation_accuracy)
# this test accuracy is only for logging, this is not used
# to make any decisions during training
test_accuracy = get_accuracy(data_loaders["test"], ss_vae.classifier, args.batch_size)
str_print += " test accuracy {}".format(test_accuracy)
# update the best validation accuracy and the corresponding
# testing accuracy and the state of the parent module (including the networks)
if best_valid_acc < validation_accuracy:
best_valid_acc = validation_accuracy
corresponding_test_acc = test_accuracy
print_and_log(logger, str_print)
final_test_accuracy = get_accuracy(data_loaders["test"], ss_vae.classifier, args.batch_size)
print_and_log(logger, "best validation accuracy {} corresponding testing accuracy {} "
"last testing accuracy {}".format(best_valid_acc, corresponding_test_acc, final_test_accuracy))
# visualize the conditional samples
visualize(ss_vae, viz, data_loaders["test"])
finally:
# close the logger file object if we opened it earlier
if args.logfile:
logger.close()
EXAMPLE_RUN = "example run: python ss_vae_M2.py --seed 0 --cuda -n 2 --aux-loss -alm 46 -enum parallel " \
"-sup 3000 -zd 50 -hl 500 -lr 0.00042 -b1 0.95 -bs 200 -log ./tmp.log"
if __name__ == "__main__":
assert pyro.__version__.startswith('1.5.1')
parser = argparse.ArgumentParser(description="SS-VAE\n{}".format(EXAMPLE_RUN))
parser.add_argument('--cuda', action='store_true',
help="use GPU(s) to speed up training")
parser.add_argument('--jit', action='store_true',
help="use PyTorch jit to speed up training")
parser.add_argument('-n', '--num-epochs', default=50, type=int,
help="number of epochs to run")
parser.add_argument('--aux-loss', action="store_true",
help="whether to use the auxiliary loss from NIPS 14 paper "
"(Kingma et al). It is not used by default ")
parser.add_argument('-alm', '--aux-loss-multiplier', default=46, type=float,
help="the multiplier to use with the auxiliary loss")
parser.add_argument('-enum', '--enum-discrete', default="parallel",
help="parallel, sequential or none. uses parallel enumeration by default")
parser.add_argument('-sup', '--sup-num', default=3000,
type=float, help="supervised amount of the data i.e. "
"how many of the images have supervised labels")
parser.add_argument('-zd', '--z-dim', default=50, type=int,
help="size of the tensor representing the latent variable z "
"variable (handwriting style for our MNIST dataset)")
parser.add_argument('-hl', '--hidden-layers', nargs='+', default=[500], type=int,
help="a tuple (or list) of MLP layers to be used in the neural networks "
"representing the parameters of the distributions in our model")
parser.add_argument('-lr', '--learning-rate', default=0.00042, type=float,
help="learning rate for Adam optimizer")
parser.add_argument('-b1', '--beta-1', default=0.9, type=float,
help="beta-1 parameter for Adam optimizer")
parser.add_argument('-bs', '--batch-size', default=200, type=int,
help="number of images (and labels) to be considered in a batch")
parser.add_argument('-log', '--logfile', default="./tmp.log", type=str,
help="filename for logging the outputs")
parser.add_argument('--seed', default=None, type=int,
help="seed for controlling randomness in this example")
parser.add_argument('--visualize', action="store_true",
help="use a visdom server to visualize the embeddings")
args = parser.parse_args()
# some assertions to make sure that batching math assumptions are met
assert args.sup_num % args.batch_size == 0, "assuming simplicity of batching math"
assert MNISTCached.validation_size % args.batch_size == 0, \
"batch size should divide the number of validation examples"
assert MNISTCached.train_data_size % args.batch_size == 0, \
"batch size doesn't divide total number of training data examples"
assert MNISTCached.test_size % args.batch_size == 0, "batch size should divide the number of test examples"
main(args)
| apache-2.0 | -6,638,713,981,091,142,000 | 45.19222 | 117 | 0.619291 | false |
Archer4499/m4a_tagger | main.py | 1 | 18661 | import queue
import threading
from glob import glob
from os import chdir
from tkinter import *
from tkinter import ttk, filedialog, messagebox
from mutagen.mp4 import MP4, MP4StreamInfoError
from utils import get_external_tags
__author__ = 'Derek'
TAGS = [["Title:\t", "\xa9nam"], ["Album:\t", "\xa9alb"], ["Artist:\t", "\xa9ART"],
["Track:\t", "trkn"], ["Year:\t", "\xa9day"], ["Genre:\t", "\xa9gen"]]
OTHER_TAGS = {"aART": "Album artist:", "\xa9wrt": "Composer:", "\xa9cmt": "Comment:",
"desc": "Description:", "purd": "Purchase date:", "\xa9grp": "Grouping:",
"\xa9lyr": "Lyrics:", "purl": "Podcast URL:", "egid": "Podcast episode GUID:",
"catg": "Podcast category:", "keyw": "Podcast keywords:",
"\xa9too": "Encoded by:", "cprt": "Copyright:", "soal": "Album sort order:",
"soaa": "Album artist sort order:", "soar": "Artist sort order:",
"sonm": "Title sort order:", "soco": "Composer sort order:",
"sosn": "Show sort order:", "tvsh": "Show name:", "cpil": "Compilation:",
"pgap": "Gapless album:", "pcst": "Podcast:", "disk": "Disc number, total:",
"tmpo": "Tempo/BPM, 16 bit int:"}
with open("genres.txt", "r") as f:
GENRES = f.read().splitlines()
class Settings(Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.transient(parent)
self.title("Settings")
self.parent = parent
self.result = None
body = ttk.Frame(self)
body.pack(padx=5, pady=5)
self.browser = IntVar()
self.browser.set(int(parent.browser))
c = ttk.Checkbutton(body, text="Open in browser", variable=self.browser)
c.grid(column=0, row=0, sticky=W)
c.focus_set()
self.buttonbox()
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50, parent.winfo_rooty()+50))
self.wait_window(self)
def buttonbox(self):
box = ttk.Frame(self)
w = ttk.Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
w.pack(side=LEFT, padx=5, pady=5)
w = ttk.Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side=LEFT, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
def cancel(self, *_):
# put focus back to the parent window
self.parent.focus_set()
self.destroy()
def apply(self):
self.parent.browser = bool(self.browser.get())
def ok(self, *_):
self.withdraw()
self.update_idletasks()
self.apply()
self.cancel()
class CurrentInfo:
class CurrentEntry(ttk.Entry):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.state(["readonly"])
def __init__(self, parent, column):
self.var_list = [StringVar() if i is not 3 else [StringVar(), StringVar()] for i in range(len(TAGS))]
ttk.Label(parent, text="Current:").grid(column=column, row=0, sticky=W)
title = self.CurrentEntry(parent, textvariable=self.var_list[0])
title.grid(column=column, row=1, sticky=(W, E))
album = self.CurrentEntry(parent, textvariable=self.var_list[1])
album.grid(column=column, row=2, sticky=(W, E))
artist = self.CurrentEntry(parent, textvariable=self.var_list[2])
artist.grid(column=column, row=3, sticky=(W, E))
# Track
track_frame = ttk.Frame(parent, padding=(5, 0))
track_frame.grid(column=column, row=4, sticky=W)
track = self.CurrentEntry(track_frame, width=3, textvariable=self.var_list[3][0])
track.grid(column=0, row=0, sticky=(W, E))
# /
ttk.Label(track_frame, text="/").grid(column=1, row=0)
# Total Tracks
track_total = self.CurrentEntry(track_frame, width=3, textvariable=self.var_list[3][1])
track_total.grid(column=2, row=0, sticky=(W, E))
year = self.CurrentEntry(parent, width=5, textvariable=self.var_list[4])
year.grid(column=column, row=5, sticky=W)
genre = self.CurrentEntry(parent, textvariable=self.var_list[5])
genre.grid(column=column, row=6, sticky=(W, E))
class NewEntry:
class NumEntry(ttk.Entry):
def __init__(self, length, min_val, max_val, *args, **kwargs):
super().__init__(*args, **kwargs)
self.length = length
self.min_val = min_val
self.max_val = max_val
self.configure(width=self.length + 1, validate="key",
validatecommand=(self.register(self.on_validate), "%P"))
def on_validate(self, new_value):
if new_value.strip() == "":
return True
try:
value = int(new_value)
if value < self.min_val or value > self.max_val or len(str(value)) > self.length:
raise ValueError
except ValueError:
self.bell()
return False
return True
def __init__(self, parent, column, select_var, name):
self.var_list = [StringVar() if i is not 3 else [StringVar(), StringVar()] for i in range(len(TAGS))]
ttk.Label(parent, text=name).grid(column=column, row=0, sticky=W)
self.title = ttk.Entry(parent, textvariable=self.var_list[0])
self.title.grid(column=column, row=1, sticky=(W, E))
album = ttk.Entry(parent, textvariable=self.var_list[1])
album.grid(column=column, row=2, sticky=(W, E))
artist = ttk.Entry(parent, textvariable=self.var_list[2])
artist.grid(column=column, row=3, sticky=(W, E))
# Track
track_frame = ttk.Frame(parent, padding=(5, 0))
track_frame.grid(column=column, row=4, sticky=W)
track = self.NumEntry(2, 0, 99, track_frame, textvariable=self.var_list[3][0])
track.grid(column=0, row=0, sticky=(W, E))
# /
ttk.Label(track_frame, text="/").grid(column=1, row=0)
# Total Tracks
track_total = self.NumEntry(2, 0, 99, track_frame, textvariable=self.var_list[3][1])
track_total.grid(column=2, row=0, sticky=(W, E))
year = self.NumEntry(4, 0, 9999, parent, textvariable=self.var_list[4])
year.grid(column=column, row=5, sticky=W)
genre = ttk.Combobox(parent, textvariable=self.var_list[5], values=GENRES)
genre.grid(column=column, row=6, sticky=(W, E))
select = ttk.Radiobutton(parent, variable=select_var, value=name)
select.grid(column=column, row=7)
class MenuBar(Menu):
def __init__(self, root, close):
super().__init__()
self.option_add("*tearOff", FALSE)
file_menu = Menu(self)
file_menu.add_command(label="Settings",
command=lambda: Settings(root))
file_menu.add_command(label="Exit", command=close)
help_menu = Menu(self)
help_menu.add_command(label="About",
command=lambda: messagebox.showinfo("About", "This is an Mp4 tagger"))
self.add_cascade(menu=file_menu, label="File")
self.add_cascade(menu=help_menu, label="Help")
root.config(menu=self)
# noinspection PyAttributeOutsideInit
class Gui(Tk):
def __init__(self):
super().__init__()
self.songs = []
self.total_songs = 0
self.current_song = MP4()
self.current_song_file_name = StringVar("")
self.extra_tags = dict()
self.browser = True
self.load_queue = queue.Queue()
self.custom_queue = queue.Queue()
self.title("M4a Tagger")
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
MenuBar(self, self.quit)
mainframe = ttk.Frame(self, padding=(3, 3, 0, 0))
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
# Clear focus from text boxes on click
mainframe.bind("<1>", lambda event: mainframe.focus_set())
self.entry_select = StringVar(value="Dbpedia:")
self.init_columns(mainframe)
self.extra_tags_var = StringVar()
self.init_extra(mainframe, 9)
self.custom_url = StringVar()
self.init_custom_url(mainframe, 8)
self.progress = StringVar(value="Song 0 of 0")
self.init_buttons(mainframe)
# Add padding to most widgets
for child in mainframe.winfo_children():
if type(child) != ttk.Frame:
child.grid_configure(padx=5, pady=5)
ttk.Sizegrip(self).grid(column=999, row=999, sticky=(S, E))
def init_columns(self, mainframe):
# Row Labels
for i, item in enumerate(TAGS):
ttk.Label(mainframe, text=item[0]).grid(column=0, row=i + 1, sticky=E)
self.current_info = CurrentInfo(mainframe, 1)
mainframe.columnconfigure(1, weight=1, uniform="a")
self.dbpedia_entry = NewEntry(mainframe, 2, self.entry_select, "Dbpedia:")
self.dbpedia_entry.title.focus()
mainframe.columnconfigure(2, weight=1, uniform="a")
self.wiki_entry = NewEntry(mainframe, 3, self.entry_select, "Wikipedia:")
mainframe.columnconfigure(3, weight=1, uniform="a")
self.discogs_entry = NewEntry(mainframe, 4, self.entry_select, "Discogs:")
mainframe.columnconfigure(4, weight=1, uniform="a")
ttk.Label(mainframe, text="Select tag source:").grid(column=1, row=7, sticky=W)
ttk.Label(mainframe, textvariable=self.current_song_file_name)\
.grid(column=1, columnspan=2, row=8, sticky=W)
def init_extra(self, mainframe, row_num):
ttk.Label(mainframe, text="The following tags will be removed:") \
.grid(column=1, columnspan=2, row=row_num, sticky=W)
extra_tags_frame = ttk.Frame(mainframe, padding=(5, 0), borderwidth=2, relief="sunken")
extra_tags_frame.grid(column=1, columnspan=2, row=row_num+1, sticky=(W, E), padx=5)
ttk.Label(extra_tags_frame, textvariable=self.extra_tags_var, font="TkFixedFont") \
.grid(column=0, row=0, sticky=(W, E))
def init_custom_url(self, mainframe, row_num):
ttk.Label(mainframe, text="Enter wikipedia url if the sources are incorrect:") \
.grid(column=3, columnspan=2, row=row_num, sticky=W)
custom_url_frame = ttk.Frame(mainframe)
custom_url_frame.grid(column=3, columnspan=2, row=row_num+1, sticky=(W, E), padx=(5, 0))
ttk.Label(custom_url_frame, text="en.wikipedia.org/wiki/") \
.grid(column=0, row=0, sticky=W)
custom_url_entry = ttk.Entry(custom_url_frame, textvariable=self.custom_url)
custom_url_entry.grid(column=1, row=0, sticky=W)
self.custom_url_button = ttk.Button(custom_url_frame, text="Load URL", command=self.load_url)
self.custom_url_button.grid(column=2, row=0)
self.custom_url_button.state(["disabled"])
def init_buttons(self, mainframe):
button_frame = ttk.Frame(mainframe, padding=(5, 10, 0, 0))
button_frame.grid(column=2, columnspan=3, row=100, sticky=E)
self.progress_bar = ttk.Progressbar(button_frame, orient="horizontal", length=50, mode="indeterminate")
self.progress_bar.grid(column=0, row=0)
self.progress_bar.grid_remove()
ttk.Label(button_frame, textvariable=self.progress).grid(column=1, row=0)
self.save_button = ttk.Button(button_frame, text="Save", command=self.save)
self.save_button.grid(column=2, row=0)
self.save_button.state(["disabled"])
self.next_song_button = ttk.Button(button_frame, text="Next Song", command=self.next_song)
self.next_song_button.grid(column=3, row=0)
self.next_song_button.state(["disabled"])
self.browse_button = ttk.Button(button_frame, text="Open Folder", command=self.browse)
self.browse_button.grid(column=4, row=0)
@staticmethod
def set_var_list(var_list, tag_list):
for i, var in enumerate(var_list):
if i is 3:
var[0].set(tag_list[i][0])
if tag_list[i][1]:
var[1].set(tag_list[i][1])
else:
var[1].set("")
else:
var.set(tag_list[i])
def threaded_set_external_tags(self, title):
self.load_queue.put(get_external_tags(title=title, browser=self.browser))
def process_load_queue(self):
try:
external_tags = self.load_queue.get_nowait()
except queue.Empty:
self.after(100, self.process_load_queue)
else:
self.set_var_list(self.dbpedia_entry.var_list, external_tags[0])
self.set_var_list(self.wiki_entry.var_list, external_tags[1])
self.set_var_list(self.discogs_entry.var_list, external_tags[2])
self.progress_bar.stop()
self.progress_bar.grid_remove()
def set_external_tags(self, title):
# TODO: auto load next song
self.progress_bar.grid()
self.progress_bar.start()
# Downloads tags from Dbpedia, Wikipedia and Discogs (takes 11 seconds on average)
# TODO: Handle error messages better
threading.Thread(target=self.threaded_set_external_tags, args=(title,)).start()
self.process_load_queue()
def threaded_correct_external_tags(self, wiki_path):
self.custom_queue.put(get_external_tags(wiki_page=wiki_path, browser=False))
def process_custom_queue(self):
try:
external_tags = self.custom_queue.get_nowait()
except queue.Empty:
self.after(100, self.process_custom_queue)
else:
self.set_var_list(self.dbpedia_entry.var_list, external_tags[0])
self.set_var_list(self.wiki_entry.var_list, external_tags[1])
self.set_var_list(self.discogs_entry.var_list, external_tags[2])
self.progress_bar.stop()
self.progress_bar.grid_remove()
def correct_external_tags(self, wiki_path):
self.progress_bar.grid()
self.progress_bar.start()
wiki_path = "http://en.wikipedia.org/wiki/" + wiki_path
# Downloads tags from Dbpedia, Wikipedia and Discogs (takes 11 seconds on average)
threading.Thread(target=self.threaded_correct_external_tags, args=(wiki_path,)).start()
self.process_custom_queue()
def set_vars(self, external=True):
def tag_name_value(tag_key):
tag = self.extra_tags[tag_key]
if type(tag) is list:
value = tag[0]
else:
value = tag
return OTHER_TAGS.get(tag_key, tag_key).ljust(24) + str(value)
def get_extra_tags():
if "covr" in self.extra_tags:
del self.extra_tags["covr"]
if self.extra_tags:
return "\n".join([tag_name_value(tag_key) for tag_key in self.extra_tags])
else:
return "None"
self.custom_url.set("")
self.extra_tags = dict(self.current_song.tags)
song_tags = [self.extra_tags.pop(tag[1], "None")[0] for tag in TAGS]
self.set_var_list(self.current_info.var_list, song_tags)
self.extra_tags_var.set(get_extra_tags())
self.progress.set(value="Song "+str(self.total_songs-len(self.songs))+" of "+str(self.total_songs))
if external:
self.set_external_tags(song_tags[0])
def load_url(self):
# Bound to custom_url_button
url = self.custom_url.get()
if url:
self.correct_external_tags(url)
def open_next_song(self):
while self.songs:
try:
self.current_song_file_name.set(self.songs.pop())
self.current_song = MP4(self.current_song_file_name.get())
except MP4StreamInfoError as e:
print(repr(e))
else:
return True
return False
def browse(self):
# Bound to browse_button
directory = filedialog.askdirectory(parent=self, mustexist=True)
if not directory:
return
try:
chdir(directory)
except OSError as e:
messagebox.showerror(title="Error", message=repr(e))
return
self.songs = glob("*.m4a")
if not self.songs:
messagebox.showerror(title="Error", message="No .m4a files in the given directory")
return
self.songs.sort()
self.songs.reverse()
self.total_songs = len(self.songs)
if not self.open_next_song():
messagebox.showerror(title="Error", message="No valid .m4a files in the given directory")
return
self.set_vars()
self.custom_url_button.state(["!disabled"])
self.save_button.state(["!disabled"])
self.save_button.config(text="Save")
if self.songs:
self.next_song_button.state(["!disabled"])
def save(self):
# Bound to save_button
if self.extra_tags:
for tag in self.extra_tags:
del self.current_song[tag]
if self.entry_select.get() == "Dbpedia:":
var_save = self.dbpedia_entry.var_list
elif self.entry_select.get() == "Wikipedia:":
var_save = self.wiki_entry.var_list
else:
var_save = self.discogs_entry.var_list
for i, var in enumerate(var_save):
if i is 3:
self.current_song[TAGS[i][1]] = [(int("0" + var[0].get()), int("0" + var[1].get()))]
else:
self.current_song[TAGS[i][1]] = [var.get()]
try:
self.current_song.save()
except Exception as e:
messagebox.showerror(title="Error", message="Couldn't save tags to file",
detail=repr(e))
else:
self.set_vars(False)
self.save_button.state(["disabled"])
self.save_button.config(text="Saved")
def next_song(self):
# Bound to next_song_button
if not self.open_next_song():
messagebox.showerror(title="Error", message="No more valid .m4a files in directory")
self.next_song_button.state(["disabled"])
return
if not self.songs:
self.next_song_button.state(["disabled"])
self.save_button.state(["!disabled"])
self.save_button.config(text="Save")
self.set_vars()
if __name__ == '__main__':
Gui().mainloop()
| mit | -4,028,104,705,513,227,300 | 35.662083 | 111 | 0.584963 | false |
jmgilman/neolib2 | tests/base.py | 1 | 1291 | import os
import sys
import unittest
import getpass
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from neolib.user.User import User
class NeolibTestBase(unittest.TestCase):
_usr = None
susr = None
def setUp(self):
# Check if we have a previously saved user
if NeolibTestBase.susr is not None:
self._usr = NeolibTestBase.susr
return
print('')
print('Welcome to the Neolib 2 test framework!')
print('Please enter the below test configuration values:')
username = input('Account username: ')
password = getpass.getpass('Account password: ')
self._usr = User(username, password)
try:
print('Attempting to login to ' + self._usr.username)
if self._usr.login():
print('Successfully logged into ' + self._usr.username)
# Store this user for later testing
NeolibTestBase.susr = self._usr
else:
print('Failed to login to ' + self._usr.username + '. Exiting...')
exit()
except Exception as e:
print('Error while logging into ' + self._usr.username)
print('Message: ' + str(e))
print('Exiting...')
exit()
| gpl-2.0 | -2,549,930,788,079,709,700 | 27.688889 | 82 | 0.567002 | false |
low-sky/degas | degas/catalogs.py | 1 | 3472 | import subprocess
import glob
import os
import warnings
from astropy.table import Table, join, Column
import numpy as np
from astropy.utils.data import get_pkg_data_filename
import sys
def updateLogs(output='ObservationLog.csv',release=None):
if release is None:
command = "wget --no-check-certificate --output-document="+output+" 'https://docs.google.com/spreadsheet/ccc?key=1wFgxwpDHuYsb7ISWUyBg1xGO6SraRwCIlm1u_fHlrPs&output=csv'"
# The returns from subprocess are the error codes from the OS
# If 0 then it worked so we should return True
return not subprocess.call(command,shell=True)
if 'DR1' in release:
filename = get_pkg_data_filename('data/ObservationLog_DR1.csv',
package='degas')
command = 'cp '+filename+' ./ObservationLog.csv'
return not subprocess.call(command,shell=True)
def loadCatalog(release=None, CatalogFile=None):
if CatalogFile is None:
CatalogFile = get_pkg_data_filename('./data/dense_survey.cat',
package='degas')
Catalog = Table.read(CatalogFile, format='ascii')
return(Catalog)
def validateScanNumbers(catalog, release='QA0'):
for observation in catalog:
if ('Map' in observation['Scan Type']) and (observation[release]):
Nscans = observation['End Scan'] - observation['Start Scan'] + 1
if Nscans - observation['Nrows'] == 4:
warnings.warn("Assuming Vane Cal at start and end")
refscans = [observation['Start Scan'],
observation['End Scan'] -1]
startscan = observation['Start Scan'] + 2
endscan = observation['End Scan'] - 2
elif Nscans - observation['Nrows'] == 2:
warnings.warn("Assuming Vane Cal at start only")
refscans = [observation['Start Scan']]
startscan = observation['Start Scan'] + 2
endscan = observation['End Scan']
elif Nscans - observation['Nrows'] == 0:
warnings.warn("Number of scans = Number of Mapped Rows: no VaneCal")
else:
warnings.warn("Inconsistent number of scan rows")
print(observation)
raise
def parseLog(logfile='ObservationLog.csv'):
"""
Ingests a CSV log file into an astropy table
"""
try:
from astropy.table import Table
except:
warnings.warn('DEGAS Pipeline requires astropy. Try Anaconda!')
return
t = Table.read(logfile)
# Cull to full rows
# idx = ~t['Project'].mask
# t = t[idx]
# Convert from Google Booleans to Python Booleans
qa0 = np.zeros(len(t), dtype=np.bool)
dr1 = np.zeros(len(t), dtype=np.bool)
for idx, row in enumerate(t):
qa0[idx] = ('TRUE' in row['QA0'])
dr1[idx] = ('TRUE' in row['DR1'])
qa0col = Column(qa0, dtype=np.bool, name='QA0')
dr1col = Column(dr1, dtype=np.bool, name='DR1')
t.replace_column('QA0', qa0col)
t.replace_column('DR1', dr1col)
for row in t:
if (('Map' in row['Scan Type'])
and ('science' in row['Source Type'])
and (row['QA0'])):
try:
first = int(row['First Row Mapped'])
last = int(row['Last Row Mapped'])
except:
print(row)
validateScanNumbers(t)
return(t)
| gpl-3.0 | -1,150,071,409,156,291,300 | 37.153846 | 178 | 0.585829 | false |
drepetto/chiplotle | chiplotle/geometry/core/test/test_coordinate_sub.py | 1 | 1252 | from chiplotle import *
from py.test import raises
def test_coordinate__sub__01( ):
'''Coordinate pair can substract with other coordinate pairs.'''
a = Coordinate(1, 2)
b = Coordinate(0.5, 0.5)
t = a - b
assert isinstance(t, Coordinate)
assert t == Coordinate(0.5, 1.5)
def test_coordinate__sub__02( ):
'''Coordinate pair cannot substract a tuple.'''
a = Coordinate(1, 2)
assert raises(TypeError, 'a - (0.5, 0.5)')
def test_coordinate__rsub__02( ):
'''A tuple cannot substract a Coordinate.'''
a = Coordinate(1, 2)
assert raises(TypeError, '(0.5, 0.5) - a')
def test_coordinate__sub__03( ):
'''An int cannot be substracted from a Coordinate.'''
a = Coordinate(1, 2)
assert raises(TypeError, 'a - 1')
def test_coordinate__rsub__03( ):
'''A Coordinate cannot be substracted from an int.'''
a = Coordinate(1, 2)
assert raises(TypeError, '1 - a')
def test_coordinate__sub__04( ):
'''An float cannot be substracted from a Coordinate.'''
a = Coordinate(1, 2)
assert raises(TypeError, 't = a - 1.5')
def test_coordinate__rsub__04( ):
'''A Coordinate cannot be substracted from a float.'''
a = Coordinate(1, 2)
assert raises(TypeError, 't = 1.5 - a')
| gpl-3.0 | 3,723,885,013,193,829,400 | 26.822222 | 68 | 0.622204 | false |
ONSdigital/eq-survey-runner | app/forms/questionnaire_form.py | 1 | 14494 | import itertools
import logging
from datetime import datetime, timedelta
from decimal import Decimal
from dateutil.relativedelta import relativedelta
from flask_wtf import FlaskForm
from werkzeug.datastructures import MultiDict
from wtforms import validators
from app.forms.date_form import get_dates_for_single_date_period_validation
from app.forms.fields import get_field
from app.templating.utils import get_question_title
from app.validation.validators import DateRangeCheck, SumCheck, MutuallyExclusiveCheck
logger = logging.getLogger(__name__)
class QuestionnaireForm(FlaskForm):
def __init__(self, schema, block_json, answer_store, metadata, **kwargs):
self.schema = schema
self.block_json = block_json
self.answer_store = answer_store
self.metadata = metadata
self.question_errors = {}
self.options_with_detail_answer = {}
super().__init__(**kwargs)
def validate(self):
"""
Validate this form as usual and check for any form-level validation errors based on question type
:return: boolean
"""
valid_fields = FlaskForm.validate(self)
valid_date_range_form = True
valid_calculated_form = True
valid_mutually_exclusive_form = True
for question in self.schema.get_questions_for_block(self.block_json):
if question['type'] == 'DateRange' and valid_date_range_form:
valid_date_range_form = self.validate_date_range_question(question)
elif question['type'] == 'Calculated' and valid_calculated_form:
valid_calculated_form = self.validate_calculated_question(question)
elif question['type'] == 'MutuallyExclusive' and valid_mutually_exclusive_form and valid_fields:
valid_mutually_exclusive_form = self.validate_mutually_exclusive_question(question)
return valid_fields and valid_date_range_form and valid_calculated_form and valid_mutually_exclusive_form
def validate_date_range_question(self, question):
date_from = question['answers'][0]
date_to = question['answers'][1]
if self._has_min_and_max_single_dates(date_from, date_to):
# Work out the largest possible range, for date range question
period_range = self._get_period_range_for_single_date(date_from, date_to)
if 'period_limits' in question:
self.validate_date_range_with_period_limits_and_single_date_limits(question['id'],
question['period_limits'],
period_range)
else:
# Check every field on each form has populated data
if self.is_date_form_populated(getattr(self, date_from['id']), getattr(self, date_to['id'])):
self.validate_date_range_with_single_date_limits(question['id'], period_range)
period_from_id = date_from['id']
period_to_id = date_to['id']
messages = None
if 'validation' in question:
messages = question['validation'].get('messages')
if not (
self.answers_all_valid([period_from_id, period_to_id])
and self._validate_date_range_question(question['id'], period_from_id, period_to_id, messages,
question.get('period_limits'))):
return False
return True
def validate_calculated_question(self, question):
for calculation in question['calculations']:
target_total, currency = self._get_target_total_and_currency(calculation, question)
if (self.answers_all_valid(calculation['answers_to_calculate'])
and self._validate_calculated_question(calculation, question, target_total, currency)):
# Remove any previous question errors if it passes this OR before returning True
if question['id'] in self.question_errors:
self.question_errors.pop(question['id'])
return True
return False
def validate_mutually_exclusive_question(self, question):
is_mandatory = question.get('mandatory')
messages = question['validation'].get('messages') if 'validation' in question else None
answers = (getattr(self, answer['id']).data for answer in question['answers'])
validator = MutuallyExclusiveCheck(messages=messages)
try:
validator(answers, is_mandatory)
except validators.ValidationError as e:
self.question_errors[question['id']] = str(e)
return False
return True
def _get_target_total_and_currency(self, calculation, question):
if 'value' in calculation:
return calculation['value'], question.get('currency')
target_answer = self.schema.get_answer(calculation['answer_id'])
return self.answer_store.filter(answer_ids=[target_answer['id']]).values()[0], target_answer.get('currency')
def validate_date_range_with_period_limits_and_single_date_limits(self, question_id, period_limits, period_range):
# Get period_limits from question
period_min = self._get_period_limits(period_limits)[0]
min_offset = self._get_offset_value(period_min)
# Exception to be raised if range available is smaller than minimum range allowed
if period_min and period_range < min_offset:
exception = 'The schema has invalid period_limits for {}'.format(question_id)
raise Exception(exception)
@staticmethod
def validate_date_range_with_single_date_limits(question_id, period_range):
# Exception to be raised if range from answers are smaller than
# minimum or larger than maximum period_limits
exception = 'The schema has invalid date answer limits for {}'.format(question_id)
if period_range < timedelta(0):
raise Exception(exception)
def _validate_date_range_question(self, question_id, period_from_id, period_to_id, messages, period_limits):
period_from = getattr(self, period_from_id)
period_to = getattr(self, period_to_id)
period_min, period_max = self._get_period_limits(period_limits)
validator = DateRangeCheck(messages=messages, period_min=period_min, period_max=period_max)
# Check every field on each form has populated data
if self.is_date_form_populated(period_from, period_to):
try:
validator(self, period_from, period_to)
except validators.ValidationError as e:
self.question_errors[question_id] = str(e)
return False
return True
def _validate_calculated_question(self, calculation, question, target_total, currency):
messages = None
if 'validation' in question:
messages = question['validation'].get('messages')
validator = SumCheck(messages=messages, currency=currency)
calculation_type = self._get_calculation_type(calculation['calculation_type'])
formatted_values = self._get_formatted_calculation_values(calculation['answers_to_calculate'])
calculation_total = self._get_calculation_total(calculation_type, formatted_values)
# Validate grouped answers meet calculation_type criteria
try:
validator(self, calculation['conditions'], calculation_total, target_total)
except validators.ValidationError as e:
self.question_errors[question['id']] = str(e)
return False
return True
def _get_period_range_for_single_date(self, date_from, date_to):
from_min_period_date, from_max_period_date = get_dates_for_single_date_period_validation(date_from,
self.answer_store,
self.metadata)
to_min_period_date, to_max_period_date = get_dates_for_single_date_period_validation(date_to,
self.answer_store,
self.metadata)
min_period_date = from_min_period_date or from_max_period_date
max_period_date = to_max_period_date or to_min_period_date
# Work out the largest possible range, for date range question
period_range = max_period_date - min_period_date
return period_range
@staticmethod
def is_date_form_populated(date_from, date_to):
return all(field.data for field in itertools.chain(date_from, date_to))
@staticmethod
def _has_min_and_max_single_dates(date_from, date_to):
return ('minimum' in date_from or 'maximum' in date_from) and ('minimum' in date_to or 'maximum' in date_to)
@staticmethod
def _get_offset_value(period_object):
now = datetime.now()
delta = relativedelta(years=period_object.get('years', 0),
months=period_object.get('months', 0),
days=period_object.get('days', 0))
return now + delta - now
@staticmethod
def _get_period_limits(limits):
minimum, maximum = None, None
if limits:
if 'minimum' in limits:
minimum = limits['minimum']
if 'maximum' in limits:
maximum = limits['maximum']
return minimum, maximum
@staticmethod
def _get_calculation_type(calculation_type):
if calculation_type == 'sum':
return sum
raise Exception('Invalid calculation_type: {}'.format(calculation_type))
def _get_formatted_calculation_values(self, answers_list):
return[self.get_data(answer_id).replace(' ', '').replace(',', '') for answer_id in answers_list]
@staticmethod
def _get_calculation_total(calculation_type, values):
return calculation_type(Decimal(value or 0) for value in values)
def answers_all_valid(self, answer_id_list):
return not set(answer_id_list) & set(self.errors)
def map_errors(self):
ordered_errors = []
question_json_list = self.schema.get_questions_for_block(self.block_json)
for question_json in question_json_list:
if question_json['id'] in self.question_errors:
ordered_errors += [(question_json['id'], self.question_errors[question_json['id']])]
for answer_json in question_json['answers']:
if answer_json['id'] in self.errors:
ordered_errors += map_subfield_errors(self.errors, answer_json['id'])
if 'options' in answer_json:
ordered_errors += map_detail_answer_errors(self.errors, answer_json)
return ordered_errors
def answer_errors(self, input_id):
return [error[1] for error in self.map_errors() if input_id == error[0]]
def get_data(self, answer_id):
attr = getattr(self, answer_id)
return attr.raw_data[0] if attr.raw_data else ''
# pylint: disable=too-many-locals
def get_answer_fields(question, data, error_messages, schema, answer_store, metadata, group_instance, group_instance_id):
answer_fields = {}
for answer in question.get('answers', []):
for option in answer.get('options', []):
disable_validation = False
if 'detail_answer' in option:
detail_answer = option['detail_answer']
detail_answer_error_messages = detail_answer['validation']['messages'] if detail_answer.get('validation') else error_messages
if isinstance(data, MultiDict):
option_value_in_data = option['value'] in data.to_dict(flat=False).get(answer['id'], [])
else:
option_value_in_data = option['value'] in dict(data).get(answer['id'], [])
if not option_value_in_data:
disable_validation = True
answer_fields[detail_answer['id']] = get_field(detail_answer, detail_answer.get('label'),
detail_answer_error_messages, answer_store, metadata,
group_instance=group_instance, disable_validation=disable_validation)
name = answer.get('label') or get_question_title(question, answer_store, schema, metadata, group_instance, group_instance_id)
answer_fields[answer['id']] = get_field(answer, name, error_messages, answer_store, metadata, group_instance=group_instance)
return answer_fields
def map_subfield_errors(errors, answer_id):
subfield_errors = []
if isinstance(errors[answer_id], dict):
for error_list in errors[answer_id].values():
for error in error_list:
subfield_errors.append((answer_id, error))
else:
for error in errors[answer_id]:
subfield_errors.append((answer_id, error))
return subfield_errors
def map_detail_answer_errors(errors, answer_json):
detail_answer_errors = []
for option in answer_json['options']:
if 'detail_answer' in option and option['detail_answer']['id'] in errors:
for error in errors[option['detail_answer']['id']]:
detail_answer_errors.append((answer_json['id'], error))
return detail_answer_errors
def generate_form(schema, block_json, answer_store, metadata, group_instance, group_instance_id, data=None, formdata=None):
class DynamicForm(QuestionnaireForm):
pass
answer_fields = {}
for question in schema.get_questions_for_block(block_json):
answer_fields.update(get_answer_fields(
question,
formdata if formdata is not None else data,
schema.error_messages,
schema,
answer_store,
metadata,
group_instance,
group_instance_id,
))
for answer_id, field in answer_fields.items():
setattr(DynamicForm, answer_id, field)
if formdata:
formdata = MultiDict(formdata)
return DynamicForm(schema, block_json, answer_store, metadata, data=data, formdata=formdata)
| mit | 3,228,227,122,332,561,400 | 42.39521 | 141 | 0.613771 | false |
znick/anytask | dependencies/django-registration/registration/backends/default/__init__.py | 1 | 5257 | from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from registration import signals
from registration.forms import RegistrationForm
from registration.models import RegistrationProfile
class DefaultBackend(object):
"""
A registration backend which follows a simple workflow:
1. User signs up, inactive account is created.
2. Email is sent to user with activation link.
3. User clicks activation link, account is now active.
Using this backend requires that
* ``registration`` be listed in the ``INSTALLED_APPS`` setting
(since this backend makes use of models defined in this
application).
* The setting ``ACCOUNT_ACTIVATION_DAYS`` be supplied, specifying
(as an integer) the number of days from registration during
which a user may activate their account (after that period
expires, activation will be disallowed).
* The creation of the templates
``registration/activation_email_subject.txt`` and
``registration/activation_email.txt``, which will be used for
the activation email. See the notes for this backends
``register`` method for details regarding these templates.
Additionally, registration can be temporarily closed by adding the
setting ``REGISTRATION_OPEN`` and setting it to
``False``. Omitting this setting, or setting it to ``True``, will
be interpreted as meaning that registration is currently open and
permitted.
Internally, this is accomplished via storing an activation key in
an instance of ``registration.models.RegistrationProfile``. See
that model and its custom manager for full documentation of its
fields and supported operations.
"""
def register(self, request, **kwargs):
"""
Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied to that ``User``, containing the activation key which
will be used for this account.
An email will be sent to the supplied email address; this
email should contain an activation link. The email will be
rendered using two templates. See the documentation for
``RegistrationProfile.send_activation_email()`` for
information about these templates and the contexts provided to
them.
After the ``User`` and ``RegistrationProfile`` are created and
the activation email is sent, the signal
``registration.signals.user_registered`` will be sent, with
the new ``User`` as the keyword argument ``user`` and the
class of this backend as the sender.
"""
username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
site = get_current_site(request)
new_user = RegistrationProfile.objects.create_inactive_user(username, email,
password, site)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
def activate(self, request, activation_key):
"""
Given an an activation key, look up and activate the user
account corresponding to that key (if possible).
After successful activation, the signal
``registration.signals.user_activated`` will be sent, with the
newly activated ``User`` as the keyword argument ``user`` and
the class of this backend as the sender.
"""
activated = RegistrationProfile.objects.activate_user(activation_key)
if activated:
signals.user_activated.send(sender=self.__class__,
user=activated,
request=request)
return activated
def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:
* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.
* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.
"""
return getattr(settings, 'REGISTRATION_OPEN', True)
def get_form_class(self, request):
"""
Return the default form class used for user registration.
"""
return RegistrationForm
def post_registration_redirect(self, request, user):
"""
Return the name of the URL to redirect to after successful
user registration.
"""
return ('registration_complete', (), {})
def post_activation_redirect(self, request, user):
"""
Return the name of the URL to redirect to after successful
account activation.
"""
return ('registration_activation_complete', (), {})
| mit | 2,244,696,606,943,012,000 | 37.654412 | 92 | 0.642382 | false |
dtaht/ns-3-dev-old | src/lte/bindings/modulegen__gcc_ILP32.py | 1 | 805098 | 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.lte', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## address.h (module 'network'): ns3::Address [class]
module.add_class('Address', import_from_module='ns.network')
## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration]
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
## eps-bearer.h (module 'lte'): ns3::AllocationRetentionPriority [struct]
module.add_class('AllocationRetentionPriority')
## 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'])
## spectrum-model.h (module 'spectrum'): ns3::BandInfo [struct]
module.add_class('BandInfo', import_from_module='ns.spectrum')
## 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'])
## lte-common.h (module 'lte'): ns3::BufferSizeLevelBsr [class]
module.add_class('BufferSizeLevelBsr')
## 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')
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback [class]
module.add_class('DataOutputCallback', allow_subclassing=True, import_from_module='ns.stats')
## data-rate.h (module 'network'): ns3::DataRate [class]
module.add_class('DataRate', import_from_module='ns.network')
## eps-bearer.h (module 'lte'): ns3::EpsBearer [struct]
module.add_class('EpsBearer')
## eps-bearer.h (module 'lte'): ns3::EpsBearer::Qci [enumeration]
module.add_enum('Qci', ['GBR_CONV_VOICE', 'GBR_CONV_VIDEO', 'GBR_GAMING', 'GBR_NON_CONV_VIDEO', 'NGBR_IMS', 'NGBR_VIDEO_TCP_OPERATOR', 'NGBR_VOICE_VIDEO_GAMING', 'NGBR_VIDEO_TCP_PREMIUM', 'NGBR_VIDEO_TCP_DEFAULT'], outer_class=root_module['ns3::EpsBearer'])
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId', import_from_module='ns.core')
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider [class]
module.add_class('FfMacCschedSapProvider', allow_subclassing=True)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters [struct]
module.add_class('CschedCellConfigReqParameters', outer_class=root_module['ns3::FfMacCschedSapProvider'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::HoppingMode_e [enumeration]
module.add_enum('HoppingMode_e', ['inter', 'interintra'], outer_class=root_module['ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::PhichResource_e [enumeration]
module.add_enum('PhichResource_e', ['PHICH_R_ONE_SIXTH', 'PHICH_R_HALF', 'PHICH_R_ONE', 'PHICH_R_TWO'], outer_class=root_module['ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::DuplexMode_e [enumeration]
module.add_enum('DuplexMode_e', ['DM_TDD', 'DM_FDD'], outer_class=root_module['ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::Enable64Qam_e [enumeration]
module.add_enum('Enable64Qam_e', ['MOD_16QAM', 'MOD_64QAM'], outer_class=root_module['ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters [struct]
module.add_class('CschedLcConfigReqParameters', outer_class=root_module['ns3::FfMacCschedSapProvider'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters [struct]
module.add_class('CschedLcReleaseReqParameters', outer_class=root_module['ns3::FfMacCschedSapProvider'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters [struct]
module.add_class('CschedUeConfigReqParameters', outer_class=root_module['ns3::FfMacCschedSapProvider'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::MeasGapConfigPattern_e [enumeration]
module.add_enum('MeasGapConfigPattern_e', ['MGP_GP1', 'MGP_GP2', 'OFF'], outer_class=root_module['ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::OpenClosedLoop_e [enumeration]
module.add_enum('OpenClosedLoop_e', ['noneloop', 'openloop', 'closedloop'], outer_class=root_module['ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::RepMode_e [enumeration]
module.add_enum('RepMode_e', ['rm12', 'rm20', 'rm22', 'rm30', 'rm31', 'nonemode'], outer_class=root_module['ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::FeedbackMode_e [enumeration]
module.add_enum('FeedbackMode_e', ['bundling', 'multiplexing'], outer_class=root_module['ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters [struct]
module.add_class('CschedUeReleaseReqParameters', outer_class=root_module['ns3::FfMacCschedSapProvider'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser [class]
module.add_class('FfMacCschedSapUser', allow_subclassing=True)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters [struct]
module.add_class('CschedCellConfigCnfParameters', outer_class=root_module['ns3::FfMacCschedSapUser'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters [struct]
module.add_class('CschedCellConfigUpdateIndParameters', outer_class=root_module['ns3::FfMacCschedSapUser'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters [struct]
module.add_class('CschedLcConfigCnfParameters', outer_class=root_module['ns3::FfMacCschedSapUser'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters [struct]
module.add_class('CschedLcReleaseCnfParameters', outer_class=root_module['ns3::FfMacCschedSapUser'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters [struct]
module.add_class('CschedUeConfigCnfParameters', outer_class=root_module['ns3::FfMacCschedSapUser'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters [struct]
module.add_class('CschedUeConfigUpdateIndParameters', outer_class=root_module['ns3::FfMacCschedSapUser'])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters [struct]
module.add_class('CschedUeReleaseCnfParameters', outer_class=root_module['ns3::FfMacCschedSapUser'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider [class]
module.add_class('FfMacSchedSapProvider', allow_subclassing=True)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters [struct]
module.add_class('SchedDlCqiInfoReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters [struct]
module.add_class('SchedDlMacBufferReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters [struct]
module.add_class('SchedDlPagingBufferReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters [struct]
module.add_class('SchedDlRachInfoReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters [struct]
module.add_class('SchedDlRlcBufferReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters [struct]
module.add_class('SchedDlTriggerReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters [struct]
module.add_class('SchedUlCqiInfoReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters [struct]
module.add_class('SchedUlMacCtrlInfoReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters [struct]
module.add_class('SchedUlNoiseInterferenceReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters [struct]
module.add_class('SchedUlSrInfoReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters [struct]
module.add_class('SchedUlTriggerReqParameters', outer_class=root_module['ns3::FfMacSchedSapProvider'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser [class]
module.add_class('FfMacSchedSapUser', allow_subclassing=True)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedDlConfigIndParameters [struct]
module.add_class('SchedDlConfigIndParameters', outer_class=root_module['ns3::FfMacSchedSapUser'])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedUlConfigIndParameters [struct]
module.add_class('SchedUlConfigIndParameters', outer_class=root_module['ns3::FfMacSchedSapUser'])
## eps-bearer.h (module 'lte'): ns3::GbrQosInformation [struct]
module.add_class('GbrQosInformation')
## lte-common.h (module 'lte'): ns3::ImsiLcidPair_t [struct]
module.add_class('ImsiLcidPair_t')
## int-to-type.h (module 'core'): ns3::IntToType<0> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0'])
## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<1> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1'])
## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<2> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2'])
## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<3> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3'])
## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<4> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4'])
## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<5> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5'])
## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<6> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6'])
## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address', import_from_module='ns.network')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper [class]
module.add_class('Ipv4AddressHelper', import_from_module='ns.internet')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class]
module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration]
module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet')
## ipv4-interface-container.h (module 'internet'): ns3::Ipv4InterfaceContainer [class]
module.add_class('Ipv4InterfaceContainer', import_from_module='ns.internet')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress [class]
module.add_class('Ipv6InterfaceAddress', import_from_module='ns.internet')
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e [enumeration]
module.add_enum('State_e', ['TENTATIVE', 'DEPRECATED', 'PREFERRED', 'PERMANENT', 'HOMEADDRESS', 'TENTATIVE_OPTIMISTIC', 'INVALID'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet')
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e [enumeration]
module.add_enum('Scope_e', ['HOST', 'LINKLOCAL', 'GLOBAL'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class]
module.add_class('Ipv6Prefix', import_from_module='ns.network')
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider [class]
module.add_class('LteEnbCmacSapProvider', allow_subclassing=True)
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo [struct]
module.add_class('LcInfo', outer_class=root_module['ns3::LteEnbCmacSapProvider'])
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapUser [class]
module.add_class('LteEnbCmacSapUser', allow_subclassing=True)
## lte-enb-phy-sap.h (module 'lte'): ns3::LteEnbPhySapProvider [class]
module.add_class('LteEnbPhySapProvider', allow_subclassing=True)
## lte-enb-phy-sap.h (module 'lte'): ns3::LteEnbPhySapUser [class]
module.add_class('LteEnbPhySapUser', allow_subclassing=True)
## lte-common.h (module 'lte'): ns3::LteFfConverter [class]
module.add_class('LteFfConverter')
## lte-common.h (module 'lte'): ns3::LteFlowId_t [struct]
module.add_class('LteFlowId_t')
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider [class]
module.add_class('LteMacSapProvider', allow_subclassing=True)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters [struct]
module.add_class('ReportBufferStatusParameters', outer_class=root_module['ns3::LteMacSapProvider'])
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::TransmitPduParameters [struct]
module.add_class('TransmitPduParameters', outer_class=root_module['ns3::LteMacSapProvider'])
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapUser [class]
module.add_class('LteMacSapUser', allow_subclassing=True)
## lte-mi-error-model.h (module 'lte'): ns3::LteMiErrorModel [class]
module.add_class('LteMiErrorModel')
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapProvider [class]
module.add_class('LtePdcpSapProvider', allow_subclassing=True)
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapProvider::TransmitRrcPduParameters [struct]
module.add_class('TransmitRrcPduParameters', outer_class=root_module['ns3::LtePdcpSapProvider'])
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapUser [class]
module.add_class('LtePdcpSapUser', allow_subclassing=True)
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapUser::ReceiveRrcPduParameters [struct]
module.add_class('ReceiveRrcPduParameters', outer_class=root_module['ns3::LtePdcpSapUser'])
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapProvider [class]
module.add_class('LteRlcSapProvider', allow_subclassing=True)
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapProvider::TransmitPdcpPduParameters [struct]
module.add_class('TransmitPdcpPduParameters', outer_class=root_module['ns3::LteRlcSapProvider'])
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapUser [class]
module.add_class('LteRlcSapUser', allow_subclassing=True)
## lte-spectrum-value-helper.h (module 'lte'): ns3::LteSpectrumValueHelper [class]
module.add_class('LteSpectrumValueHelper')
## lte-ue-cmac-sap.h (module 'lte'): ns3::LteUeCmacSapProvider [class]
module.add_class('LteUeCmacSapProvider', allow_subclassing=True)
## lte-ue-cmac-sap.h (module 'lte'): ns3::LteUeCmacSapUser [class]
module.add_class('LteUeCmacSapUser', allow_subclassing=True)
## lte-common.h (module 'lte'): ns3::LteUeConfig_t [struct]
module.add_class('LteUeConfig_t')
## lte-ue-phy-sap.h (module 'lte'): ns3::LteUePhySapProvider [class]
module.add_class('LteUePhySapProvider', allow_subclassing=True)
## lte-ue-phy-sap.h (module 'lte'): ns3::LteUePhySapUser [class]
module.add_class('LteUePhySapUser', allow_subclassing=True)
## 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'])
## names.h (module 'core'): ns3::Names [class]
module.add_class('Names', import_from_module='ns.core')
## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class]
module.add_class('NetDeviceContainer', import_from_module='ns.network')
## node-container.h (module 'network'): ns3::NodeContainer [class]
module.add_class('NodeContainer', import_from_module='ns.network')
## object-base.h (module 'core'): ns3::ObjectBase [class]
module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core')
## object.h (module 'core'): ns3::ObjectDeleter [struct]
module.add_class('ObjectDeleter', import_from_module='ns.core')
## object-factory.h (module 'core'): ns3::ObjectFactory [class]
module.add_class('ObjectFactory', import_from_module='ns.core')
## packet-metadata.h (module 'network'): ns3::PacketMetadata [class]
module.add_class('PacketMetadata', import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration]
module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class]
module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet.h (module 'network'): ns3::PacketTagIterator [class]
module.add_class('PacketTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::PacketTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList [class]
module.add_class('PacketTagList', import_from_module='ns.network')
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct]
module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList'])
## random-variable.h (module 'core'): ns3::RandomVariable [class]
module.add_class('RandomVariable', import_from_module='ns.core')
## rng-seed-manager.h (module 'core'): ns3::RngSeedManager [class]
module.add_class('RngSeedManager', import_from_module='ns.core')
## lte-rlc-sequence-number.h (module 'lte'): ns3::SequenceNumber10 [class]
module.add_class('SequenceNumber10')
## 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')
## data-calculator.h (module 'stats'): ns3::StatisticalSummary [class]
module.add_class('StatisticalSummary', allow_subclassing=True, import_from_module='ns.stats')
## 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')
## lte-spectrum-phy.h (module 'lte'): ns3::TbId_t [struct]
module.add_class('TbId_t')
## timer.h (module 'core'): ns3::Timer [class]
module.add_class('Timer', import_from_module='ns.core')
## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration]
module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core')
## timer.h (module 'core'): ns3::Timer::State [enumeration]
module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core')
## timer-impl.h (module 'core'): ns3::TimerImpl [class]
module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core')
## lte-common.h (module 'lte'): ns3::TransmissionModesLayers [class]
module.add_class('TransmissionModesLayers')
## 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'])
## 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')
## pf-ff-mac-scheduler.h (module 'lte'): ns3::pfsFlowPerf_t [struct]
module.add_class('pfsFlowPerf_t')
## lte-spectrum-phy.h (module 'lte'): ns3::tbInfo_t [struct]
module.add_class('tbInfo_t')
## 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'])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class]
module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header'])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration]
module.add_enum('DscpType', ['DscpDefault', 'CS1', 'AF11', 'AF12', 'AF13', 'CS2', 'AF21', 'AF22', 'AF23', 'CS3', 'AF31', 'AF32', 'AF33', 'CS4', 'AF41', 'AF42', 'AF43', 'CS5', 'EF', 'CS6', 'CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet')
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration]
module.add_enum('EcnType', ['NotECT', 'ECT1', 'ECT0', 'CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet')
## ipv6-header.h (module 'internet'): ns3::Ipv6Header [class]
module.add_class('Ipv6Header', import_from_module='ns.internet', parent=root_module['ns3::Header'])
## ipv6-header.h (module 'internet'): ns3::Ipv6Header::NextHeader_e [enumeration]
module.add_enum('NextHeader_e', ['IPV6_EXT_HOP_BY_HOP', 'IPV6_IPV4', 'IPV6_TCP', 'IPV6_UDP', 'IPV6_IPV6', 'IPV6_EXT_ROUTING', 'IPV6_EXT_FRAGMENTATION', 'IPV6_EXT_CONFIDENTIALITY', 'IPV6_EXT_AUTHENTIFICATION', 'IPV6_ICMPV6', 'IPV6_EXT_END', 'IPV6_EXT_DESTINATION', 'IPV6_SCTP', 'IPV6_EXT_MOBILITY', 'IPV6_UDP_LITE'], outer_class=root_module['ns3::Ipv6Header'], import_from_module='ns.internet')
## random-variable.h (module 'core'): ns3::LogNormalVariable [class]
module.add_class('LogNormalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## lte-pdcp-header.h (module 'lte'): ns3::LtePdcpHeader [class]
module.add_class('LtePdcpHeader', parent=root_module['ns3::Header'])
## lte-pdcp-header.h (module 'lte'): ns3::LtePdcpHeader::DcBit_t [enumeration]
module.add_enum('DcBit_t', ['CONTROL_PDU', 'DATA_PDU'], outer_class=root_module['ns3::LtePdcpHeader'])
## lte-phy-tag.h (module 'lte'): ns3::LtePhyTag [class]
module.add_class('LtePhyTag', parent=root_module['ns3::Tag'])
## lte-radio-bearer-tag.h (module 'lte'): ns3::LteRadioBearerTag [class]
module.add_class('LteRadioBearerTag', parent=root_module['ns3::Tag'])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader [class]
module.add_class('LteRlcAmHeader', parent=root_module['ns3::Header'])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::DataControlPdu_t [enumeration]
module.add_enum('DataControlPdu_t', ['CONTROL_PDU', 'DATA_PDU'], outer_class=root_module['ns3::LteRlcAmHeader'])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::ControPduType_t [enumeration]
module.add_enum('ControPduType_t', ['STATUS_PDU'], outer_class=root_module['ns3::LteRlcAmHeader'])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::FramingInfoFirstByte_t [enumeration]
module.add_enum('FramingInfoFirstByte_t', ['FIRST_BYTE', 'NO_FIRST_BYTE'], outer_class=root_module['ns3::LteRlcAmHeader'])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::FramingInfoLastByte_t [enumeration]
module.add_enum('FramingInfoLastByte_t', ['LAST_BYTE', 'NO_LAST_BYTE'], outer_class=root_module['ns3::LteRlcAmHeader'])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::ExtensionBit_t [enumeration]
module.add_enum('ExtensionBit_t', ['DATA_FIELD_FOLLOWS', 'E_LI_FIELDS_FOLLOWS'], outer_class=root_module['ns3::LteRlcAmHeader'])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::ResegmentationFlag_t [enumeration]
module.add_enum('ResegmentationFlag_t', ['PDU', 'SEGMENT'], outer_class=root_module['ns3::LteRlcAmHeader'])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::PollingBit_t [enumeration]
module.add_enum('PollingBit_t', ['STATUS_REPORT_NOT_REQUESTED', 'STATUS_REPORT_IS_REQUESTED'], outer_class=root_module['ns3::LteRlcAmHeader'])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::LastSegmentFlag_t [enumeration]
module.add_enum('LastSegmentFlag_t', ['NO_LAST_PDU_SEGMENT', 'LAST_PDU_SEGMENT'], outer_class=root_module['ns3::LteRlcAmHeader'])
## lte-rlc-header.h (module 'lte'): ns3::LteRlcHeader [class]
module.add_class('LteRlcHeader', parent=root_module['ns3::Header'])
## lte-rlc-header.h (module 'lte'): ns3::LteRlcHeader::ExtensionBit_t [enumeration]
module.add_enum('ExtensionBit_t', ['DATA_FIELD_FOLLOWS', 'E_LI_FIELDS_FOLLOWS'], outer_class=root_module['ns3::LteRlcHeader'])
## lte-rlc-header.h (module 'lte'): ns3::LteRlcHeader::FramingInfoFirstByte_t [enumeration]
module.add_enum('FramingInfoFirstByte_t', ['FIRST_BYTE', 'NO_FIRST_BYTE'], outer_class=root_module['ns3::LteRlcHeader'])
## lte-rlc-header.h (module 'lte'): ns3::LteRlcHeader::FramingInfoLastByte_t [enumeration]
module.add_enum('FramingInfoLastByte_t', ['LAST_BYTE', 'NO_LAST_BYTE'], outer_class=root_module['ns3::LteRlcHeader'])
## lte-rlc-sdu-status-tag.h (module 'lte'): ns3::LteRlcSduStatusTag [class]
module.add_class('LteRlcSduStatusTag', parent=root_module['ns3::Tag'])
## lte-rlc-sdu-status-tag.h (module 'lte'): ns3::LteRlcSduStatusTag::SduStatus_t [enumeration]
module.add_enum('SduStatus_t', ['FULL_SDU', 'FIRST_SEGMENT', 'MIDDLE_SEGMENT', 'LAST_SEGMENT', 'ANY_SEGMENT'], outer_class=root_module['ns3::LteRlcSduStatusTag'])
## random-variable.h (module 'core'): ns3::NormalVariable [class]
module.add_class('NormalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable'])
## 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'])
## packet-burst.h (module 'network'): ns3::PacketBurst [class]
module.add_class('PacketBurst', import_from_module='ns.network', parent=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'])
## lte-pdcp-tag.h (module 'lte'): ns3::PdcpTag [class]
module.add_class('PdcpTag', parent=root_module['ns3::Tag'])
## radio-environment-map-helper.h (module 'lte'): ns3::RadioEnvironmentMapHelper [class]
module.add_class('RadioEnvironmentMapHelper', parent=root_module['ns3::Object'])
## lte-rlc-tag.h (module 'lte'): ns3::RlcTag [class]
module.add_class('RlcTag', parent=root_module['ns3::Tag'])
## 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::EpcTft, ns3::empty, ns3::DefaultDeleter<ns3::EpcTft> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::EpcTft', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EpcTft>'], 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::EpcTftClassifier, ns3::empty, ns3::DefaultDeleter<ns3::EpcTftClassifier> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::EpcTftClassifier', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EpcTftClassifier>'], 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::IdealControlMessage, ns3::empty, ns3::DefaultDeleter<ns3::IdealControlMessage> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::IdealControlMessage', 'ns3::empty', 'ns3::DefaultDeleter<ns3::IdealControlMessage>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::LteSinrChunkProcessor, ns3::empty, ns3::DefaultDeleter<ns3::LteSinrChunkProcessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::LteSinrChunkProcessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::LteSinrChunkProcessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::SpectrumModel', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SpectrumModel>'], 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::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::SpectrumSignalParameters', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SpectrumSignalParameters>'], 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::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::SpectrumValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SpectrumValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## socket.h (module 'network'): ns3::Socket [class]
module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object'])
## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration]
module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::Socket::SocketType [enumeration]
module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::SocketAddressTag [class]
module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpTtlTag [class]
module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class]
module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## spectrum-interference.h (module 'spectrum'): ns3::SpectrumInterference [class]
module.add_class('SpectrumInterference', import_from_module='ns.spectrum', parent=root_module['ns3::Object'])
## spectrum-model.h (module 'spectrum'): ns3::SpectrumModel [class]
module.add_class('SpectrumModel', import_from_module='ns.spectrum', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >'])
## spectrum-phy.h (module 'spectrum'): ns3::SpectrumPhy [class]
module.add_class('SpectrumPhy', import_from_module='ns.spectrum', parent=root_module['ns3::Object'])
## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::SpectrumPropagationLossModel [class]
module.add_class('SpectrumPropagationLossModel', import_from_module='ns.spectrum', parent=root_module['ns3::Object'])
## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters [struct]
module.add_class('SpectrumSignalParameters', import_from_module='ns.spectrum', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >'])
## spectrum-value.h (module 'spectrum'): ns3::SpectrumValue [class]
module.add_class('SpectrumValue', import_from_module='ns.spectrum', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >'])
## 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-fading-loss-model.h (module 'lte'): ns3::TraceFadingLossModel [class]
module.add_class('TraceFadingLossModel', parent=root_module['ns3::SpectrumPropagationLossModel'])
## 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'])
## lte-enb-rrc.h (module 'lte'): ns3::UeInfo [class]
module.add_class('UeInfo', parent=root_module['ns3::Object'])
## application.h (module 'network'): ns3::Application [class]
module.add_class('Application', import_from_module='ns.network', 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> >'])
## boolean.h (module 'core'): ns3::BooleanChecker [class]
module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## boolean.h (module 'core'): ns3::BooleanValue [class]
module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## channel.h (module 'network'): ns3::Channel [class]
module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## data-calculator.h (module 'stats'): ns3::DataCalculator [class]
module.add_class('DataCalculator', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface [class]
module.add_class('DataOutputInterface', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-rate.h (module 'network'): ns3::DataRateChecker [class]
module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## data-rate.h (module 'network'): ns3::DataRateValue [class]
module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## double.h (module 'core'): ns3::DoubleValue [class]
module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## enum.h (module 'core'): ns3::EnumChecker [class]
module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## enum.h (module 'core'): ns3::EnumValue [class]
module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## epc-enb-application.h (module 'lte'): ns3::EpcEnbApplication [class]
module.add_class('EpcEnbApplication', parent=root_module['ns3::Application'])
## epc-helper.h (module 'lte'): ns3::EpcHelper [class]
module.add_class('EpcHelper', parent=root_module['ns3::Object'])
## epc-sgw-pgw-application.h (module 'lte'): ns3::EpcSgwPgwApplication [class]
module.add_class('EpcSgwPgwApplication', parent=root_module['ns3::Application'])
## epc-tft.h (module 'lte'): ns3::EpcTft [class]
module.add_class('EpcTft', parent=root_module['ns3::SimpleRefCount< ns3::EpcTft, ns3::empty, ns3::DefaultDeleter<ns3::EpcTft> >'])
## epc-tft.h (module 'lte'): ns3::EpcTft::Direction [enumeration]
module.add_enum('Direction', ['DOWNLINK', 'UPLINK', 'BIDIRECTIONAL'], outer_class=root_module['ns3::EpcTft'])
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter [struct]
module.add_class('PacketFilter', outer_class=root_module['ns3::EpcTft'])
## epc-tft-classifier.h (module 'lte'): ns3::EpcTftClassifier [class]
module.add_class('EpcTftClassifier', parent=root_module['ns3::SimpleRefCount< ns3::EpcTftClassifier, ns3::empty, ns3::DefaultDeleter<ns3::EpcTftClassifier> >'])
## 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> >'])
## ff-mac-scheduler.h (module 'lte'): ns3::FfMacScheduler [class]
module.add_class('FfMacScheduler', parent=root_module['ns3::Object'])
## epc-gtpu-header.h (module 'lte'): ns3::GtpuHeader [class]
module.add_class('GtpuHeader', parent=root_module['ns3::Header'])
## ideal-control-messages.h (module 'lte'): ns3::IdealControlMessage [class]
module.add_class('IdealControlMessage', parent=root_module['ns3::SimpleRefCount< ns3::IdealControlMessage, ns3::empty, ns3::DefaultDeleter<ns3::IdealControlMessage> >'])
## ideal-control-messages.h (module 'lte'): ns3::IdealControlMessage::MessageType [enumeration]
module.add_enum('MessageType', ['CQI_FEEDBACKS', 'ALLOCATION_MAP', 'DL_DCI', 'UL_DCI', 'DL_CQI', 'UL_CQI', 'BSR'], outer_class=root_module['ns3::IdealControlMessage'])
## integer.h (module 'core'): ns3::IntegerValue [class]
module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol [class]
module.add_class('IpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus [enumeration]
module.add_enum('RxStatus', ['RX_OK', 'RX_CSUM_FAILED', 'RX_ENDPOINT_CLOSED', 'RX_ENDPOINT_UNREACH'], outer_class=root_module['ns3::IpL4Protocol'], import_from_module='ns.internet')
## ipv4.h (module 'internet'): ns3::Ipv4 [class]
module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class]
module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class]
module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class]
module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class]
module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class]
module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >'])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class]
module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class]
module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class]
module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface [class]
module.add_class('Ipv6Interface', import_from_module='ns.internet', parent=root_module['ns3::Object'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class]
module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class]
module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## lte-amc.h (module 'lte'): ns3::LteAmc [class]
module.add_class('LteAmc', parent=root_module['ns3::Object'])
## lte-amc.h (module 'lte'): ns3::LteAmc::AmcModel [enumeration]
module.add_enum('AmcModel', ['PiroEW2010', 'MiErrorModel'], outer_class=root_module['ns3::LteAmc'])
## lte-enb-mac.h (module 'lte'): ns3::LteEnbMac [class]
module.add_class('LteEnbMac', parent=root_module['ns3::Object'])
## lte-enb-rrc.h (module 'lte'): ns3::LteEnbRrc [class]
module.add_class('LteEnbRrc', parent=root_module['ns3::Object'])
## lte-helper.h (module 'lte'): ns3::LteHelper [class]
module.add_class('LteHelper', parent=root_module['ns3::Object'])
## lte-helper.h (module 'lte'): ns3::LteHelper::LteEpsBearerToRlcMapping_t [enumeration]
module.add_enum('LteEpsBearerToRlcMapping_t', ['RLC_SM_ALWAYS', 'RLC_UM_ALWAYS', 'RLC_AM_ALWAYS', 'PER_BASED'], outer_class=root_module['ns3::LteHelper'])
## lte-hex-grid-enb-topology-helper.h (module 'lte'): ns3::LteHexGridEnbTopologyHelper [class]
module.add_class('LteHexGridEnbTopologyHelper', parent=root_module['ns3::Object'])
## lte-interference.h (module 'lte'): ns3::LteInterference [class]
module.add_class('LteInterference', parent=root_module['ns3::Object'])
## lte-pdcp.h (module 'lte'): ns3::LtePdcp [class]
module.add_class('LtePdcp', parent=root_module['ns3::Object'])
## lte-phy.h (module 'lte'): ns3::LtePhy [class]
module.add_class('LtePhy', parent=root_module['ns3::Object'])
## lte-radio-bearer-info.h (module 'lte'): ns3::LteRadioBearerInfo [class]
module.add_class('LteRadioBearerInfo', parent=root_module['ns3::Object'])
## lte-rlc.h (module 'lte'): ns3::LteRlc [class]
module.add_class('LteRlc', parent=root_module['ns3::Object'])
## lte-rlc-am.h (module 'lte'): ns3::LteRlcAm [class]
module.add_class('LteRlcAm', parent=root_module['ns3::LteRlc'])
## lte-rlc.h (module 'lte'): ns3::LteRlcSm [class]
module.add_class('LteRlcSm', parent=root_module['ns3::LteRlc'])
## lte-rlc-um.h (module 'lte'): ns3::LteRlcUm [class]
module.add_class('LteRlcUm', parent=root_module['ns3::LteRlc'])
## lte-sinr-chunk-processor.h (module 'lte'): ns3::LteSinrChunkProcessor [class]
module.add_class('LteSinrChunkProcessor', parent=root_module['ns3::SimpleRefCount< ns3::LteSinrChunkProcessor, ns3::empty, ns3::DefaultDeleter<ns3::LteSinrChunkProcessor> >'])
## lte-spectrum-phy.h (module 'lte'): ns3::LteSpectrumPhy [class]
module.add_class('LteSpectrumPhy', parent=root_module['ns3::SpectrumPhy'])
## lte-spectrum-phy.h (module 'lte'): ns3::LteSpectrumPhy::State [enumeration]
module.add_enum('State', ['IDLE', 'TX', 'RX'], outer_class=root_module['ns3::LteSpectrumPhy'])
## lte-spectrum-signal-parameters.h (module 'lte'): ns3::LteSpectrumSignalParameters [struct]
module.add_class('LteSpectrumSignalParameters', parent=root_module['ns3::SpectrumSignalParameters'])
## lte-stats-calculator.h (module 'lte'): ns3::LteStatsCalculator [class]
module.add_class('LteStatsCalculator', parent=root_module['ns3::Object'])
## lte-ue-mac.h (module 'lte'): ns3::LteUeMac [class]
module.add_class('LteUeMac', parent=root_module['ns3::Object'])
## lte-ue-phy.h (module 'lte'): ns3::LteUePhy [class]
module.add_class('LteUePhy', parent=root_module['ns3::LtePhy'])
## lte-ue-rrc.h (module 'lte'): ns3::LteUeRrc [class]
module.add_class('LteUeRrc', parent=root_module['ns3::Object'])
## 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-stats-calculator.h (module 'lte'): ns3::MacStatsCalculator [class]
module.add_class('MacStatsCalculator', parent=root_module['ns3::LteStatsCalculator'])
## mobility-model.h (module 'mobility'): ns3::MobilityModel [class]
module.add_class('MobilityModel', import_from_module='ns.mobility', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration]
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
## 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'])
## 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> >'])
## pf-ff-mac-scheduler.h (module 'lte'): ns3::PfFfMacScheduler [class]
module.add_class('PfFfMacScheduler', parent=root_module['ns3::FfMacScheduler'])
## pointer.h (module 'core'): ns3::PointerChecker [class]
module.add_class('PointerChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## pointer.h (module 'core'): ns3::PointerValue [class]
module.add_class('PointerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## radio-bearer-stats-calculator.h (module 'lte'): ns3::RadioBearerStatsCalculator [class]
module.add_class('RadioBearerStatsCalculator', parent=root_module['ns3::LteStatsCalculator'])
## 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'])
## rem-spectrum-phy.h (module 'lte'): ns3::RemSpectrumPhy [class]
module.add_class('RemSpectrumPhy', parent=root_module['ns3::SpectrumPhy'])
## rr-ff-mac-scheduler.h (module 'lte'): ns3::RrFfMacScheduler [class]
module.add_class('RrFfMacScheduler', parent=root_module['ns3::FfMacScheduler'])
## spectrum-channel.h (module 'spectrum'): ns3::SpectrumChannel [class]
module.add_class('SpectrumChannel', import_from_module='ns.spectrum', parent=root_module['ns3::Channel'])
## string.h (module 'core'): ns3::StringChecker [class]
module.add_class('StringChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## string.h (module 'core'): ns3::StringValue [class]
module.add_class('StringValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## 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'])
## ideal-control-messages.h (module 'lte'): ns3::UlDciIdealControlMessage [class]
module.add_class('UlDciIdealControlMessage', parent=root_module['ns3::IdealControlMessage'])
## 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'])
## virtual-net-device.h (module 'virtual-net-device'): ns3::VirtualNetDevice [class]
module.add_class('VirtualNetDevice', import_from_module='ns.virtual_net_device', parent=root_module['ns3::NetDevice'])
## 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'])
## ideal-control-messages.h (module 'lte'): ns3::BsrIdealControlMessage [class]
module.add_class('BsrIdealControlMessage', parent=root_module['ns3::IdealControlMessage'])
## ideal-control-messages.h (module 'lte'): ns3::DlCqiIdealControlMessage [class]
module.add_class('DlCqiIdealControlMessage', parent=root_module['ns3::IdealControlMessage'])
## ideal-control-messages.h (module 'lte'): ns3::DlDciIdealControlMessage [class]
module.add_class('DlDciIdealControlMessage', parent=root_module['ns3::IdealControlMessage'])
## lte-sinr-chunk-processor.h (module 'lte'): ns3::LteCqiSinrChunkProcessor [class]
module.add_class('LteCqiSinrChunkProcessor', parent=root_module['ns3::LteSinrChunkProcessor'])
## lte-enb-phy.h (module 'lte'): ns3::LteEnbPhy [class]
module.add_class('LteEnbPhy', parent=root_module['ns3::LtePhy'])
## lte-net-device.h (module 'lte'): ns3::LteNetDevice [class]
module.add_class('LteNetDevice', parent=root_module['ns3::NetDevice'])
## lte-sinr-chunk-processor.h (module 'lte'): ns3::LtePemSinrChunkProcessor [class]
module.add_class('LtePemSinrChunkProcessor', parent=root_module['ns3::LteSinrChunkProcessor'])
## lte-ue-net-device.h (module 'lte'): ns3::LteUeNetDevice [class]
module.add_class('LteUeNetDevice', parent=root_module['ns3::LteNetDevice'])
## lte-enb-net-device.h (module 'lte'): ns3::LteEnbNetDevice [class]
module.add_class('LteEnbNetDevice', parent=root_module['ns3::LteNetDevice'])
module.add_container('std::vector< unsigned char >', 'unsigned char', container_type='vector')
module.add_container('std::vector< VendorSpecificListElement_s >', 'VendorSpecificListElement_s', container_type='vector')
module.add_container('std::vector< LogicalChannelConfigListElement_s >', 'LogicalChannelConfigListElement_s', container_type='vector')
module.add_container('std::vector< PagingInfoListElement_s >', 'PagingInfoListElement_s', container_type='vector')
module.add_container('std::vector< DlInfoListElement_s >', 'DlInfoListElement_s', container_type='vector')
module.add_container('std::vector< RachListElement_s >', 'RachListElement_s', container_type='vector')
module.add_container('std::vector< CqiListElement_s >', 'CqiListElement_s', container_type='vector')
module.add_container('std::vector< UlInfoListElement_s >', 'UlInfoListElement_s', container_type='vector')
module.add_container('std::vector< SrListElement_s >', 'SrListElement_s', container_type='vector')
module.add_container('std::vector< MacCeListElement_s >', 'MacCeListElement_s', container_type='vector')
module.add_container('std::vector< BuildDataListElement_s >', 'BuildDataListElement_s', container_type='vector')
module.add_container('std::vector< BuildRarListElement_s >', 'BuildRarListElement_s', container_type='vector')
module.add_container('std::vector< BuildBroadcastListElement_s >', 'BuildBroadcastListElement_s', container_type='vector')
module.add_container('std::vector< UlDciListElement_s >', 'UlDciListElement_s', container_type='vector')
module.add_container('std::vector< PhichListElement_s >', 'PhichListElement_s', container_type='vector')
module.add_container('std::vector< int >', 'int', container_type='vector')
module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type='list')
module.add_container('std::vector< double >', 'double', container_type='vector')
module.add_container('ns3::Bands', 'ns3::BandInfo', container_type='vector')
module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map')
module.add_container('std::map< unsigned short, ns3::Ptr< ns3::UeInfo > >', ('short unsigned int', 'ns3::Ptr< ns3::UeInfo >'), container_type='map')
module.add_container('std::list< ns3::Ptr< ns3::IdealControlMessage > >', 'ns3::Ptr< ns3::IdealControlMessage >', container_type='list')
module.add_container('std::list< ns3::UlDciIdealControlMessage >', 'ns3::UlDciIdealControlMessage', container_type='list')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, unsigned long long, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, unsigned long long > > >', 'ns3::Uint64Map')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, unsigned long long, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, unsigned long long > > >*', 'ns3::Uint64Map*')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, unsigned long long, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, unsigned long long > > >&', 'ns3::Uint64Map&')
typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyTxEndCallback')
typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyTxEndCallback*')
typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyTxEndCallback&')
typehandlers.add_type_alias('ns3::RngSeedManager', 'ns3::SeedManager')
typehandlers.add_type_alias('ns3::RngSeedManager*', 'ns3::SeedManager*')
typehandlers.add_type_alias('ns3::RngSeedManager&', 'ns3::SeedManager&')
module.add_typedef(root_module['ns3::RngSeedManager'], 'SeedManager')
typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyRxStartCallback')
typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyRxStartCallback*')
typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyRxStartCallback&')
typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyRxEndErrorCallback')
typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyRxEndErrorCallback*')
typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyRxEndErrorCallback&')
typehandlers.add_type_alias('std::vector< double, std::allocator< double > >', 'ns3::Values')
typehandlers.add_type_alias('std::vector< double, std::allocator< double > >*', 'ns3::Values*')
typehandlers.add_type_alias('std::vector< double, std::allocator< double > >&', 'ns3::Values&')
typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyTxStartCallback')
typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyTxStartCallback*')
typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyTxStartCallback&')
typehandlers.add_type_alias('std::vector< ns3::BandInfo, std::allocator< ns3::BandInfo > >', 'ns3::Bands')
typehandlers.add_type_alias('std::vector< ns3::BandInfo, std::allocator< ns3::BandInfo > >*', 'ns3::Bands*')
typehandlers.add_type_alias('std::vector< ns3::BandInfo, std::allocator< ns3::BandInfo > >&', 'ns3::Bands&')
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('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('uint32_t', 'ns3::SpectrumModelUid_t')
typehandlers.add_type_alias('uint32_t*', 'ns3::SpectrumModelUid_t*')
typehandlers.add_type_alias('uint32_t&', 'ns3::SpectrumModelUid_t&')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, unsigned int, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, unsigned int > > >', 'ns3::Uint32Map')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, unsigned int, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, unsigned int > > >*', 'ns3::Uint32Map*')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, unsigned int, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, unsigned int > > >&', 'ns3::Uint32Map&')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, double, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, double > > >', 'ns3::DoubleMap')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, double, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, double > > >*', 'ns3::DoubleMap*')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, double, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, double > > >&', 'ns3::DoubleMap&')
typehandlers.add_type_alias('std::map< ns3::TbId_t, ns3::tbInfo_t, std::less< ns3::TbId_t >, std::allocator< std::pair< ns3::TbId_t const, ns3::tbInfo_t > > >', 'ns3::expectedTbs_t')
typehandlers.add_type_alias('std::map< ns3::TbId_t, ns3::tbInfo_t, std::less< ns3::TbId_t >, std::allocator< std::pair< ns3::TbId_t const, ns3::tbInfo_t > > >*', 'ns3::expectedTbs_t*')
typehandlers.add_type_alias('std::map< ns3::TbId_t, ns3::tbInfo_t, std::less< ns3::TbId_t >, std::allocator< std::pair< ns3::TbId_t const, ns3::tbInfo_t > > >&', 'ns3::expectedTbs_t&')
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')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, ns3::LteFlowId_t, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, ns3::LteFlowId_t > > >', 'ns3::FlowIdMap')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, ns3::LteFlowId_t, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, ns3::LteFlowId_t > > >*', 'ns3::FlowIdMap*')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, ns3::LteFlowId_t, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, ns3::LteFlowId_t > > >&', 'ns3::FlowIdMap&')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned int > >, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned int > > > > >', 'ns3::Uint32StatsMap')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned int > >, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned int > > > > >*', 'ns3::Uint32StatsMap*')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned int > >, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned int > > > > >&', 'ns3::Uint32StatsMap&')
typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyRxEndOkCallback')
typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyRxEndOkCallback*')
typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyRxEndOkCallback&')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned long long > >, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned long long > > > > >', 'ns3::Uint64StatsMap')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned long long > >, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned long long > > > > >*', 'ns3::Uint64StatsMap*')
typehandlers.add_type_alias('std::map< ns3::ImsiLcidPair_t, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned long long > >, std::less< ns3::ImsiLcidPair_t >, std::allocator< std::pair< ns3::ImsiLcidPair_t const, ns3::Ptr< ns3::MinMaxAvgTotalCalculator< unsigned long long > > > > >&', 'ns3::Uint64StatsMap&')
## Register a nested module for the namespace Config
nested_module = module.add_cpp_namespace('Config')
register_types_ns3_Config(nested_module)
## 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_Config(module):
root_module = module.get_root()
## config.h (module 'core'): ns3::Config::MatchContainer [class]
module.add_class('MatchContainer', import_from_module='ns.core')
module.add_container('std::vector< ns3::Ptr< ns3::Object > >', 'ns3::Ptr< ns3::Object >', container_type='vector')
module.add_container('std::vector< std::string >', 'std::string', container_type='vector')
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_Ns3AllocationRetentionPriority_methods(root_module, root_module['ns3::AllocationRetentionPriority'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3BandInfo_methods(root_module, root_module['ns3::BandInfo'])
register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer'])
register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator'])
register_Ns3BufferSizeLevelBsr_methods(root_module, root_module['ns3::BufferSizeLevelBsr'])
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_Ns3DataOutputCallback_methods(root_module, root_module['ns3::DataOutputCallback'])
register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate'])
register_Ns3EpsBearer_methods(root_module, root_module['ns3::EpsBearer'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3FfMacCschedSapProvider_methods(root_module, root_module['ns3::FfMacCschedSapProvider'])
register_Ns3FfMacCschedSapProviderCschedCellConfigReqParameters_methods(root_module, root_module['ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters'])
register_Ns3FfMacCschedSapProviderCschedLcConfigReqParameters_methods(root_module, root_module['ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters'])
register_Ns3FfMacCschedSapProviderCschedLcReleaseReqParameters_methods(root_module, root_module['ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters'])
register_Ns3FfMacCschedSapProviderCschedUeConfigReqParameters_methods(root_module, root_module['ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters'])
register_Ns3FfMacCschedSapProviderCschedUeReleaseReqParameters_methods(root_module, root_module['ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters'])
register_Ns3FfMacCschedSapUser_methods(root_module, root_module['ns3::FfMacCschedSapUser'])
register_Ns3FfMacCschedSapUserCschedCellConfigCnfParameters_methods(root_module, root_module['ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters'])
register_Ns3FfMacCschedSapUserCschedCellConfigUpdateIndParameters_methods(root_module, root_module['ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters'])
register_Ns3FfMacCschedSapUserCschedLcConfigCnfParameters_methods(root_module, root_module['ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters'])
register_Ns3FfMacCschedSapUserCschedLcReleaseCnfParameters_methods(root_module, root_module['ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters'])
register_Ns3FfMacCschedSapUserCschedUeConfigCnfParameters_methods(root_module, root_module['ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters'])
register_Ns3FfMacCschedSapUserCschedUeConfigUpdateIndParameters_methods(root_module, root_module['ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters'])
register_Ns3FfMacCschedSapUserCschedUeReleaseCnfParameters_methods(root_module, root_module['ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters'])
register_Ns3FfMacSchedSapProvider_methods(root_module, root_module['ns3::FfMacSchedSapProvider'])
register_Ns3FfMacSchedSapProviderSchedDlCqiInfoReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters'])
register_Ns3FfMacSchedSapProviderSchedDlMacBufferReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters'])
register_Ns3FfMacSchedSapProviderSchedDlPagingBufferReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters'])
register_Ns3FfMacSchedSapProviderSchedDlRachInfoReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters'])
register_Ns3FfMacSchedSapProviderSchedDlRlcBufferReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters'])
register_Ns3FfMacSchedSapProviderSchedDlTriggerReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters'])
register_Ns3FfMacSchedSapProviderSchedUlCqiInfoReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters'])
register_Ns3FfMacSchedSapProviderSchedUlMacCtrlInfoReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters'])
register_Ns3FfMacSchedSapProviderSchedUlNoiseInterferenceReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters'])
register_Ns3FfMacSchedSapProviderSchedUlSrInfoReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters'])
register_Ns3FfMacSchedSapProviderSchedUlTriggerReqParameters_methods(root_module, root_module['ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters'])
register_Ns3FfMacSchedSapUser_methods(root_module, root_module['ns3::FfMacSchedSapUser'])
register_Ns3FfMacSchedSapUserSchedDlConfigIndParameters_methods(root_module, root_module['ns3::FfMacSchedSapUser::SchedDlConfigIndParameters'])
register_Ns3FfMacSchedSapUserSchedUlConfigIndParameters_methods(root_module, root_module['ns3::FfMacSchedSapUser::SchedUlConfigIndParameters'])
register_Ns3GbrQosInformation_methods(root_module, root_module['ns3::GbrQosInformation'])
register_Ns3ImsiLcidPair_t_methods(root_module, root_module['ns3::ImsiLcidPair_t'])
register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >'])
register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >'])
register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >'])
register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >'])
register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >'])
register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >'])
register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4AddressHelper_methods(root_module, root_module['ns3::Ipv4AddressHelper'])
register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress'])
register_Ns3Ipv4InterfaceContainer_methods(root_module, root_module['ns3::Ipv4InterfaceContainer'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address'])
register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress'])
register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix'])
register_Ns3LteEnbCmacSapProvider_methods(root_module, root_module['ns3::LteEnbCmacSapProvider'])
register_Ns3LteEnbCmacSapProviderLcInfo_methods(root_module, root_module['ns3::LteEnbCmacSapProvider::LcInfo'])
register_Ns3LteEnbCmacSapUser_methods(root_module, root_module['ns3::LteEnbCmacSapUser'])
register_Ns3LteEnbPhySapProvider_methods(root_module, root_module['ns3::LteEnbPhySapProvider'])
register_Ns3LteEnbPhySapUser_methods(root_module, root_module['ns3::LteEnbPhySapUser'])
register_Ns3LteFfConverter_methods(root_module, root_module['ns3::LteFfConverter'])
register_Ns3LteFlowId_t_methods(root_module, root_module['ns3::LteFlowId_t'])
register_Ns3LteMacSapProvider_methods(root_module, root_module['ns3::LteMacSapProvider'])
register_Ns3LteMacSapProviderReportBufferStatusParameters_methods(root_module, root_module['ns3::LteMacSapProvider::ReportBufferStatusParameters'])
register_Ns3LteMacSapProviderTransmitPduParameters_methods(root_module, root_module['ns3::LteMacSapProvider::TransmitPduParameters'])
register_Ns3LteMacSapUser_methods(root_module, root_module['ns3::LteMacSapUser'])
register_Ns3LteMiErrorModel_methods(root_module, root_module['ns3::LteMiErrorModel'])
register_Ns3LtePdcpSapProvider_methods(root_module, root_module['ns3::LtePdcpSapProvider'])
register_Ns3LtePdcpSapProviderTransmitRrcPduParameters_methods(root_module, root_module['ns3::LtePdcpSapProvider::TransmitRrcPduParameters'])
register_Ns3LtePdcpSapUser_methods(root_module, root_module['ns3::LtePdcpSapUser'])
register_Ns3LtePdcpSapUserReceiveRrcPduParameters_methods(root_module, root_module['ns3::LtePdcpSapUser::ReceiveRrcPduParameters'])
register_Ns3LteRlcSapProvider_methods(root_module, root_module['ns3::LteRlcSapProvider'])
register_Ns3LteRlcSapProviderTransmitPdcpPduParameters_methods(root_module, root_module['ns3::LteRlcSapProvider::TransmitPdcpPduParameters'])
register_Ns3LteRlcSapUser_methods(root_module, root_module['ns3::LteRlcSapUser'])
register_Ns3LteSpectrumValueHelper_methods(root_module, root_module['ns3::LteSpectrumValueHelper'])
register_Ns3LteUeCmacSapProvider_methods(root_module, root_module['ns3::LteUeCmacSapProvider'])
register_Ns3LteUeCmacSapUser_methods(root_module, root_module['ns3::LteUeCmacSapUser'])
register_Ns3LteUeConfig_t_methods(root_module, root_module['ns3::LteUeConfig_t'])
register_Ns3LteUePhySapProvider_methods(root_module, root_module['ns3::LteUePhySapProvider'])
register_Ns3LteUePhySapUser_methods(root_module, root_module['ns3::LteUePhySapUser'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3Names_methods(root_module, root_module['ns3::Names'])
register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata'])
register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item'])
register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3RandomVariable_methods(root_module, root_module['ns3::RandomVariable'])
register_Ns3RngSeedManager_methods(root_module, root_module['ns3::RngSeedManager'])
register_Ns3SequenceNumber10_methods(root_module, root_module['ns3::SequenceNumber10'])
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_Ns3StatisticalSummary_methods(root_module, root_module['ns3::StatisticalSummary'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3TbId_t_methods(root_module, root_module['ns3::TbId_t'])
register_Ns3Timer_methods(root_module, root_module['ns3::Timer'])
register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl'])
register_Ns3TransmissionModesLayers_methods(root_module, root_module['ns3::TransmissionModesLayers'])
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_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_Ns3PfsFlowPerf_t_methods(root_module, root_module['ns3::pfsFlowPerf_t'])
register_Ns3TbInfo_t_methods(root_module, root_module['ns3::tbInfo_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_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header'])
register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header'])
register_Ns3LogNormalVariable_methods(root_module, root_module['ns3::LogNormalVariable'])
register_Ns3LtePdcpHeader_methods(root_module, root_module['ns3::LtePdcpHeader'])
register_Ns3LtePhyTag_methods(root_module, root_module['ns3::LtePhyTag'])
register_Ns3LteRadioBearerTag_methods(root_module, root_module['ns3::LteRadioBearerTag'])
register_Ns3LteRlcAmHeader_methods(root_module, root_module['ns3::LteRlcAmHeader'])
register_Ns3LteRlcHeader_methods(root_module, root_module['ns3::LteRlcHeader'])
register_Ns3LteRlcSduStatusTag_methods(root_module, root_module['ns3::LteRlcSduStatusTag'])
register_Ns3NormalVariable_methods(root_module, root_module['ns3::NormalVariable'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3PacketBurst_methods(root_module, root_module['ns3::PacketBurst'])
register_Ns3ParetoVariable_methods(root_module, root_module['ns3::ParetoVariable'])
register_Ns3PdcpTag_methods(root_module, root_module['ns3::PdcpTag'])
register_Ns3RadioEnvironmentMapHelper_methods(root_module, root_module['ns3::RadioEnvironmentMapHelper'])
register_Ns3RlcTag_methods(root_module, root_module['ns3::RlcTag'])
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__Ns3EpcTft_Ns3Empty_Ns3DefaultDeleter__lt__ns3EpcTft__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EpcTft, ns3::empty, ns3::DefaultDeleter<ns3::EpcTft> >'])
register_Ns3SimpleRefCount__Ns3EpcTftClassifier_Ns3Empty_Ns3DefaultDeleter__lt__ns3EpcTftClassifier__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EpcTftClassifier, ns3::empty, ns3::DefaultDeleter<ns3::EpcTftClassifier> >'])
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__Ns3IdealControlMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3IdealControlMessage__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::IdealControlMessage, ns3::empty, ns3::DefaultDeleter<ns3::IdealControlMessage> >'])
register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >'])
register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >'])
register_Ns3SimpleRefCount__Ns3LteSinrChunkProcessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3LteSinrChunkProcessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::LteSinrChunkProcessor, ns3::empty, ns3::DefaultDeleter<ns3::LteSinrChunkProcessor> >'])
register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
register_Ns3SimpleRefCount__Ns3SpectrumModel_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumModel__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >'])
register_Ns3SimpleRefCount__Ns3SpectrumSignalParameters_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumSignalParameters__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >'])
register_Ns3SimpleRefCount__Ns3SpectrumValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3Socket_methods(root_module, root_module['ns3::Socket'])
register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag'])
register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag'])
register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag'])
register_Ns3SpectrumInterference_methods(root_module, root_module['ns3::SpectrumInterference'])
register_Ns3SpectrumModel_methods(root_module, root_module['ns3::SpectrumModel'])
register_Ns3SpectrumPhy_methods(root_module, root_module['ns3::SpectrumPhy'])
register_Ns3SpectrumPropagationLossModel_methods(root_module, root_module['ns3::SpectrumPropagationLossModel'])
register_Ns3SpectrumSignalParameters_methods(root_module, root_module['ns3::SpectrumSignalParameters'])
register_Ns3SpectrumValue_methods(root_module, root_module['ns3::SpectrumValue'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceFadingLossModel_methods(root_module, root_module['ns3::TraceFadingLossModel'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
register_Ns3UeInfo_methods(root_module, root_module['ns3::UeInfo'])
register_Ns3Application_methods(root_module, root_module['ns3::Application'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker'])
register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3DataCalculator_methods(root_module, root_module['ns3::DataCalculator'])
register_Ns3DataOutputInterface_methods(root_module, root_module['ns3::DataOutputInterface'])
register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker'])
register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker'])
register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue'])
register_Ns3EpcEnbApplication_methods(root_module, root_module['ns3::EpcEnbApplication'])
register_Ns3EpcHelper_methods(root_module, root_module['ns3::EpcHelper'])
register_Ns3EpcSgwPgwApplication_methods(root_module, root_module['ns3::EpcSgwPgwApplication'])
register_Ns3EpcTft_methods(root_module, root_module['ns3::EpcTft'])
register_Ns3EpcTftPacketFilter_methods(root_module, root_module['ns3::EpcTft::PacketFilter'])
register_Ns3EpcTftClassifier_methods(root_module, root_module['ns3::EpcTftClassifier'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3FfMacScheduler_methods(root_module, root_module['ns3::FfMacScheduler'])
register_Ns3GtpuHeader_methods(root_module, root_module['ns3::GtpuHeader'])
register_Ns3IdealControlMessage_methods(root_module, root_module['ns3::IdealControlMessage'])
register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue'])
register_Ns3IpL4Protocol_methods(root_module, root_module['ns3::IpL4Protocol'])
register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4'])
register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker'])
register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue'])
register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker'])
register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue'])
register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute'])
register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route'])
register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker'])
register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue'])
register_Ns3Ipv6Interface_methods(root_module, root_module['ns3::Ipv6Interface'])
register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker'])
register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue'])
register_Ns3LteAmc_methods(root_module, root_module['ns3::LteAmc'])
register_Ns3LteEnbMac_methods(root_module, root_module['ns3::LteEnbMac'])
register_Ns3LteEnbRrc_methods(root_module, root_module['ns3::LteEnbRrc'])
register_Ns3LteHelper_methods(root_module, root_module['ns3::LteHelper'])
register_Ns3LteHexGridEnbTopologyHelper_methods(root_module, root_module['ns3::LteHexGridEnbTopologyHelper'])
register_Ns3LteInterference_methods(root_module, root_module['ns3::LteInterference'])
register_Ns3LtePdcp_methods(root_module, root_module['ns3::LtePdcp'])
register_Ns3LtePhy_methods(root_module, root_module['ns3::LtePhy'])
register_Ns3LteRadioBearerInfo_methods(root_module, root_module['ns3::LteRadioBearerInfo'])
register_Ns3LteRlc_methods(root_module, root_module['ns3::LteRlc'])
register_Ns3LteRlcAm_methods(root_module, root_module['ns3::LteRlcAm'])
register_Ns3LteRlcSm_methods(root_module, root_module['ns3::LteRlcSm'])
register_Ns3LteRlcUm_methods(root_module, root_module['ns3::LteRlcUm'])
register_Ns3LteSinrChunkProcessor_methods(root_module, root_module['ns3::LteSinrChunkProcessor'])
register_Ns3LteSpectrumPhy_methods(root_module, root_module['ns3::LteSpectrumPhy'])
register_Ns3LteSpectrumSignalParameters_methods(root_module, root_module['ns3::LteSpectrumSignalParameters'])
register_Ns3LteStatsCalculator_methods(root_module, root_module['ns3::LteStatsCalculator'])
register_Ns3LteUeMac_methods(root_module, root_module['ns3::LteUeMac'])
register_Ns3LteUePhy_methods(root_module, root_module['ns3::LteUePhy'])
register_Ns3LteUeRrc_methods(root_module, root_module['ns3::LteUeRrc'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3MacStatsCalculator_methods(root_module, root_module['ns3::MacStatsCalculator'])
register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3PfFfMacScheduler_methods(root_module, root_module['ns3::PfFfMacScheduler'])
register_Ns3PointerChecker_methods(root_module, root_module['ns3::PointerChecker'])
register_Ns3PointerValue_methods(root_module, root_module['ns3::PointerValue'])
register_Ns3RadioBearerStatsCalculator_methods(root_module, root_module['ns3::RadioBearerStatsCalculator'])
register_Ns3RandomVariableChecker_methods(root_module, root_module['ns3::RandomVariableChecker'])
register_Ns3RandomVariableValue_methods(root_module, root_module['ns3::RandomVariableValue'])
register_Ns3RemSpectrumPhy_methods(root_module, root_module['ns3::RemSpectrumPhy'])
register_Ns3RrFfMacScheduler_methods(root_module, root_module['ns3::RrFfMacScheduler'])
register_Ns3SpectrumChannel_methods(root_module, root_module['ns3::SpectrumChannel'])
register_Ns3StringChecker_methods(root_module, root_module['ns3::StringChecker'])
register_Ns3StringValue_methods(root_module, root_module['ns3::StringValue'])
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_Ns3UlDciIdealControlMessage_methods(root_module, root_module['ns3::UlDciIdealControlMessage'])
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_Ns3VirtualNetDevice_methods(root_module, root_module['ns3::VirtualNetDevice'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3BsrIdealControlMessage_methods(root_module, root_module['ns3::BsrIdealControlMessage'])
register_Ns3DlCqiIdealControlMessage_methods(root_module, root_module['ns3::DlCqiIdealControlMessage'])
register_Ns3DlDciIdealControlMessage_methods(root_module, root_module['ns3::DlDciIdealControlMessage'])
register_Ns3LteCqiSinrChunkProcessor_methods(root_module, root_module['ns3::LteCqiSinrChunkProcessor'])
register_Ns3LteEnbPhy_methods(root_module, root_module['ns3::LteEnbPhy'])
register_Ns3LteNetDevice_methods(root_module, root_module['ns3::LteNetDevice'])
register_Ns3LtePemSinrChunkProcessor_methods(root_module, root_module['ns3::LtePemSinrChunkProcessor'])
register_Ns3LteUeNetDevice_methods(root_module, root_module['ns3::LteUeNetDevice'])
register_Ns3LteEnbNetDevice_methods(root_module, root_module['ns3::LteEnbNetDevice'])
register_Ns3ConfigMatchContainer_methods(root_module, root_module['ns3::Config::MatchContainer'])
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_Ns3AllocationRetentionPriority_methods(root_module, cls):
## eps-bearer.h (module 'lte'): ns3::AllocationRetentionPriority::AllocationRetentionPriority() [constructor]
cls.add_constructor([])
## eps-bearer.h (module 'lte'): ns3::AllocationRetentionPriority::AllocationRetentionPriority(ns3::AllocationRetentionPriority const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AllocationRetentionPriority const &', 'arg0')])
## eps-bearer.h (module 'lte'): ns3::AllocationRetentionPriority::preemprionCapability [variable]
cls.add_instance_attribute('preemprionCapability', 'bool', is_const=False)
## eps-bearer.h (module 'lte'): ns3::AllocationRetentionPriority::preemprionVulnerability [variable]
cls.add_instance_attribute('preemprionVulnerability', 'bool', is_const=False)
## eps-bearer.h (module 'lte'): ns3::AllocationRetentionPriority::priorityLevel [variable]
cls.add_instance_attribute('priorityLevel', 'uint8_t', is_const=False)
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_Ns3BandInfo_methods(root_module, cls):
## spectrum-model.h (module 'spectrum'): ns3::BandInfo::BandInfo() [constructor]
cls.add_constructor([])
## spectrum-model.h (module 'spectrum'): ns3::BandInfo::BandInfo(ns3::BandInfo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BandInfo const &', 'arg0')])
## spectrum-model.h (module 'spectrum'): ns3::BandInfo::fc [variable]
cls.add_instance_attribute('fc', 'double', is_const=False)
## spectrum-model.h (module 'spectrum'): ns3::BandInfo::fh [variable]
cls.add_instance_attribute('fh', 'double', is_const=False)
## spectrum-model.h (module 'spectrum'): ns3::BandInfo::fl [variable]
cls.add_instance_attribute('fl', 'double', is_const=False)
return
def register_Ns3Buffer_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor]
cls.add_constructor([param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'bool',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'bool',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function]
cls.add_method('Begin',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Buffer',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function]
cls.add_method('CreateFullCopy',
'ns3::Buffer',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function]
cls.add_method('End',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function]
cls.add_method('GetCurrentEndOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function]
cls.add_method('GetCurrentStartOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3BufferIterator_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')])
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function]
cls.add_method('GetDistanceFrom',
'uint32_t',
[param('ns3::Buffer::Iterator const &', 'o')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function]
cls.add_method('IsEnd',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function]
cls.add_method('IsStart',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function]
cls.add_method('Next',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function]
cls.add_method('Next',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function]
cls.add_method('Prev',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function]
cls.add_method('Prev',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function]
cls.add_method('ReadLsbtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function]
cls.add_method('ReadLsbtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function]
cls.add_method('ReadLsbtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function]
cls.add_method('ReadNtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function]
cls.add_method('ReadNtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function]
cls.add_method('ReadNtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Write',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function]
cls.add_method('WriteHtolsbU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function]
cls.add_method('WriteHtolsbU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function]
cls.add_method('WriteHtolsbU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function]
cls.add_method('WriteHtonU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function]
cls.add_method('WriteHtonU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function]
cls.add_method('WriteHtonU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data'), param('uint32_t', 'len')])
return
def register_Ns3BufferSizeLevelBsr_methods(root_module, cls):
## lte-common.h (module 'lte'): ns3::BufferSizeLevelBsr::BufferSizeLevelBsr() [constructor]
cls.add_constructor([])
## lte-common.h (module 'lte'): ns3::BufferSizeLevelBsr::BufferSizeLevelBsr(ns3::BufferSizeLevelBsr const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BufferSizeLevelBsr const &', 'arg0')])
## lte-common.h (module 'lte'): static uint32_t ns3::BufferSizeLevelBsr::BsrId2BufferSize(uint8_t val) [member function]
cls.add_method('BsrId2BufferSize',
'uint32_t',
[param('uint8_t', 'val')],
is_static=True)
## lte-common.h (module 'lte'): static uint8_t ns3::BufferSizeLevelBsr::BufferSize2BsrId(uint32_t val) [member function]
cls.add_method('BufferSize2BsrId',
'uint8_t',
[param('uint32_t', 'val')],
is_static=True)
## lte-common.h (module 'lte'): ns3::BufferSizeLevelBsr::m_bufferSizeLevelBsr [variable]
cls.add_static_attribute('m_bufferSizeLevelBsr', 'int [ 64 ]', is_const=False)
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_Ns3DataOutputCallback_methods(root_module, cls):
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback() [constructor]
cls.add_constructor([])
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback(ns3::DataOutputCallback const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataOutputCallback const &', 'arg0')])
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, int val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('int', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, uint32_t val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('uint32_t', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, double val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('double', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, std::string val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('std::string', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, ns3::Time val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('ns3::Time', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputStatistic(std::string key, std::string variable, ns3::StatisticalSummary const * statSum) [member function]
cls.add_method('OutputStatistic',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('ns3::StatisticalSummary const *', 'statSum')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3DataRate_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('>=')
## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRate const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor]
cls.add_constructor([param('uint64_t', 'bps')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor]
cls.add_constructor([param('std::string', 'rate')])
## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function]
cls.add_method('CalculateTxTime',
'double',
[param('uint32_t', 'bytes')],
is_const=True)
## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function]
cls.add_method('GetBitRate',
'uint64_t',
[],
is_const=True)
return
def register_Ns3EpsBearer_methods(root_module, cls):
## eps-bearer.h (module 'lte'): ns3::EpsBearer::EpsBearer(ns3::EpsBearer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EpsBearer const &', 'arg0')])
## eps-bearer.h (module 'lte'): ns3::EpsBearer::EpsBearer(ns3::EpsBearer::Qci x) [constructor]
cls.add_constructor([param('ns3::EpsBearer::Qci', 'x')])
## eps-bearer.h (module 'lte'): uint16_t ns3::EpsBearer::GetPacketDelayBudgetMs() const [member function]
cls.add_method('GetPacketDelayBudgetMs',
'uint16_t',
[],
is_const=True)
## eps-bearer.h (module 'lte'): double ns3::EpsBearer::GetPacketErrorLossRate() const [member function]
cls.add_method('GetPacketErrorLossRate',
'double',
[],
is_const=True)
## eps-bearer.h (module 'lte'): uint8_t ns3::EpsBearer::GetPriority() const [member function]
cls.add_method('GetPriority',
'uint8_t',
[],
is_const=True)
## eps-bearer.h (module 'lte'): bool ns3::EpsBearer::IsGbr() const [member function]
cls.add_method('IsGbr',
'bool',
[],
is_const=True)
## eps-bearer.h (module 'lte'): ns3::EpsBearer::arp [variable]
cls.add_instance_attribute('arp', 'ns3::AllocationRetentionPriority', is_const=False)
## eps-bearer.h (module 'lte'): ns3::EpsBearer::gbrQosInfo [variable]
cls.add_instance_attribute('gbrQosInfo', 'ns3::GbrQosInformation', is_const=False)
## eps-bearer.h (module 'lte'): ns3::EpsBearer::qci [variable]
cls.add_instance_attribute('qci', 'ns3::EpsBearer::Qci', is_const=False)
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_Ns3FfMacCschedSapProvider_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::FfMacCschedSapProvider() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::FfMacCschedSapProvider(ns3::FfMacCschedSapProvider const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapProvider const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapProvider::CschedCellConfigReq(ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters const & params) [member function]
cls.add_method('CschedCellConfigReq',
'void',
[param('ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapProvider::CschedLcConfigReq(ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters const & params) [member function]
cls.add_method('CschedLcConfigReq',
'void',
[param('ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapProvider::CschedLcReleaseReq(ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters const & params) [member function]
cls.add_method('CschedLcReleaseReq',
'void',
[param('ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapProvider::CschedUeConfigReq(ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters const & params) [member function]
cls.add_method('CschedUeConfigReq',
'void',
[param('ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapProvider::CschedUeReleaseReq(ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters const & params) [member function]
cls.add_method('CschedUeReleaseReq',
'void',
[param('ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3FfMacCschedSapProviderCschedCellConfigReqParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::CschedCellConfigReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::CschedCellConfigReqParameters(ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_antennaPortsCount [variable]
cls.add_instance_attribute('m_antennaPortsCount', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_deltaPucchShift [variable]
cls.add_instance_attribute('m_deltaPucchShift', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_dlBandwidth [variable]
cls.add_instance_attribute('m_dlBandwidth', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_dlCyclicPrefixLength [variable]
cls.add_instance_attribute('m_dlCyclicPrefixLength', 'NormalExtended_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_duplexMode [variable]
cls.add_instance_attribute('m_duplexMode', 'ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::DuplexMode_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_enable64Qam [variable]
cls.add_instance_attribute('m_enable64Qam', 'ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::Enable64Qam_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_hoppingMode [variable]
cls.add_instance_attribute('m_hoppingMode', 'ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::HoppingMode_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_initialNrOfPdcchOfdmSymbols [variable]
cls.add_instance_attribute('m_initialNrOfPdcchOfdmSymbols', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_macContentionResolutionTimer [variable]
cls.add_instance_attribute('m_macContentionResolutionTimer', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_maxHarqMsg3Tx [variable]
cls.add_instance_attribute('m_maxHarqMsg3Tx', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_mbsfnSubframeConfigRfOffset [variable]
cls.add_instance_attribute('m_mbsfnSubframeConfigRfOffset', 'std::vector< unsigned char >', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_mbsfnSubframeConfigRfPeriod [variable]
cls.add_instance_attribute('m_mbsfnSubframeConfigRfPeriod', 'std::vector< unsigned char >', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_mbsfnSubframeConfigSfAllocation [variable]
cls.add_instance_attribute('m_mbsfnSubframeConfigSfAllocation', 'std::vector< unsigned char >', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_n1PucchAn [variable]
cls.add_instance_attribute('m_n1PucchAn', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_nSb [variable]
cls.add_instance_attribute('m_nSb', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_ncsAn [variable]
cls.add_instance_attribute('m_ncsAn', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_nrbCqi [variable]
cls.add_instance_attribute('m_nrbCqi', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_phichDuration [variable]
cls.add_instance_attribute('m_phichDuration', 'NormalExtended_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_phichResource [variable]
cls.add_instance_attribute('m_phichResource', 'ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::PhichResource_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_prachConfigurationIndex [variable]
cls.add_instance_attribute('m_prachConfigurationIndex', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_prachFreqOffset [variable]
cls.add_instance_attribute('m_prachFreqOffset', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_puschHoppingOffset [variable]
cls.add_instance_attribute('m_puschHoppingOffset', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_raResponseWindowSize [variable]
cls.add_instance_attribute('m_raResponseWindowSize', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_siConfiguration [variable]
cls.add_instance_attribute('m_siConfiguration', 'SiConfiguration_s', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_specialSubframePatterns [variable]
cls.add_instance_attribute('m_specialSubframePatterns', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_srsBandwidthConfiguration [variable]
cls.add_instance_attribute('m_srsBandwidthConfiguration', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_srsMaxUpPts [variable]
cls.add_instance_attribute('m_srsMaxUpPts', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_srsSubframeConfiguration [variable]
cls.add_instance_attribute('m_srsSubframeConfiguration', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_srsSubframeOffset [variable]
cls.add_instance_attribute('m_srsSubframeOffset', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_subframeAssignment [variable]
cls.add_instance_attribute('m_subframeAssignment', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_ulBandwidth [variable]
cls.add_instance_attribute('m_ulBandwidth', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_ulCyclicPrefixLength [variable]
cls.add_instance_attribute('m_ulCyclicPrefixLength', 'NormalExtended_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedCellConfigReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapProviderCschedLcConfigReqParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters::CschedLcConfigReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters::CschedLcConfigReqParameters(ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters::m_logicalChannelConfigList [variable]
cls.add_instance_attribute('m_logicalChannelConfigList', 'std::vector< LogicalChannelConfigListElement_s >', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters::m_reconfigureFlag [variable]
cls.add_instance_attribute('m_reconfigureFlag', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcConfigReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapProviderCschedLcReleaseReqParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters::CschedLcReleaseReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters::CschedLcReleaseReqParameters(ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters::m_logicalChannelIdentity [variable]
cls.add_instance_attribute('m_logicalChannelIdentity', 'std::vector< unsigned char >', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedLcReleaseReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapProviderCschedUeConfigReqParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::CschedUeConfigReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::CschedUeConfigReqParameters(ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_ackNackRepetitionFactor [variable]
cls.add_instance_attribute('m_ackNackRepetitionFactor', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_ackNackSrsSimultaneousTransmission [variable]
cls.add_instance_attribute('m_ackNackSrsSimultaneousTransmission', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_aperiodicCqiRepMode [variable]
cls.add_instance_attribute('m_aperiodicCqiRepMode', 'ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::RepMode_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_betaOffsetAckIndex [variable]
cls.add_instance_attribute('m_betaOffsetAckIndex', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_betaOffsetCqiIndex [variable]
cls.add_instance_attribute('m_betaOffsetCqiIndex', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_betaOffsetRiIndex [variable]
cls.add_instance_attribute('m_betaOffsetRiIndex', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_cqiConfig [variable]
cls.add_instance_attribute('m_cqiConfig', 'CqiConfig_s', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_cqiConfigPresent [variable]
cls.add_instance_attribute('m_cqiConfigPresent', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_drxConfig [variable]
cls.add_instance_attribute('m_drxConfig', 'DrxConfig_s', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_drxConfigPresent [variable]
cls.add_instance_attribute('m_drxConfigPresent', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_maxHarqTx [variable]
cls.add_instance_attribute('m_maxHarqTx', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_measGapConfigPattern [variable]
cls.add_instance_attribute('m_measGapConfigPattern', 'ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::MeasGapConfigPattern_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_measGapConfigSubframeOffset [variable]
cls.add_instance_attribute('m_measGapConfigSubframeOffset', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_reconfigureFlag [variable]
cls.add_instance_attribute('m_reconfigureFlag', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_simultaneousAckNackAndCqi [variable]
cls.add_instance_attribute('m_simultaneousAckNackAndCqi', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_spsConfig [variable]
cls.add_instance_attribute('m_spsConfig', 'SpsConfig_s', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_spsConfigPresent [variable]
cls.add_instance_attribute('m_spsConfigPresent', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_srConfig [variable]
cls.add_instance_attribute('m_srConfig', 'SrConfig_s', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_srConfigPresent [variable]
cls.add_instance_attribute('m_srConfigPresent', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_tddAckNackFeedbackMode [variable]
cls.add_instance_attribute('m_tddAckNackFeedbackMode', 'ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::FeedbackMode_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_timeAlignmentTimer [variable]
cls.add_instance_attribute('m_timeAlignmentTimer', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_transmissionMode [variable]
cls.add_instance_attribute('m_transmissionMode', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_ttiBundling [variable]
cls.add_instance_attribute('m_ttiBundling', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_ueAggregatedMaximumBitrateDl [variable]
cls.add_instance_attribute('m_ueAggregatedMaximumBitrateDl', 'uint64_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_ueAggregatedMaximumBitrateUl [variable]
cls.add_instance_attribute('m_ueAggregatedMaximumBitrateUl', 'uint64_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_ueCapabilities [variable]
cls.add_instance_attribute('m_ueCapabilities', 'UeCapabilities_s', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_ueTransmitAntennaSelection [variable]
cls.add_instance_attribute('m_ueTransmitAntennaSelection', 'ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::OpenClosedLoop_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapProviderCschedUeReleaseReqParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters::CschedUeReleaseReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters::CschedUeReleaseReqParameters(ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapProvider::CschedUeReleaseReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapUser_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::FfMacCschedSapUser() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::FfMacCschedSapUser(ns3::FfMacCschedSapUser const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapUser const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapUser::CschedCellConfigCnf(ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters const & params) [member function]
cls.add_method('CschedCellConfigCnf',
'void',
[param('ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapUser::CschedCellConfigUpdateInd(ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters const & params) [member function]
cls.add_method('CschedCellConfigUpdateInd',
'void',
[param('ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapUser::CschedLcConfigCnf(ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters const & params) [member function]
cls.add_method('CschedLcConfigCnf',
'void',
[param('ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapUser::CschedLcReleaseCnf(ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters const & params) [member function]
cls.add_method('CschedLcReleaseCnf',
'void',
[param('ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapUser::CschedUeConfigCnf(ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters const & params) [member function]
cls.add_method('CschedUeConfigCnf',
'void',
[param('ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapUser::CschedUeConfigUpdateInd(ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters const & params) [member function]
cls.add_method('CschedUeConfigUpdateInd',
'void',
[param('ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-csched-sap.h (module 'lte'): void ns3::FfMacCschedSapUser::CschedUeReleaseCnf(ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters const & params) [member function]
cls.add_method('CschedUeReleaseCnf',
'void',
[param('ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3FfMacCschedSapUserCschedCellConfigCnfParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters::CschedCellConfigCnfParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters::CschedCellConfigCnfParameters(ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters::m_result [variable]
cls.add_instance_attribute('m_result', 'Result_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapUserCschedCellConfigUpdateIndParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters::CschedCellConfigUpdateIndParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters::CschedCellConfigUpdateIndParameters(ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters::m_prbUtilizationDl [variable]
cls.add_instance_attribute('m_prbUtilizationDl', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters::m_prbUtilizationUl [variable]
cls.add_instance_attribute('m_prbUtilizationUl', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedCellConfigUpdateIndParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapUserCschedLcConfigCnfParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters::CschedLcConfigCnfParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters::CschedLcConfigCnfParameters(ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters::m_logicalChannelIdentity [variable]
cls.add_instance_attribute('m_logicalChannelIdentity', 'std::vector< unsigned char >', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters::m_result [variable]
cls.add_instance_attribute('m_result', 'Result_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapUserCschedLcReleaseCnfParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters::CschedLcReleaseCnfParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters::CschedLcReleaseCnfParameters(ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters::m_logicalChannelIdentity [variable]
cls.add_instance_attribute('m_logicalChannelIdentity', 'std::vector< unsigned char >', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters::m_result [variable]
cls.add_instance_attribute('m_result', 'Result_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedLcReleaseCnfParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapUserCschedUeConfigCnfParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters::CschedUeConfigCnfParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters::CschedUeConfigCnfParameters(ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters::m_result [variable]
cls.add_instance_attribute('m_result', 'Result_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigCnfParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapUserCschedUeConfigUpdateIndParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::CschedUeConfigUpdateIndParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::CschedUeConfigUpdateIndParameters(ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::m_cqiConfig [variable]
cls.add_instance_attribute('m_cqiConfig', 'CqiConfig_s', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::m_cqiConfigPresent [variable]
cls.add_instance_attribute('m_cqiConfigPresent', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::m_spsConfig [variable]
cls.add_instance_attribute('m_spsConfig', 'SpsConfig_s', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::m_spsConfigPresent [variable]
cls.add_instance_attribute('m_spsConfigPresent', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::m_srConfig [variable]
cls.add_instance_attribute('m_srConfig', 'SrConfig_s', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::m_srConfigPresent [variable]
cls.add_instance_attribute('m_srConfigPresent', 'bool', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::m_transmissionMode [variable]
cls.add_instance_attribute('m_transmissionMode', 'uint8_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeConfigUpdateIndParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacCschedSapUserCschedUeReleaseCnfParameters_methods(root_module, cls):
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters::CschedUeReleaseCnfParameters() [constructor]
cls.add_constructor([])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters::CschedUeReleaseCnfParameters(ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters const &', 'arg0')])
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters::m_result [variable]
cls.add_instance_attribute('m_result', 'Result_e', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-csched-sap.h (module 'lte'): ns3::FfMacCschedSapUser::CschedUeReleaseCnfParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProvider_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::FfMacSchedSapProvider() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::FfMacSchedSapProvider(ns3::FfMacSchedSapProvider const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedDlCqiInfoReq(ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters const & params) [member function]
cls.add_method('SchedDlCqiInfoReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedDlMacBufferReq(ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters const & params) [member function]
cls.add_method('SchedDlMacBufferReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedDlPagingBufferReq(ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters const & params) [member function]
cls.add_method('SchedDlPagingBufferReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedDlRachInfoReq(ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters const & params) [member function]
cls.add_method('SchedDlRachInfoReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedDlRlcBufferReq(ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters const & params) [member function]
cls.add_method('SchedDlRlcBufferReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedDlTriggerReq(ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters const & params) [member function]
cls.add_method('SchedDlTriggerReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedUlCqiInfoReq(ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters const & params) [member function]
cls.add_method('SchedUlCqiInfoReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReq(ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters const & params) [member function]
cls.add_method('SchedUlMacCtrlInfoReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReq(ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters const & params) [member function]
cls.add_method('SchedUlNoiseInterferenceReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedUlSrInfoReq(ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters const & params) [member function]
cls.add_method('SchedUlSrInfoReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapProvider::SchedUlTriggerReq(ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters const & params) [member function]
cls.add_method('SchedUlTriggerReq',
'void',
[param('ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3FfMacSchedSapProviderSchedDlCqiInfoReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters::SchedDlCqiInfoReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters::SchedDlCqiInfoReqParameters(ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters::m_cqiList [variable]
cls.add_instance_attribute('m_cqiList', 'std::vector< CqiListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters::m_sfnSf [variable]
cls.add_instance_attribute('m_sfnSf', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlCqiInfoReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedDlMacBufferReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters::SchedDlMacBufferReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters::SchedDlMacBufferReqParameters(ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters::m_ceBitmap [variable]
cls.add_instance_attribute('m_ceBitmap', 'CeBitmap_e', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlMacBufferReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedDlPagingBufferReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters::SchedDlPagingBufferReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters::SchedDlPagingBufferReqParameters(ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters::m_pagingInfoList [variable]
cls.add_instance_attribute('m_pagingInfoList', 'std::vector< PagingInfoListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlPagingBufferReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedDlRachInfoReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters::SchedDlRachInfoReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters::SchedDlRachInfoReqParameters(ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters::m_rachList [variable]
cls.add_instance_attribute('m_rachList', 'std::vector< RachListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters::m_sfnSf [variable]
cls.add_instance_attribute('m_sfnSf', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRachInfoReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedDlRlcBufferReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::SchedDlRlcBufferReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::SchedDlRlcBufferReqParameters(ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::m_logicalChannelIdentity [variable]
cls.add_instance_attribute('m_logicalChannelIdentity', 'uint8_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::m_rlcRetransmissionHolDelay [variable]
cls.add_instance_attribute('m_rlcRetransmissionHolDelay', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::m_rlcRetransmissionQueueSize [variable]
cls.add_instance_attribute('m_rlcRetransmissionQueueSize', 'uint32_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::m_rlcStatusPduSize [variable]
cls.add_instance_attribute('m_rlcStatusPduSize', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::m_rlcTransmissionQueueHolDelay [variable]
cls.add_instance_attribute('m_rlcTransmissionQueueHolDelay', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::m_rlcTransmissionQueueSize [variable]
cls.add_instance_attribute('m_rlcTransmissionQueueSize', 'uint32_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlRlcBufferReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedDlTriggerReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters::SchedDlTriggerReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters::SchedDlTriggerReqParameters(ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters::m_dlInfoList [variable]
cls.add_instance_attribute('m_dlInfoList', 'std::vector< DlInfoListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters::m_sfnSf [variable]
cls.add_instance_attribute('m_sfnSf', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedDlTriggerReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedUlCqiInfoReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters::SchedUlCqiInfoReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters::SchedUlCqiInfoReqParameters(ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters::m_sfnSf [variable]
cls.add_instance_attribute('m_sfnSf', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters::m_ulCqi [variable]
cls.add_instance_attribute('m_ulCqi', 'UlCqi_s', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlCqiInfoReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedUlMacCtrlInfoReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters::SchedUlMacCtrlInfoReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters::SchedUlMacCtrlInfoReqParameters(ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters::m_macCeList [variable]
cls.add_instance_attribute('m_macCeList', 'std::vector< MacCeListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters::m_sfnSf [variable]
cls.add_instance_attribute('m_sfnSf', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlMacCtrlInfoReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedUlNoiseInterferenceReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters::SchedUlNoiseInterferenceReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters::SchedUlNoiseInterferenceReqParameters(ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters::m_rip [variable]
cls.add_instance_attribute('m_rip', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters::m_sfnSf [variable]
cls.add_instance_attribute('m_sfnSf', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters::m_tnp [variable]
cls.add_instance_attribute('m_tnp', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlNoiseInterferenceReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedUlSrInfoReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters::SchedUlSrInfoReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters::SchedUlSrInfoReqParameters(ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters::m_sfnSf [variable]
cls.add_instance_attribute('m_sfnSf', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters::m_srList [variable]
cls.add_instance_attribute('m_srList', 'std::vector< SrListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlSrInfoReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapProviderSchedUlTriggerReqParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters::SchedUlTriggerReqParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters::SchedUlTriggerReqParameters(ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters::m_sfnSf [variable]
cls.add_instance_attribute('m_sfnSf', 'uint16_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters::m_ulInfoList [variable]
cls.add_instance_attribute('m_ulInfoList', 'std::vector< UlInfoListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapProvider::SchedUlTriggerReqParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapUser_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::FfMacSchedSapUser() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::FfMacSchedSapUser(ns3::FfMacSchedSapUser const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapUser const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapUser::SchedDlConfigInd(ns3::FfMacSchedSapUser::SchedDlConfigIndParameters const & params) [member function]
cls.add_method('SchedDlConfigInd',
'void',
[param('ns3::FfMacSchedSapUser::SchedDlConfigIndParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-sched-sap.h (module 'lte'): void ns3::FfMacSchedSapUser::SchedUlConfigInd(ns3::FfMacSchedSapUser::SchedUlConfigIndParameters const & params) [member function]
cls.add_method('SchedUlConfigInd',
'void',
[param('ns3::FfMacSchedSapUser::SchedUlConfigIndParameters const &', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3FfMacSchedSapUserSchedDlConfigIndParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedDlConfigIndParameters::SchedDlConfigIndParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedDlConfigIndParameters::SchedDlConfigIndParameters(ns3::FfMacSchedSapUser::SchedDlConfigIndParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapUser::SchedDlConfigIndParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedDlConfigIndParameters::m_buildBroadcastList [variable]
cls.add_instance_attribute('m_buildBroadcastList', 'std::vector< BuildBroadcastListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedDlConfigIndParameters::m_buildDataList [variable]
cls.add_instance_attribute('m_buildDataList', 'std::vector< BuildDataListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedDlConfigIndParameters::m_buildRarList [variable]
cls.add_instance_attribute('m_buildRarList', 'std::vector< BuildRarListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedDlConfigIndParameters::m_nrOfPdcchOfdmSymbols [variable]
cls.add_instance_attribute('m_nrOfPdcchOfdmSymbols', 'uint8_t', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedDlConfigIndParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3FfMacSchedSapUserSchedUlConfigIndParameters_methods(root_module, cls):
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedUlConfigIndParameters::SchedUlConfigIndParameters() [constructor]
cls.add_constructor([])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedUlConfigIndParameters::SchedUlConfigIndParameters(ns3::FfMacSchedSapUser::SchedUlConfigIndParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacSchedSapUser::SchedUlConfigIndParameters const &', 'arg0')])
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedUlConfigIndParameters::m_dciList [variable]
cls.add_instance_attribute('m_dciList', 'std::vector< UlDciListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedUlConfigIndParameters::m_phichList [variable]
cls.add_instance_attribute('m_phichList', 'std::vector< PhichListElement_s >', is_const=False)
## ff-mac-sched-sap.h (module 'lte'): ns3::FfMacSchedSapUser::SchedUlConfigIndParameters::m_vendorSpecificList [variable]
cls.add_instance_attribute('m_vendorSpecificList', 'std::vector< VendorSpecificListElement_s >', is_const=False)
return
def register_Ns3GbrQosInformation_methods(root_module, cls):
## eps-bearer.h (module 'lte'): ns3::GbrQosInformation::GbrQosInformation() [constructor]
cls.add_constructor([])
## eps-bearer.h (module 'lte'): ns3::GbrQosInformation::GbrQosInformation(ns3::GbrQosInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::GbrQosInformation const &', 'arg0')])
## eps-bearer.h (module 'lte'): ns3::GbrQosInformation::gbrDl [variable]
cls.add_instance_attribute('gbrDl', 'uint64_t', is_const=False)
## eps-bearer.h (module 'lte'): ns3::GbrQosInformation::gbrUl [variable]
cls.add_instance_attribute('gbrUl', 'uint64_t', is_const=False)
## eps-bearer.h (module 'lte'): ns3::GbrQosInformation::mbrDl [variable]
cls.add_instance_attribute('mbrDl', 'uint64_t', is_const=False)
## eps-bearer.h (module 'lte'): ns3::GbrQosInformation::mbrUl [variable]
cls.add_instance_attribute('mbrUl', 'uint64_t', is_const=False)
return
def register_Ns3ImsiLcidPair_t_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('==')
## lte-common.h (module 'lte'): ns3::ImsiLcidPair_t::ImsiLcidPair_t(ns3::ImsiLcidPair_t const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ImsiLcidPair_t const &', 'arg0')])
## lte-common.h (module 'lte'): ns3::ImsiLcidPair_t::ImsiLcidPair_t() [constructor]
cls.add_constructor([])
## lte-common.h (module 'lte'): ns3::ImsiLcidPair_t::ImsiLcidPair_t(uint64_t const a, uint8_t const b) [constructor]
cls.add_constructor([param('uint64_t const', 'a'), param('uint8_t const', 'b')])
## lte-common.h (module 'lte'): ns3::ImsiLcidPair_t::m_imsi [variable]
cls.add_instance_attribute('m_imsi', 'uint64_t', is_const=False)
## lte-common.h (module 'lte'): ns3::ImsiLcidPair_t::m_lcId [variable]
cls.add_instance_attribute('m_lcId', 'uint8_t', is_const=False)
return
def register_Ns3IntToType__0_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')])
return
def register_Ns3IntToType__1_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')])
return
def register_Ns3IntToType__2_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')])
return
def register_Ns3IntToType__3_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')])
return
def register_Ns3IntToType__4_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')])
return
def register_Ns3IntToType__5_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')])
return
def register_Ns3IntToType__6_methods(root_module, cls):
## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor]
cls.add_constructor([])
## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')])
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor]
cls.add_constructor([param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('CombineMask',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv4Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv4Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('GetSubnetDirectedBroadcast',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Address const &', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function]
cls.add_method('IsLocalMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('IsSubnetDirectedBroadcast',
'bool',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
return
def register_Ns3Ipv4AddressHelper_methods(root_module, cls):
## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper::Ipv4AddressHelper(ns3::Ipv4AddressHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressHelper const &', 'arg0')])
## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper::Ipv4AddressHelper() [constructor]
cls.add_constructor([])
## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper::Ipv4AddressHelper(ns3::Ipv4Address network, ns3::Ipv4Mask mask, ns3::Ipv4Address base="0.0.0.1") [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'network'), param('ns3::Ipv4Mask', 'mask'), param('ns3::Ipv4Address', 'base', default_value='"0.0.0.1"')])
## ipv4-address-helper.h (module 'internet'): ns3::Ipv4InterfaceContainer ns3::Ipv4AddressHelper::Assign(ns3::NetDeviceContainer const & c) [member function]
cls.add_method('Assign',
'ns3::Ipv4InterfaceContainer',
[param('ns3::NetDeviceContainer const &', 'c')])
## ipv4-address-helper.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4AddressHelper::NewAddress() [member function]
cls.add_method('NewAddress',
'ns3::Ipv4Address',
[])
## ipv4-address-helper.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4AddressHelper::NewNetwork() [member function]
cls.add_method('NewNetwork',
'ns3::Ipv4Address',
[])
## ipv4-address-helper.h (module 'internet'): void ns3::Ipv4AddressHelper::SetBase(ns3::Ipv4Address network, ns3::Ipv4Mask mask, ns3::Ipv4Address base="0.0.0.1") [member function]
cls.add_method('SetBase',
'void',
[param('ns3::Ipv4Address', 'network'), param('ns3::Ipv4Mask', 'mask'), param('ns3::Ipv4Address', 'base', default_value='"0.0.0.1"')])
return
def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor]
cls.add_constructor([])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor]
cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')])
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function]
cls.add_method('GetLocal',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function]
cls.add_method('GetMask',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function]
cls.add_method('GetScope',
'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function]
cls.add_method('IsSecondary',
'bool',
[],
is_const=True)
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function]
cls.add_method('SetBroadcast',
'void',
[param('ns3::Ipv4Address', 'broadcast')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function]
cls.add_method('SetLocal',
'void',
[param('ns3::Ipv4Address', 'local')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function]
cls.add_method('SetMask',
'void',
[param('ns3::Ipv4Mask', 'mask')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function]
cls.add_method('SetPrimary',
'void',
[])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SetScope',
'void',
[param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')])
## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function]
cls.add_method('SetSecondary',
'void',
[])
return
def register_Ns3Ipv4InterfaceContainer_methods(root_module, cls):
## ipv4-interface-container.h (module 'internet'): ns3::Ipv4InterfaceContainer::Ipv4InterfaceContainer(ns3::Ipv4InterfaceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4InterfaceContainer const &', 'arg0')])
## ipv4-interface-container.h (module 'internet'): ns3::Ipv4InterfaceContainer::Ipv4InterfaceContainer() [constructor]
cls.add_constructor([])
## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(ns3::Ipv4InterfaceContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ipv4InterfaceContainer', 'other')])
## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface')])
## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(std::pair<ns3::Ptr<ns3::Ipv4>,unsigned int> ipInterfacePair) [member function]
cls.add_method('Add',
'void',
[param('std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int >', 'ipInterfacePair')])
## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(std::string ipv4Name, uint32_t interface) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'ipv4Name'), param('uint32_t', 'interface')])
## ipv4-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int> > > > ns3::Ipv4InterfaceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > > >',
[],
is_const=True)
## ipv4-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int> > > > ns3::Ipv4InterfaceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > > >',
[],
is_const=True)
## ipv4-interface-container.h (module 'internet'): std::pair<ns3::Ptr<ns3::Ipv4>,unsigned int> ns3::Ipv4InterfaceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int >',
[param('uint32_t', 'i')],
is_const=True)
## ipv4-interface-container.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceContainer::GetAddress(uint32_t i, uint32_t j=0) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv4Address',
[param('uint32_t', 'i'), param('uint32_t', 'j', default_value='0')],
is_const=True)
## ipv4-interface-container.h (module 'internet'): uint32_t ns3::Ipv4InterfaceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::SetMetric(uint32_t i, uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint32_t', 'i'), param('uint16_t', 'metric')])
return
def register_Ns3Ipv4Mask_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor]
cls.add_constructor([param('uint32_t', 'mask')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor]
cls.add_constructor([param('char const *', 'mask')])
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function]
cls.add_method('GetInverse',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint16_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Mask', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'mask')])
return
def register_Ns3Ipv6Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor]
cls.add_constructor([param('uint8_t *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function]
cls.add_method('CombinePrefix',
'ns3::Ipv6Address',
[param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv6Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv6Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function]
cls.add_method('GetAllHostsMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function]
cls.add_method('GetAllNodesMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function]
cls.add_method('GetAllRoutersMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function]
cls.add_method('GetIpv4MappedAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function]
cls.add_method('IsAllHostsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function]
cls.add_method('IsAllNodesMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function]
cls.add_method('IsAllRoutersMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function]
cls.add_method('IsAny',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Address const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function]
cls.add_method('IsIpv4MappedAddress',
'bool',
[])
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function]
cls.add_method('IsLinkLocal',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function]
cls.add_method('IsLinkLocalMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function]
cls.add_method('IsSolicitedMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('MakeIpv4MappedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv4Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function]
cls.add_method('MakeSolicitedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv6Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function]
cls.add_method('Set',
'void',
[param('uint8_t *', 'address')])
return
def register_Ns3Ipv6InterfaceAddress_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress() [constructor]
cls.add_constructor([])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'address')])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address, ns3::Ipv6Prefix prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'prefix')])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6InterfaceAddress const & o) [copy constructor]
cls.add_constructor([param('ns3::Ipv6InterfaceAddress const &', 'o')])
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceAddress::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): uint32_t ns3::Ipv6InterfaceAddress::GetNsDadUid() const [member function]
cls.add_method('GetNsDadUid',
'uint32_t',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Prefix ns3::Ipv6InterfaceAddress::GetPrefix() const [member function]
cls.add_method('GetPrefix',
'ns3::Ipv6Prefix',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e ns3::Ipv6InterfaceAddress::GetScope() const [member function]
cls.add_method('GetScope',
'ns3::Ipv6InterfaceAddress::Scope_e',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e ns3::Ipv6InterfaceAddress::GetState() const [member function]
cls.add_method('GetState',
'ns3::Ipv6InterfaceAddress::State_e',
[],
is_const=True)
## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetAddress(ns3::Ipv6Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Ipv6Address', 'address')])
## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetNsDadUid(uint32_t uid) [member function]
cls.add_method('SetNsDadUid',
'void',
[param('uint32_t', 'uid')])
## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetScope(ns3::Ipv6InterfaceAddress::Scope_e scope) [member function]
cls.add_method('SetScope',
'void',
[param('ns3::Ipv6InterfaceAddress::Scope_e', 'scope')])
## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetState(ns3::Ipv6InterfaceAddress::State_e state) [member function]
cls.add_method('SetState',
'void',
[param('ns3::Ipv6InterfaceAddress::State_e', 'state')])
return
def register_Ns3Ipv6Prefix_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor]
cls.add_constructor([param('uint8_t *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor]
cls.add_constructor([param('char const *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor]
cls.add_constructor([param('uint8_t', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint8_t',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Prefix const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
return
def register_Ns3LteEnbCmacSapProvider_methods(root_module, cls):
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LteEnbCmacSapProvider() [constructor]
cls.add_constructor([])
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LteEnbCmacSapProvider(ns3::LteEnbCmacSapProvider const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteEnbCmacSapProvider const &', 'arg0')])
## lte-enb-cmac-sap.h (module 'lte'): void ns3::LteEnbCmacSapProvider::AddLc(ns3::LteEnbCmacSapProvider::LcInfo lcinfo, ns3::LteMacSapUser * msu) [member function]
cls.add_method('AddLc',
'void',
[param('ns3::LteEnbCmacSapProvider::LcInfo', 'lcinfo'), param('ns3::LteMacSapUser *', 'msu')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-cmac-sap.h (module 'lte'): void ns3::LteEnbCmacSapProvider::AddUe(uint16_t rnti) [member function]
cls.add_method('AddUe',
'void',
[param('uint16_t', 'rnti')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-cmac-sap.h (module 'lte'): void ns3::LteEnbCmacSapProvider::ConfigureMac(uint8_t ulBandwidth, uint8_t dlBandwidth) [member function]
cls.add_method('ConfigureMac',
'void',
[param('uint8_t', 'ulBandwidth'), param('uint8_t', 'dlBandwidth')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-cmac-sap.h (module 'lte'): void ns3::LteEnbCmacSapProvider::ReconfigureLc(ns3::LteEnbCmacSapProvider::LcInfo lcinfo) [member function]
cls.add_method('ReconfigureLc',
'void',
[param('ns3::LteEnbCmacSapProvider::LcInfo', 'lcinfo')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-cmac-sap.h (module 'lte'): void ns3::LteEnbCmacSapProvider::ReleaseLc(uint16_t rnti, uint8_t lcid) [member function]
cls.add_method('ReleaseLc',
'void',
[param('uint16_t', 'rnti'), param('uint8_t', 'lcid')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-cmac-sap.h (module 'lte'): void ns3::LteEnbCmacSapProvider::RrcUpdateConfigurationReq(ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters params) [member function]
cls.add_method('RrcUpdateConfigurationReq',
'void',
[param('ns3::FfMacCschedSapProvider::CschedUeConfigReqParameters', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteEnbCmacSapProviderLcInfo_methods(root_module, cls):
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::LcInfo() [constructor]
cls.add_constructor([])
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::LcInfo(ns3::LteEnbCmacSapProvider::LcInfo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteEnbCmacSapProvider::LcInfo const &', 'arg0')])
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::gbrDl [variable]
cls.add_instance_attribute('gbrDl', 'uint64_t', is_const=False)
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::gbrUl [variable]
cls.add_instance_attribute('gbrUl', 'uint64_t', is_const=False)
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::isGbr [variable]
cls.add_instance_attribute('isGbr', 'bool', is_const=False)
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::lcGroup [variable]
cls.add_instance_attribute('lcGroup', 'uint8_t', is_const=False)
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::lcId [variable]
cls.add_instance_attribute('lcId', 'uint8_t', is_const=False)
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::mbrDl [variable]
cls.add_instance_attribute('mbrDl', 'uint64_t', is_const=False)
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::mbrUl [variable]
cls.add_instance_attribute('mbrUl', 'uint64_t', is_const=False)
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::qci [variable]
cls.add_instance_attribute('qci', 'uint8_t', is_const=False)
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapProvider::LcInfo::rnti [variable]
cls.add_instance_attribute('rnti', 'uint16_t', is_const=False)
return
def register_Ns3LteEnbCmacSapUser_methods(root_module, cls):
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapUser::LteEnbCmacSapUser() [constructor]
cls.add_constructor([])
## lte-enb-cmac-sap.h (module 'lte'): ns3::LteEnbCmacSapUser::LteEnbCmacSapUser(ns3::LteEnbCmacSapUser const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteEnbCmacSapUser const &', 'arg0')])
## lte-enb-cmac-sap.h (module 'lte'): void ns3::LteEnbCmacSapUser::NotifyLcConfigResult(uint16_t rnti, uint8_t lcid, bool success) [member function]
cls.add_method('NotifyLcConfigResult',
'void',
[param('uint16_t', 'rnti'), param('uint8_t', 'lcid'), param('bool', 'success')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-cmac-sap.h (module 'lte'): void ns3::LteEnbCmacSapUser::RrcConfigurationUpdateInd(ns3::LteUeConfig_t params) [member function]
cls.add_method('RrcConfigurationUpdateInd',
'void',
[param('ns3::LteUeConfig_t', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteEnbPhySapProvider_methods(root_module, cls):
## lte-enb-phy-sap.h (module 'lte'): ns3::LteEnbPhySapProvider::LteEnbPhySapProvider() [constructor]
cls.add_constructor([])
## lte-enb-phy-sap.h (module 'lte'): ns3::LteEnbPhySapProvider::LteEnbPhySapProvider(ns3::LteEnbPhySapProvider const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteEnbPhySapProvider const &', 'arg0')])
## lte-enb-phy-sap.h (module 'lte'): uint8_t ns3::LteEnbPhySapProvider::GetMacChTtiDelay() [member function]
cls.add_method('GetMacChTtiDelay',
'uint8_t',
[],
is_pure_virtual=True, is_virtual=True)
## lte-enb-phy-sap.h (module 'lte'): void ns3::LteEnbPhySapProvider::SendIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('SendIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-phy-sap.h (module 'lte'): void ns3::LteEnbPhySapProvider::SendMacPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('SendMacPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-phy-sap.h (module 'lte'): void ns3::LteEnbPhySapProvider::SetBandwidth(uint8_t ulBandwidth, uint8_t dlBandwidth) [member function]
cls.add_method('SetBandwidth',
'void',
[param('uint8_t', 'ulBandwidth'), param('uint8_t', 'dlBandwidth')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-phy-sap.h (module 'lte'): void ns3::LteEnbPhySapProvider::SetCellId(uint16_t cellId) [member function]
cls.add_method('SetCellId',
'void',
[param('uint16_t', 'cellId')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-phy-sap.h (module 'lte'): void ns3::LteEnbPhySapProvider::SetTransmissionMode(uint16_t rnti, uint8_t txMode) [member function]
cls.add_method('SetTransmissionMode',
'void',
[param('uint16_t', 'rnti'), param('uint8_t', 'txMode')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteEnbPhySapUser_methods(root_module, cls):
## lte-enb-phy-sap.h (module 'lte'): ns3::LteEnbPhySapUser::LteEnbPhySapUser() [constructor]
cls.add_constructor([])
## lte-enb-phy-sap.h (module 'lte'): ns3::LteEnbPhySapUser::LteEnbPhySapUser(ns3::LteEnbPhySapUser const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteEnbPhySapUser const &', 'arg0')])
## lte-enb-phy-sap.h (module 'lte'): void ns3::LteEnbPhySapUser::ReceiveIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('ReceiveIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-phy-sap.h (module 'lte'): void ns3::LteEnbPhySapUser::ReceivePhyPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('ReceivePhyPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-phy-sap.h (module 'lte'): void ns3::LteEnbPhySapUser::SubframeIndication(uint32_t frameNo, uint32_t subframeNo) [member function]
cls.add_method('SubframeIndication',
'void',
[param('uint32_t', 'frameNo'), param('uint32_t', 'subframeNo')],
is_pure_virtual=True, is_virtual=True)
## lte-enb-phy-sap.h (module 'lte'): void ns3::LteEnbPhySapUser::UlCqiReport(UlCqi_s ulcqi) [member function]
cls.add_method('UlCqiReport',
'void',
[param('UlCqi_s', 'ulcqi')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteFfConverter_methods(root_module, cls):
## lte-common.h (module 'lte'): ns3::LteFfConverter::LteFfConverter() [constructor]
cls.add_constructor([])
## lte-common.h (module 'lte'): ns3::LteFfConverter::LteFfConverter(ns3::LteFfConverter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteFfConverter const &', 'arg0')])
## lte-common.h (module 'lte'): static uint16_t ns3::LteFfConverter::double2fpS11dot3(double val) [member function]
cls.add_method('double2fpS11dot3',
'uint16_t',
[param('double', 'val')],
is_static=True)
## lte-common.h (module 'lte'): static double ns3::LteFfConverter::fpS11dot3toDouble(uint16_t val) [member function]
cls.add_method('fpS11dot3toDouble',
'double',
[param('uint16_t', 'val')],
is_static=True)
## lte-common.h (module 'lte'): static double ns3::LteFfConverter::getMinFpS11dot3Value() [member function]
cls.add_method('getMinFpS11dot3Value',
'double',
[],
is_static=True)
return
def register_Ns3LteFlowId_t_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('==')
## lte-common.h (module 'lte'): ns3::LteFlowId_t::LteFlowId_t(ns3::LteFlowId_t const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteFlowId_t const &', 'arg0')])
## lte-common.h (module 'lte'): ns3::LteFlowId_t::LteFlowId_t() [constructor]
cls.add_constructor([])
## lte-common.h (module 'lte'): ns3::LteFlowId_t::LteFlowId_t(uint16_t const a, uint8_t const b) [constructor]
cls.add_constructor([param('uint16_t const', 'a'), param('uint8_t const', 'b')])
## lte-common.h (module 'lte'): ns3::LteFlowId_t::m_lcId [variable]
cls.add_instance_attribute('m_lcId', 'uint8_t', is_const=False)
## lte-common.h (module 'lte'): ns3::LteFlowId_t::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
return
def register_Ns3LteMacSapProvider_methods(root_module, cls):
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::LteMacSapProvider() [constructor]
cls.add_constructor([])
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::LteMacSapProvider(ns3::LteMacSapProvider const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteMacSapProvider const &', 'arg0')])
## lte-mac-sap.h (module 'lte'): void ns3::LteMacSapProvider::ReportBufferStatus(ns3::LteMacSapProvider::ReportBufferStatusParameters params) [member function]
cls.add_method('ReportBufferStatus',
'void',
[param('ns3::LteMacSapProvider::ReportBufferStatusParameters', 'params')],
is_pure_virtual=True, is_virtual=True)
## lte-mac-sap.h (module 'lte'): void ns3::LteMacSapProvider::TransmitPdu(ns3::LteMacSapProvider::TransmitPduParameters params) [member function]
cls.add_method('TransmitPdu',
'void',
[param('ns3::LteMacSapProvider::TransmitPduParameters', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteMacSapProviderReportBufferStatusParameters_methods(root_module, cls):
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters::ReportBufferStatusParameters() [constructor]
cls.add_constructor([])
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters::ReportBufferStatusParameters(ns3::LteMacSapProvider::ReportBufferStatusParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteMacSapProvider::ReportBufferStatusParameters const &', 'arg0')])
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters::lcid [variable]
cls.add_instance_attribute('lcid', 'uint8_t', is_const=False)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters::retxQueueHolDelay [variable]
cls.add_instance_attribute('retxQueueHolDelay', 'uint16_t', is_const=False)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters::retxQueueSize [variable]
cls.add_instance_attribute('retxQueueSize', 'uint32_t', is_const=False)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters::rnti [variable]
cls.add_instance_attribute('rnti', 'uint16_t', is_const=False)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters::statusPduSize [variable]
cls.add_instance_attribute('statusPduSize', 'uint16_t', is_const=False)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters::txQueueHolDelay [variable]
cls.add_instance_attribute('txQueueHolDelay', 'uint16_t', is_const=False)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::ReportBufferStatusParameters::txQueueSize [variable]
cls.add_instance_attribute('txQueueSize', 'uint32_t', is_const=False)
return
def register_Ns3LteMacSapProviderTransmitPduParameters_methods(root_module, cls):
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::TransmitPduParameters::TransmitPduParameters() [constructor]
cls.add_constructor([])
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::TransmitPduParameters::TransmitPduParameters(ns3::LteMacSapProvider::TransmitPduParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteMacSapProvider::TransmitPduParameters const &', 'arg0')])
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::TransmitPduParameters::layer [variable]
cls.add_instance_attribute('layer', 'uint8_t', is_const=False)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::TransmitPduParameters::lcid [variable]
cls.add_instance_attribute('lcid', 'uint8_t', is_const=False)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::TransmitPduParameters::pdu [variable]
cls.add_instance_attribute('pdu', 'ns3::Ptr< ns3::Packet >', is_const=False)
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapProvider::TransmitPduParameters::rnti [variable]
cls.add_instance_attribute('rnti', 'uint16_t', is_const=False)
return
def register_Ns3LteMacSapUser_methods(root_module, cls):
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapUser::LteMacSapUser() [constructor]
cls.add_constructor([])
## lte-mac-sap.h (module 'lte'): ns3::LteMacSapUser::LteMacSapUser(ns3::LteMacSapUser const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteMacSapUser const &', 'arg0')])
## lte-mac-sap.h (module 'lte'): void ns3::LteMacSapUser::NotifyHarqDeliveryFailure() [member function]
cls.add_method('NotifyHarqDeliveryFailure',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## lte-mac-sap.h (module 'lte'): void ns3::LteMacSapUser::NotifyTxOpportunity(uint32_t bytes, uint8_t layer) [member function]
cls.add_method('NotifyTxOpportunity',
'void',
[param('uint32_t', 'bytes'), param('uint8_t', 'layer')],
is_pure_virtual=True, is_virtual=True)
## lte-mac-sap.h (module 'lte'): void ns3::LteMacSapUser::ReceivePdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('ReceivePdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteMiErrorModel_methods(root_module, cls):
## lte-mi-error-model.h (module 'lte'): ns3::LteMiErrorModel::LteMiErrorModel() [constructor]
cls.add_constructor([])
## lte-mi-error-model.h (module 'lte'): ns3::LteMiErrorModel::LteMiErrorModel(ns3::LteMiErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteMiErrorModel const &', 'arg0')])
## lte-mi-error-model.h (module 'lte'): static double ns3::LteMiErrorModel::GetTbError(ns3::SpectrumValue const & sinr, std::vector<int, std::allocator<int> > const & map, uint16_t size, uint8_t mcs) [member function]
cls.add_method('GetTbError',
'double',
[param('ns3::SpectrumValue const &', 'sinr'), param('std::vector< int > const &', 'map'), param('uint16_t', 'size'), param('uint8_t', 'mcs')],
is_static=True)
## lte-mi-error-model.h (module 'lte'): static double ns3::LteMiErrorModel::MappingMiBler(double mib, uint8_t mcs, uint16_t cbSize) [member function]
cls.add_method('MappingMiBler',
'double',
[param('double', 'mib'), param('uint8_t', 'mcs'), param('uint16_t', 'cbSize')],
is_static=True)
## lte-mi-error-model.h (module 'lte'): static double ns3::LteMiErrorModel::Mib(ns3::SpectrumValue const & sinr, std::vector<int, std::allocator<int> > const & map, uint8_t mcs) [member function]
cls.add_method('Mib',
'double',
[param('ns3::SpectrumValue const &', 'sinr'), param('std::vector< int > const &', 'map'), param('uint8_t', 'mcs')],
is_static=True)
return
def register_Ns3LtePdcpSapProvider_methods(root_module, cls):
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapProvider::LtePdcpSapProvider() [constructor]
cls.add_constructor([])
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapProvider::LtePdcpSapProvider(ns3::LtePdcpSapProvider const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LtePdcpSapProvider const &', 'arg0')])
## lte-pdcp-sap.h (module 'lte'): void ns3::LtePdcpSapProvider::TransmitRrcPdu(ns3::LtePdcpSapProvider::TransmitRrcPduParameters params) [member function]
cls.add_method('TransmitRrcPdu',
'void',
[param('ns3::LtePdcpSapProvider::TransmitRrcPduParameters', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LtePdcpSapProviderTransmitRrcPduParameters_methods(root_module, cls):
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapProvider::TransmitRrcPduParameters::TransmitRrcPduParameters() [constructor]
cls.add_constructor([])
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapProvider::TransmitRrcPduParameters::TransmitRrcPduParameters(ns3::LtePdcpSapProvider::TransmitRrcPduParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LtePdcpSapProvider::TransmitRrcPduParameters const &', 'arg0')])
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapProvider::TransmitRrcPduParameters::lcid [variable]
cls.add_instance_attribute('lcid', 'uint8_t', is_const=False)
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapProvider::TransmitRrcPduParameters::rnti [variable]
cls.add_instance_attribute('rnti', 'uint16_t', is_const=False)
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapProvider::TransmitRrcPduParameters::rrcPdu [variable]
cls.add_instance_attribute('rrcPdu', 'ns3::Ptr< ns3::Packet >', is_const=False)
return
def register_Ns3LtePdcpSapUser_methods(root_module, cls):
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapUser::LtePdcpSapUser() [constructor]
cls.add_constructor([])
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapUser::LtePdcpSapUser(ns3::LtePdcpSapUser const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LtePdcpSapUser const &', 'arg0')])
## lte-pdcp-sap.h (module 'lte'): void ns3::LtePdcpSapUser::ReceiveRrcPdu(ns3::LtePdcpSapUser::ReceiveRrcPduParameters params) [member function]
cls.add_method('ReceiveRrcPdu',
'void',
[param('ns3::LtePdcpSapUser::ReceiveRrcPduParameters', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LtePdcpSapUserReceiveRrcPduParameters_methods(root_module, cls):
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapUser::ReceiveRrcPduParameters::ReceiveRrcPduParameters() [constructor]
cls.add_constructor([])
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapUser::ReceiveRrcPduParameters::ReceiveRrcPduParameters(ns3::LtePdcpSapUser::ReceiveRrcPduParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LtePdcpSapUser::ReceiveRrcPduParameters const &', 'arg0')])
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapUser::ReceiveRrcPduParameters::lcid [variable]
cls.add_instance_attribute('lcid', 'uint8_t', is_const=False)
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapUser::ReceiveRrcPduParameters::rnti [variable]
cls.add_instance_attribute('rnti', 'uint16_t', is_const=False)
## lte-pdcp-sap.h (module 'lte'): ns3::LtePdcpSapUser::ReceiveRrcPduParameters::rrcPdu [variable]
cls.add_instance_attribute('rrcPdu', 'ns3::Ptr< ns3::Packet >', is_const=False)
return
def register_Ns3LteRlcSapProvider_methods(root_module, cls):
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapProvider::LteRlcSapProvider() [constructor]
cls.add_constructor([])
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapProvider::LteRlcSapProvider(ns3::LteRlcSapProvider const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlcSapProvider const &', 'arg0')])
## lte-rlc-sap.h (module 'lte'): void ns3::LteRlcSapProvider::TransmitPdcpPdu(ns3::LteRlcSapProvider::TransmitPdcpPduParameters params) [member function]
cls.add_method('TransmitPdcpPdu',
'void',
[param('ns3::LteRlcSapProvider::TransmitPdcpPduParameters', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteRlcSapProviderTransmitPdcpPduParameters_methods(root_module, cls):
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapProvider::TransmitPdcpPduParameters::TransmitPdcpPduParameters() [constructor]
cls.add_constructor([])
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapProvider::TransmitPdcpPduParameters::TransmitPdcpPduParameters(ns3::LteRlcSapProvider::TransmitPdcpPduParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlcSapProvider::TransmitPdcpPduParameters const &', 'arg0')])
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapProvider::TransmitPdcpPduParameters::lcid [variable]
cls.add_instance_attribute('lcid', 'uint8_t', is_const=False)
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapProvider::TransmitPdcpPduParameters::pdcpPdu [variable]
cls.add_instance_attribute('pdcpPdu', 'ns3::Ptr< ns3::Packet >', is_const=False)
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapProvider::TransmitPdcpPduParameters::rnti [variable]
cls.add_instance_attribute('rnti', 'uint16_t', is_const=False)
return
def register_Ns3LteRlcSapUser_methods(root_module, cls):
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapUser::LteRlcSapUser() [constructor]
cls.add_constructor([])
## lte-rlc-sap.h (module 'lte'): ns3::LteRlcSapUser::LteRlcSapUser(ns3::LteRlcSapUser const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlcSapUser const &', 'arg0')])
## lte-rlc-sap.h (module 'lte'): void ns3::LteRlcSapUser::ReceivePdcpPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('ReceivePdcpPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteSpectrumValueHelper_methods(root_module, cls):
## lte-spectrum-value-helper.h (module 'lte'): ns3::LteSpectrumValueHelper::LteSpectrumValueHelper() [constructor]
cls.add_constructor([])
## lte-spectrum-value-helper.h (module 'lte'): ns3::LteSpectrumValueHelper::LteSpectrumValueHelper(ns3::LteSpectrumValueHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteSpectrumValueHelper const &', 'arg0')])
## lte-spectrum-value-helper.h (module 'lte'): static ns3::Ptr<ns3::SpectrumValue> ns3::LteSpectrumValueHelper::CreateNoisePowerSpectralDensity(uint16_t earfcn, uint8_t bandwdith, double noiseFigure) [member function]
cls.add_method('CreateNoisePowerSpectralDensity',
'ns3::Ptr< ns3::SpectrumValue >',
[param('uint16_t', 'earfcn'), param('uint8_t', 'bandwdith'), param('double', 'noiseFigure')],
is_static=True)
## lte-spectrum-value-helper.h (module 'lte'): static ns3::Ptr<ns3::SpectrumValue> ns3::LteSpectrumValueHelper::CreateNoisePowerSpectralDensity(double noiseFigure, ns3::Ptr<ns3::SpectrumModel> spectrumModel) [member function]
cls.add_method('CreateNoisePowerSpectralDensity',
'ns3::Ptr< ns3::SpectrumValue >',
[param('double', 'noiseFigure'), param('ns3::Ptr< ns3::SpectrumModel >', 'spectrumModel')],
is_static=True)
## lte-spectrum-value-helper.h (module 'lte'): static ns3::Ptr<ns3::SpectrumValue> ns3::LteSpectrumValueHelper::CreateTxPowerSpectralDensity(uint16_t earfcn, uint8_t bandwdith, double powerTx, std::vector<int, std::allocator<int> > activeRbs) [member function]
cls.add_method('CreateTxPowerSpectralDensity',
'ns3::Ptr< ns3::SpectrumValue >',
[param('uint16_t', 'earfcn'), param('uint8_t', 'bandwdith'), param('double', 'powerTx'), param('std::vector< int >', 'activeRbs')],
is_static=True)
## lte-spectrum-value-helper.h (module 'lte'): static double ns3::LteSpectrumValueHelper::GetCarrierFrequency(uint16_t earfcn) [member function]
cls.add_method('GetCarrierFrequency',
'double',
[param('uint16_t', 'earfcn')],
is_static=True)
## lte-spectrum-value-helper.h (module 'lte'): static double ns3::LteSpectrumValueHelper::GetChannelBandwidth(uint8_t txBandwidthConf) [member function]
cls.add_method('GetChannelBandwidth',
'double',
[param('uint8_t', 'txBandwidthConf')],
is_static=True)
## lte-spectrum-value-helper.h (module 'lte'): static double ns3::LteSpectrumValueHelper::GetDownlinkCarrierFrequency(uint16_t earfcn) [member function]
cls.add_method('GetDownlinkCarrierFrequency',
'double',
[param('uint16_t', 'earfcn')],
is_static=True)
## lte-spectrum-value-helper.h (module 'lte'): static ns3::Ptr<ns3::SpectrumModel> ns3::LteSpectrumValueHelper::GetSpectrumModel(uint16_t earfcn, uint8_t bandwdith) [member function]
cls.add_method('GetSpectrumModel',
'ns3::Ptr< ns3::SpectrumModel >',
[param('uint16_t', 'earfcn'), param('uint8_t', 'bandwdith')],
is_static=True)
## lte-spectrum-value-helper.h (module 'lte'): static double ns3::LteSpectrumValueHelper::GetUplinkCarrierFrequency(uint16_t earfcn) [member function]
cls.add_method('GetUplinkCarrierFrequency',
'double',
[param('uint16_t', 'earfcn')],
is_static=True)
return
def register_Ns3LteUeCmacSapProvider_methods(root_module, cls):
## lte-ue-cmac-sap.h (module 'lte'): ns3::LteUeCmacSapProvider::LteUeCmacSapProvider() [constructor]
cls.add_constructor([])
## lte-ue-cmac-sap.h (module 'lte'): ns3::LteUeCmacSapProvider::LteUeCmacSapProvider(ns3::LteUeCmacSapProvider const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteUeCmacSapProvider const &', 'arg0')])
## lte-ue-cmac-sap.h (module 'lte'): void ns3::LteUeCmacSapProvider::AddLc(uint8_t lcId, ns3::LteMacSapUser * msu) [member function]
cls.add_method('AddLc',
'void',
[param('uint8_t', 'lcId'), param('ns3::LteMacSapUser *', 'msu')],
is_pure_virtual=True, is_virtual=True)
## lte-ue-cmac-sap.h (module 'lte'): void ns3::LteUeCmacSapProvider::ConfigureUe(uint16_t rnti) [member function]
cls.add_method('ConfigureUe',
'void',
[param('uint16_t', 'rnti')],
is_pure_virtual=True, is_virtual=True)
## lte-ue-cmac-sap.h (module 'lte'): void ns3::LteUeCmacSapProvider::RemoveLc(uint8_t lcId) [member function]
cls.add_method('RemoveLc',
'void',
[param('uint8_t', 'lcId')],
is_pure_virtual=True, is_virtual=True)
## lte-ue-cmac-sap.h (module 'lte'): void ns3::LteUeCmacSapProvider::RrcUpdateConfigurationReq(ns3::LteUeConfig_t params) [member function]
cls.add_method('RrcUpdateConfigurationReq',
'void',
[param('ns3::LteUeConfig_t', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteUeCmacSapUser_methods(root_module, cls):
## lte-ue-cmac-sap.h (module 'lte'): ns3::LteUeCmacSapUser::LteUeCmacSapUser() [constructor]
cls.add_constructor([])
## lte-ue-cmac-sap.h (module 'lte'): ns3::LteUeCmacSapUser::LteUeCmacSapUser(ns3::LteUeCmacSapUser const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteUeCmacSapUser const &', 'arg0')])
## lte-ue-cmac-sap.h (module 'lte'): void ns3::LteUeCmacSapUser::LcConfigCompleted() [member function]
cls.add_method('LcConfigCompleted',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteUeConfig_t_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('==')
## lte-common.h (module 'lte'): ns3::LteUeConfig_t::LteUeConfig_t(ns3::LteUeConfig_t const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteUeConfig_t const &', 'arg0')])
## lte-common.h (module 'lte'): ns3::LteUeConfig_t::LteUeConfig_t() [constructor]
cls.add_constructor([])
## lte-common.h (module 'lte'): ns3::LteUeConfig_t::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
## lte-common.h (module 'lte'): ns3::LteUeConfig_t::m_transmissionMode [variable]
cls.add_instance_attribute('m_transmissionMode', 'uint8_t', is_const=False)
return
def register_Ns3LteUePhySapProvider_methods(root_module, cls):
## lte-ue-phy-sap.h (module 'lte'): ns3::LteUePhySapProvider::LteUePhySapProvider() [constructor]
cls.add_constructor([])
## lte-ue-phy-sap.h (module 'lte'): ns3::LteUePhySapProvider::LteUePhySapProvider(ns3::LteUePhySapProvider const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteUePhySapProvider const &', 'arg0')])
## lte-ue-phy-sap.h (module 'lte'): void ns3::LteUePhySapProvider::SendIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('SendIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')],
is_pure_virtual=True, is_virtual=True)
## lte-ue-phy-sap.h (module 'lte'): void ns3::LteUePhySapProvider::SendMacPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('SendMacPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, is_virtual=True)
## lte-ue-phy-sap.h (module 'lte'): void ns3::LteUePhySapProvider::SetBandwidth(uint8_t ulBandwidth, uint8_t dlBandwidth) [member function]
cls.add_method('SetBandwidth',
'void',
[param('uint8_t', 'ulBandwidth'), param('uint8_t', 'dlBandwidth')],
is_pure_virtual=True, is_virtual=True)
## lte-ue-phy-sap.h (module 'lte'): void ns3::LteUePhySapProvider::SetTransmissionMode(uint8_t txMode) [member function]
cls.add_method('SetTransmissionMode',
'void',
[param('uint8_t', 'txMode')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteUePhySapUser_methods(root_module, cls):
## lte-ue-phy-sap.h (module 'lte'): ns3::LteUePhySapUser::LteUePhySapUser() [constructor]
cls.add_constructor([])
## lte-ue-phy-sap.h (module 'lte'): ns3::LteUePhySapUser::LteUePhySapUser(ns3::LteUePhySapUser const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteUePhySapUser const &', 'arg0')])
## lte-ue-phy-sap.h (module 'lte'): void ns3::LteUePhySapUser::ReceiveIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('ReceiveIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')],
is_pure_virtual=True, is_virtual=True)
## lte-ue-phy-sap.h (module 'lte'): void ns3::LteUePhySapUser::ReceivePhyPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('ReceivePhyPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, is_virtual=True)
## lte-ue-phy-sap.h (module 'lte'): void ns3::LteUePhySapUser::SubframeIndication(uint32_t frameNo, uint32_t subframeNo) [member function]
cls.add_method('SubframeIndication',
'void',
[param('uint32_t', 'frameNo'), param('uint32_t', 'subframeNo')],
is_pure_virtual=True, is_virtual=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_Ns3Names_methods(root_module, cls):
## names.h (module 'core'): ns3::Names::Names() [constructor]
cls.add_constructor([])
## names.h (module 'core'): ns3::Names::Names(ns3::Names const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Names const &', 'arg0')])
## names.h (module 'core'): static void ns3::Names::Add(std::string name, ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name'), param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Add(std::string path, std::string name, ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'path'), param('std::string', 'name'), param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Add(ns3::Ptr<ns3::Object> context, std::string name, ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Object >', 'context'), param('std::string', 'name'), param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Clear() [member function]
cls.add_method('Clear',
'void',
[],
is_static=True)
## names.h (module 'core'): static std::string ns3::Names::FindName(ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('FindName',
'std::string',
[param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static std::string ns3::Names::FindPath(ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('FindPath',
'std::string',
[param('ns3::Ptr< ns3::Object >', 'object')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Rename(std::string oldpath, std::string newname) [member function]
cls.add_method('Rename',
'void',
[param('std::string', 'oldpath'), param('std::string', 'newname')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Rename(std::string path, std::string oldname, std::string newname) [member function]
cls.add_method('Rename',
'void',
[param('std::string', 'path'), param('std::string', 'oldname'), param('std::string', 'newname')],
is_static=True)
## names.h (module 'core'): static void ns3::Names::Rename(ns3::Ptr<ns3::Object> context, std::string oldname, std::string newname) [member function]
cls.add_method('Rename',
'void',
[param('ns3::Ptr< ns3::Object >', 'context'), param('std::string', 'oldname'), param('std::string', 'newname')],
is_static=True)
return
def register_Ns3NetDeviceContainer_methods(root_module, cls):
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor]
cls.add_constructor([])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor]
cls.add_constructor([param('std::string', 'devName')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NetDeviceContainer', 'other')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'deviceName')])
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True)
## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeContainer_methods(root_module, cls):
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor]
cls.add_constructor([])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor]
cls.add_constructor([param('std::string', 'nodeName')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NodeContainer', 'other')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'nodeName')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n')])
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n'), param('uint32_t', 'systemId')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'i')],
is_const=True)
## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function]
cls.add_method('GetGlobal',
'ns3::NodeContainer',
[],
is_static=True)
## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3ObjectBase_methods(root_module, cls):
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor]
cls.add_constructor([])
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')])
## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')],
is_const=True)
## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function]
cls.add_method('ConstructSelf',
'void',
[param('ns3::AttributeConstructionList const &', 'attributes')],
visibility='protected')
## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function]
cls.add_method('NotifyConstructionCompleted',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectDeleter_methods(root_module, cls):
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor]
cls.add_constructor([])
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')])
## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Object *', 'object')],
is_static=True)
return
def register_Ns3ObjectFactory_methods(root_module, cls):
cls.add_output_stream_operator()
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor]
cls.add_constructor([param('std::string', 'typeId')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('ns3::TypeId', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('char const *', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('std::string', 'tid')])
return
def register_Ns3PacketMetadata_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor]
cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[param('ns3::Buffer', 'buffer')],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function]
cls.add_method('CreateFragment',
'ns3::PacketMetadata',
[param('uint32_t', 'start'), param('uint32_t', 'end')],
is_const=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function]
cls.add_method('Enable',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('RemoveTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3PacketMetadataItem_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor]
cls.add_constructor([])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable]
cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable]
cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable]
cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable]
cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable]
cls.add_instance_attribute('isFragment', 'bool', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor]
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketMetadata::Item',
[])
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3PacketTagListTagData_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable]
cls.add_instance_attribute('count', 'uint32_t', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable]
cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable]
cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_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_Ns3RngSeedManager_methods(root_module, cls):
## rng-seed-manager.h (module 'core'): ns3::RngSeedManager::RngSeedManager() [constructor]
cls.add_constructor([])
## rng-seed-manager.h (module 'core'): ns3::RngSeedManager::RngSeedManager(ns3::RngSeedManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RngSeedManager const &', 'arg0')])
## rng-seed-manager.h (module 'core'): static uint64_t ns3::RngSeedManager::GetNextStreamIndex() [member function]
cls.add_method('GetNextStreamIndex',
'uint64_t',
[],
is_static=True)
## rng-seed-manager.h (module 'core'): static uint64_t ns3::RngSeedManager::GetRun() [member function]
cls.add_method('GetRun',
'uint64_t',
[],
is_static=True)
## rng-seed-manager.h (module 'core'): static uint32_t ns3::RngSeedManager::GetSeed() [member function]
cls.add_method('GetSeed',
'uint32_t',
[],
is_static=True)
## rng-seed-manager.h (module 'core'): static void ns3::RngSeedManager::SetRun(uint64_t run) [member function]
cls.add_method('SetRun',
'void',
[param('uint64_t', 'run')],
is_static=True)
## rng-seed-manager.h (module 'core'): static void ns3::RngSeedManager::SetSeed(uint32_t seed) [member function]
cls.add_method('SetSeed',
'void',
[param('uint32_t', 'seed')],
is_static=True)
return
def register_Ns3SequenceNumber10_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('!=')
cls.add_binary_numeric_operator('+', root_module['ns3::SequenceNumber10'], root_module['ns3::SequenceNumber10'], param('uint16_t', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::SequenceNumber10'], root_module['ns3::SequenceNumber10'], param('uint16_t', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('>=')
## lte-rlc-sequence-number.h (module 'lte'): ns3::SequenceNumber10::SequenceNumber10() [constructor]
cls.add_constructor([])
## lte-rlc-sequence-number.h (module 'lte'): ns3::SequenceNumber10::SequenceNumber10(uint16_t value) [constructor]
cls.add_constructor([param('uint16_t', 'value')])
## lte-rlc-sequence-number.h (module 'lte'): ns3::SequenceNumber10::SequenceNumber10(ns3::SequenceNumber10 const & value) [copy constructor]
cls.add_constructor([param('ns3::SequenceNumber10 const &', 'value')])
## lte-rlc-sequence-number.h (module 'lte'): uint16_t ns3::SequenceNumber10::GetValue() const [member function]
cls.add_method('GetValue',
'uint16_t',
[],
is_const=True)
## lte-rlc-sequence-number.h (module 'lte'): void ns3::SequenceNumber10::SetModulusBase(ns3::SequenceNumber10 modulusBase) [member function]
cls.add_method('SetModulusBase',
'void',
[param('ns3::SequenceNumber10', 'modulusBase')])
## lte-rlc-sequence-number.h (module 'lte'): void ns3::SequenceNumber10::SetModulusBase(uint16_t modulusBase) [member function]
cls.add_method('SetModulusBase',
'void',
[param('uint16_t', 'modulusBase')])
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_Ns3StatisticalSummary_methods(root_module, cls):
## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary() [constructor]
cls.add_constructor([])
## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary(ns3::StatisticalSummary const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StatisticalSummary const &', 'arg0')])
## data-calculator.h (module 'stats'): long int ns3::StatisticalSummary::getCount() const [member function]
cls.add_method('getCount',
'long int',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMax() const [member function]
cls.add_method('getMax',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMean() const [member function]
cls.add_method('getMean',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMin() const [member function]
cls.add_method('getMin',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSqrSum() const [member function]
cls.add_method('getSqrSum',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getStddev() const [member function]
cls.add_method('getStddev',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSum() const [member function]
cls.add_method('getSum',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getVariance() const [member function]
cls.add_method('getVariance',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_Ns3TbId_t_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('==')
## lte-spectrum-phy.h (module 'lte'): ns3::TbId_t::TbId_t(ns3::TbId_t const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TbId_t const &', 'arg0')])
## lte-spectrum-phy.h (module 'lte'): ns3::TbId_t::TbId_t() [constructor]
cls.add_constructor([])
## lte-spectrum-phy.h (module 'lte'): ns3::TbId_t::TbId_t(uint16_t const a, uint8_t const b) [constructor]
cls.add_constructor([param('uint16_t const', 'a'), param('uint8_t const', 'b')])
## lte-spectrum-phy.h (module 'lte'): ns3::TbId_t::m_layer [variable]
cls.add_instance_attribute('m_layer', 'uint8_t', is_const=False)
## lte-spectrum-phy.h (module 'lte'): ns3::TbId_t::m_rnti [variable]
cls.add_instance_attribute('m_rnti', 'uint16_t', is_const=False)
return
def register_Ns3Timer_methods(root_module, cls):
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Timer const &', 'arg0')])
## timer.h (module 'core'): ns3::Timer::Timer() [constructor]
cls.add_constructor([])
## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor]
cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')])
## timer.h (module 'core'): void ns3::Timer::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[],
is_const=True)
## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function]
cls.add_method('GetState',
'ns3::Timer::State',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function]
cls.add_method('IsSuspended',
'bool',
[],
is_const=True)
## timer.h (module 'core'): void ns3::Timer::Remove() [member function]
cls.add_method('Remove',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Resume() [member function]
cls.add_method('Resume',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule() [member function]
cls.add_method('Schedule',
'void',
[])
## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function]
cls.add_method('Schedule',
'void',
[param('ns3::Time', 'delay')])
## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function]
cls.add_method('SetDelay',
'void',
[param('ns3::Time const &', 'delay')])
## timer.h (module 'core'): void ns3::Timer::Suspend() [member function]
cls.add_method('Suspend',
'void',
[])
return
def register_Ns3TimerImpl_methods(root_module, cls):
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor]
cls.add_constructor([])
## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')])
## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function]
cls.add_method('Schedule',
'ns3::EventId',
[param('ns3::Time const &', 'delay')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3TransmissionModesLayers_methods(root_module, cls):
## lte-common.h (module 'lte'): ns3::TransmissionModesLayers::TransmissionModesLayers() [constructor]
cls.add_constructor([])
## lte-common.h (module 'lte'): ns3::TransmissionModesLayers::TransmissionModesLayers(ns3::TransmissionModesLayers const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TransmissionModesLayers const &', 'arg0')])
## lte-common.h (module 'lte'): static uint8_t ns3::TransmissionModesLayers::TxMode2LayerNum(uint8_t txMode) [member function]
cls.add_method('TxMode2LayerNum',
'uint8_t',
[param('uint8_t', 'txMode')],
is_static=True)
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_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_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor]
cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t', 'v')],
is_static=True)
## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function]
cls.add_method('MulByInvert',
'void',
[param('ns3::int64x64_t const &', 'o')])
return
def register_Ns3PfsFlowPerf_t_methods(root_module, cls):
## pf-ff-mac-scheduler.h (module 'lte'): ns3::pfsFlowPerf_t::pfsFlowPerf_t() [constructor]
cls.add_constructor([])
## pf-ff-mac-scheduler.h (module 'lte'): ns3::pfsFlowPerf_t::pfsFlowPerf_t(ns3::pfsFlowPerf_t const & arg0) [copy constructor]
cls.add_constructor([param('ns3::pfsFlowPerf_t const &', 'arg0')])
## pf-ff-mac-scheduler.h (module 'lte'): ns3::pfsFlowPerf_t::flowStart [variable]
cls.add_instance_attribute('flowStart', 'ns3::Time', is_const=False)
## pf-ff-mac-scheduler.h (module 'lte'): ns3::pfsFlowPerf_t::lastAveragedThroughput [variable]
cls.add_instance_attribute('lastAveragedThroughput', 'double', is_const=False)
## pf-ff-mac-scheduler.h (module 'lte'): ns3::pfsFlowPerf_t::lastTtiBytesTrasmitted [variable]
cls.add_instance_attribute('lastTtiBytesTrasmitted', 'unsigned int', is_const=False)
## pf-ff-mac-scheduler.h (module 'lte'): ns3::pfsFlowPerf_t::totalBytesTransmitted [variable]
cls.add_instance_attribute('totalBytesTransmitted', 'long unsigned int', is_const=False)
return
def register_Ns3TbInfo_t_methods(root_module, cls):
## lte-spectrum-phy.h (module 'lte'): ns3::tbInfo_t::tbInfo_t() [constructor]
cls.add_constructor([])
## lte-spectrum-phy.h (module 'lte'): ns3::tbInfo_t::tbInfo_t(ns3::tbInfo_t const & arg0) [copy constructor]
cls.add_constructor([param('ns3::tbInfo_t const &', 'arg0')])
## lte-spectrum-phy.h (module 'lte'): ns3::tbInfo_t::corrupt [variable]
cls.add_instance_attribute('corrupt', 'bool', is_const=False)
## lte-spectrum-phy.h (module 'lte'): ns3::tbInfo_t::mcs [variable]
cls.add_instance_attribute('mcs', 'uint8_t', is_const=False)
## lte-spectrum-phy.h (module 'lte'): ns3::tbInfo_t::rbBitmap [variable]
cls.add_instance_attribute('rbBitmap', 'std::vector< int >', is_const=False)
## lte-spectrum-phy.h (module 'lte'): ns3::tbInfo_t::size [variable]
cls.add_instance_attribute('size', 'uint16_t', is_const=False)
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_Ns3Ipv4Header_methods(root_module, cls):
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')])
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor]
cls.add_constructor([])
## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function]
cls.add_method('DscpTypeToString',
'std::string',
[param('ns3::Ipv4Header::DscpType', 'dscp')],
is_const=True)
## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function]
cls.add_method('EcnTypeToString',
'std::string',
[param('ns3::Ipv4Header::EcnType', 'ecn')],
is_const=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function]
cls.add_method('EnableChecksum',
'void',
[])
## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function]
cls.add_method('GetDscp',
'ns3::Ipv4Header::DscpType',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function]
cls.add_method('GetEcn',
'ns3::Ipv4Header::EcnType',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function]
cls.add_method('GetFragmentOffset',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function]
cls.add_method('GetIdentification',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function]
cls.add_method('GetPayloadSize',
'uint16_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function]
cls.add_method('GetTtl',
'uint8_t',
[],
is_const=True)
## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function]
cls.add_method('IsChecksumOk',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function]
cls.add_method('IsDontFragment',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function]
cls.add_method('IsLastFragment',
'bool',
[],
is_const=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'destination')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function]
cls.add_method('SetDontFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function]
cls.add_method('SetDscp',
'void',
[param('ns3::Ipv4Header::DscpType', 'dscp')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function]
cls.add_method('SetEcn',
'void',
[param('ns3::Ipv4Header::EcnType', 'ecn')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function]
cls.add_method('SetFragmentOffset',
'void',
[param('uint16_t', 'offsetBytes')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function]
cls.add_method('SetIdentification',
'void',
[param('uint16_t', 'identification')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function]
cls.add_method('SetLastFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function]
cls.add_method('SetMayFragment',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function]
cls.add_method('SetMoreFragments',
'void',
[])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function]
cls.add_method('SetPayloadSize',
'void',
[param('uint16_t', 'size')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function]
cls.add_method('SetProtocol',
'void',
[param('uint8_t', 'num')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 'source')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function]
cls.add_method('SetTtl',
'void',
[param('uint8_t', 'ttl')])
return
def register_Ns3Ipv6Header_methods(root_module, cls):
## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header(ns3::Ipv6Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Header const &', 'arg0')])
## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header() [constructor]
cls.add_constructor([])
## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetDestinationAddress() const [member function]
cls.add_method('GetDestinationAddress',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetFlowLabel() const [member function]
cls.add_method('GetFlowLabel',
'uint32_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetHopLimit() const [member function]
cls.add_method('GetHopLimit',
'uint8_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): ns3::TypeId ns3::Ipv6Header::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetNextHeader() const [member function]
cls.add_method('GetNextHeader',
'uint8_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint16_t ns3::Ipv6Header::GetPayloadLength() const [member function]
cls.add_method('GetPayloadLength',
'uint16_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetSourceAddress() const [member function]
cls.add_method('GetSourceAddress',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetTrafficClass() const [member function]
cls.add_method('GetTrafficClass',
'uint8_t',
[],
is_const=True)
## ipv6-header.h (module 'internet'): static ns3::TypeId ns3::Ipv6Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetDestinationAddress(ns3::Ipv6Address dst) [member function]
cls.add_method('SetDestinationAddress',
'void',
[param('ns3::Ipv6Address', 'dst')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetFlowLabel(uint32_t flow) [member function]
cls.add_method('SetFlowLabel',
'void',
[param('uint32_t', 'flow')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetHopLimit(uint8_t limit) [member function]
cls.add_method('SetHopLimit',
'void',
[param('uint8_t', 'limit')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetNextHeader(uint8_t next) [member function]
cls.add_method('SetNextHeader',
'void',
[param('uint8_t', 'next')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetPayloadLength(uint16_t len) [member function]
cls.add_method('SetPayloadLength',
'void',
[param('uint16_t', 'len')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetSourceAddress(ns3::Ipv6Address src) [member function]
cls.add_method('SetSourceAddress',
'void',
[param('ns3::Ipv6Address', 'src')])
## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetTrafficClass(uint8_t traffic) [member function]
cls.add_method('SetTrafficClass',
'void',
[param('uint8_t', 'traffic')])
return
def register_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_Ns3LtePdcpHeader_methods(root_module, cls):
## lte-pdcp-header.h (module 'lte'): ns3::LtePdcpHeader::LtePdcpHeader(ns3::LtePdcpHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LtePdcpHeader const &', 'arg0')])
## lte-pdcp-header.h (module 'lte'): ns3::LtePdcpHeader::LtePdcpHeader() [constructor]
cls.add_constructor([])
## lte-pdcp-header.h (module 'lte'): uint32_t ns3::LtePdcpHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## lte-pdcp-header.h (module 'lte'): uint8_t ns3::LtePdcpHeader::GetDcBit() const [member function]
cls.add_method('GetDcBit',
'uint8_t',
[],
is_const=True)
## lte-pdcp-header.h (module 'lte'): ns3::TypeId ns3::LtePdcpHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## lte-pdcp-header.h (module 'lte'): uint16_t ns3::LtePdcpHeader::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## lte-pdcp-header.h (module 'lte'): uint32_t ns3::LtePdcpHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## lte-pdcp-header.h (module 'lte'): static ns3::TypeId ns3::LtePdcpHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-pdcp-header.h (module 'lte'): void ns3::LtePdcpHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## lte-pdcp-header.h (module 'lte'): void ns3::LtePdcpHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## lte-pdcp-header.h (module 'lte'): void ns3::LtePdcpHeader::SetDcBit(uint8_t dcBit) [member function]
cls.add_method('SetDcBit',
'void',
[param('uint8_t', 'dcBit')])
## lte-pdcp-header.h (module 'lte'): void ns3::LtePdcpHeader::SetSequenceNumber(uint16_t sequenceNumber) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'sequenceNumber')])
return
def register_Ns3LtePhyTag_methods(root_module, cls):
## lte-phy-tag.h (module 'lte'): ns3::LtePhyTag::LtePhyTag(ns3::LtePhyTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LtePhyTag const &', 'arg0')])
## lte-phy-tag.h (module 'lte'): ns3::LtePhyTag::LtePhyTag() [constructor]
cls.add_constructor([])
## lte-phy-tag.h (module 'lte'): ns3::LtePhyTag::LtePhyTag(uint16_t cellId) [constructor]
cls.add_constructor([param('uint16_t', 'cellId')])
## lte-phy-tag.h (module 'lte'): void ns3::LtePhyTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## lte-phy-tag.h (module 'lte'): uint16_t ns3::LtePhyTag::GetCellId() const [member function]
cls.add_method('GetCellId',
'uint16_t',
[],
is_const=True)
## lte-phy-tag.h (module 'lte'): ns3::TypeId ns3::LtePhyTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## lte-phy-tag.h (module 'lte'): uint32_t ns3::LtePhyTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## lte-phy-tag.h (module 'lte'): static ns3::TypeId ns3::LtePhyTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-phy-tag.h (module 'lte'): void ns3::LtePhyTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## lte-phy-tag.h (module 'lte'): void ns3::LtePhyTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
return
def register_Ns3LteRadioBearerTag_methods(root_module, cls):
## lte-radio-bearer-tag.h (module 'lte'): ns3::LteRadioBearerTag::LteRadioBearerTag(ns3::LteRadioBearerTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRadioBearerTag const &', 'arg0')])
## lte-radio-bearer-tag.h (module 'lte'): ns3::LteRadioBearerTag::LteRadioBearerTag() [constructor]
cls.add_constructor([])
## lte-radio-bearer-tag.h (module 'lte'): ns3::LteRadioBearerTag::LteRadioBearerTag(uint16_t rnti, uint8_t lcId) [constructor]
cls.add_constructor([param('uint16_t', 'rnti'), param('uint8_t', 'lcId')])
## lte-radio-bearer-tag.h (module 'lte'): ns3::LteRadioBearerTag::LteRadioBearerTag(uint16_t rnti, uint8_t lcId, uint8_t layer) [constructor]
cls.add_constructor([param('uint16_t', 'rnti'), param('uint8_t', 'lcId'), param('uint8_t', 'layer')])
## lte-radio-bearer-tag.h (module 'lte'): void ns3::LteRadioBearerTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## lte-radio-bearer-tag.h (module 'lte'): ns3::TypeId ns3::LteRadioBearerTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## lte-radio-bearer-tag.h (module 'lte'): uint8_t ns3::LteRadioBearerTag::GetLayer() const [member function]
cls.add_method('GetLayer',
'uint8_t',
[],
is_const=True)
## lte-radio-bearer-tag.h (module 'lte'): uint8_t ns3::LteRadioBearerTag::GetLcid() const [member function]
cls.add_method('GetLcid',
'uint8_t',
[],
is_const=True)
## lte-radio-bearer-tag.h (module 'lte'): uint16_t ns3::LteRadioBearerTag::GetRnti() const [member function]
cls.add_method('GetRnti',
'uint16_t',
[],
is_const=True)
## lte-radio-bearer-tag.h (module 'lte'): uint32_t ns3::LteRadioBearerTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## lte-radio-bearer-tag.h (module 'lte'): static ns3::TypeId ns3::LteRadioBearerTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-radio-bearer-tag.h (module 'lte'): void ns3::LteRadioBearerTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## lte-radio-bearer-tag.h (module 'lte'): void ns3::LteRadioBearerTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## lte-radio-bearer-tag.h (module 'lte'): void ns3::LteRadioBearerTag::SetLayer(uint8_t lcid) [member function]
cls.add_method('SetLayer',
'void',
[param('uint8_t', 'lcid')])
## lte-radio-bearer-tag.h (module 'lte'): void ns3::LteRadioBearerTag::SetLcid(uint8_t lcid) [member function]
cls.add_method('SetLcid',
'void',
[param('uint8_t', 'lcid')])
## lte-radio-bearer-tag.h (module 'lte'): void ns3::LteRadioBearerTag::SetRnti(uint16_t tid) [member function]
cls.add_method('SetRnti',
'void',
[param('uint16_t', 'tid')])
return
def register_Ns3LteRlcAmHeader_methods(root_module, cls):
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::LteRlcAmHeader(ns3::LteRlcAmHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlcAmHeader const &', 'arg0')])
## lte-rlc-am-header.h (module 'lte'): ns3::LteRlcAmHeader::LteRlcAmHeader() [constructor]
cls.add_constructor([])
## lte-rlc-am-header.h (module 'lte'): uint32_t ns3::LteRlcAmHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## lte-rlc-am-header.h (module 'lte'): ns3::SequenceNumber10 ns3::LteRlcAmHeader::GetAckSn() const [member function]
cls.add_method('GetAckSn',
'ns3::SequenceNumber10',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): uint8_t ns3::LteRlcAmHeader::GetFramingInfo() const [member function]
cls.add_method('GetFramingInfo',
'uint8_t',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): ns3::TypeId ns3::LteRlcAmHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## lte-rlc-am-header.h (module 'lte'): uint16_t ns3::LteRlcAmHeader::GetLastOffset() const [member function]
cls.add_method('GetLastOffset',
'uint16_t',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): uint8_t ns3::LteRlcAmHeader::GetLastSegmentFlag() const [member function]
cls.add_method('GetLastSegmentFlag',
'uint8_t',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): uint8_t ns3::LteRlcAmHeader::GetPollingBit() const [member function]
cls.add_method('GetPollingBit',
'uint8_t',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): uint8_t ns3::LteRlcAmHeader::GetResegmentationFlag() const [member function]
cls.add_method('GetResegmentationFlag',
'uint8_t',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): uint16_t ns3::LteRlcAmHeader::GetSegmentOffset() const [member function]
cls.add_method('GetSegmentOffset',
'uint16_t',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): ns3::SequenceNumber10 ns3::LteRlcAmHeader::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'ns3::SequenceNumber10',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): uint32_t ns3::LteRlcAmHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## lte-rlc-am-header.h (module 'lte'): static ns3::TypeId ns3::LteRlcAmHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-rlc-am-header.h (module 'lte'): bool ns3::LteRlcAmHeader::IsControlPdu() const [member function]
cls.add_method('IsControlPdu',
'bool',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): bool ns3::LteRlcAmHeader::IsDataPdu() const [member function]
cls.add_method('IsDataPdu',
'bool',
[],
is_const=True)
## lte-rlc-am-header.h (module 'lte'): uint8_t ns3::LteRlcAmHeader::PopExtensionBit() [member function]
cls.add_method('PopExtensionBit',
'uint8_t',
[])
## lte-rlc-am-header.h (module 'lte'): uint16_t ns3::LteRlcAmHeader::PopLengthIndicator() [member function]
cls.add_method('PopLengthIndicator',
'uint16_t',
[])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::PushExtensionBit(uint8_t extensionBit) [member function]
cls.add_method('PushExtensionBit',
'void',
[param('uint8_t', 'extensionBit')])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::PushLengthIndicator(uint16_t lengthIndicator) [member function]
cls.add_method('PushLengthIndicator',
'void',
[param('uint16_t', 'lengthIndicator')])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::SetAckSn(ns3::SequenceNumber10 ackSn) [member function]
cls.add_method('SetAckSn',
'void',
[param('ns3::SequenceNumber10', 'ackSn')])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::SetControlPdu(uint8_t controlPduType) [member function]
cls.add_method('SetControlPdu',
'void',
[param('uint8_t', 'controlPduType')])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::SetDataPdu() [member function]
cls.add_method('SetDataPdu',
'void',
[])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::SetFramingInfo(uint8_t framingInfo) [member function]
cls.add_method('SetFramingInfo',
'void',
[param('uint8_t', 'framingInfo')])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::SetLastSegmentFlag(uint8_t lsf) [member function]
cls.add_method('SetLastSegmentFlag',
'void',
[param('uint8_t', 'lsf')])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::SetPollingBit(uint8_t pollingBit) [member function]
cls.add_method('SetPollingBit',
'void',
[param('uint8_t', 'pollingBit')])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::SetResegmentationFlag(uint8_t resegFlag) [member function]
cls.add_method('SetResegmentationFlag',
'void',
[param('uint8_t', 'resegFlag')])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::SetSegmentOffset(uint16_t segmentOffset) [member function]
cls.add_method('SetSegmentOffset',
'void',
[param('uint16_t', 'segmentOffset')])
## lte-rlc-am-header.h (module 'lte'): void ns3::LteRlcAmHeader::SetSequenceNumber(ns3::SequenceNumber10 sequenceNumber) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('ns3::SequenceNumber10', 'sequenceNumber')])
return
def register_Ns3LteRlcHeader_methods(root_module, cls):
## lte-rlc-header.h (module 'lte'): ns3::LteRlcHeader::LteRlcHeader(ns3::LteRlcHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlcHeader const &', 'arg0')])
## lte-rlc-header.h (module 'lte'): ns3::LteRlcHeader::LteRlcHeader() [constructor]
cls.add_constructor([])
## lte-rlc-header.h (module 'lte'): uint32_t ns3::LteRlcHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## lte-rlc-header.h (module 'lte'): uint8_t ns3::LteRlcHeader::GetFramingInfo() const [member function]
cls.add_method('GetFramingInfo',
'uint8_t',
[],
is_const=True)
## lte-rlc-header.h (module 'lte'): ns3::TypeId ns3::LteRlcHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## lte-rlc-header.h (module 'lte'): ns3::SequenceNumber10 ns3::LteRlcHeader::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'ns3::SequenceNumber10',
[],
is_const=True)
## lte-rlc-header.h (module 'lte'): uint32_t ns3::LteRlcHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## lte-rlc-header.h (module 'lte'): static ns3::TypeId ns3::LteRlcHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-rlc-header.h (module 'lte'): uint8_t ns3::LteRlcHeader::PopExtensionBit() [member function]
cls.add_method('PopExtensionBit',
'uint8_t',
[])
## lte-rlc-header.h (module 'lte'): uint16_t ns3::LteRlcHeader::PopLengthIndicator() [member function]
cls.add_method('PopLengthIndicator',
'uint16_t',
[])
## lte-rlc-header.h (module 'lte'): void ns3::LteRlcHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## lte-rlc-header.h (module 'lte'): void ns3::LteRlcHeader::PushExtensionBit(uint8_t extensionBit) [member function]
cls.add_method('PushExtensionBit',
'void',
[param('uint8_t', 'extensionBit')])
## lte-rlc-header.h (module 'lte'): void ns3::LteRlcHeader::PushLengthIndicator(uint16_t lengthIndicator) [member function]
cls.add_method('PushLengthIndicator',
'void',
[param('uint16_t', 'lengthIndicator')])
## lte-rlc-header.h (module 'lte'): void ns3::LteRlcHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## lte-rlc-header.h (module 'lte'): void ns3::LteRlcHeader::SetFramingInfo(uint8_t framingInfo) [member function]
cls.add_method('SetFramingInfo',
'void',
[param('uint8_t', 'framingInfo')])
## lte-rlc-header.h (module 'lte'): void ns3::LteRlcHeader::SetSequenceNumber(ns3::SequenceNumber10 sequenceNumber) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('ns3::SequenceNumber10', 'sequenceNumber')])
return
def register_Ns3LteRlcSduStatusTag_methods(root_module, cls):
## lte-rlc-sdu-status-tag.h (module 'lte'): ns3::LteRlcSduStatusTag::LteRlcSduStatusTag(ns3::LteRlcSduStatusTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlcSduStatusTag const &', 'arg0')])
## lte-rlc-sdu-status-tag.h (module 'lte'): ns3::LteRlcSduStatusTag::LteRlcSduStatusTag() [constructor]
cls.add_constructor([])
## lte-rlc-sdu-status-tag.h (module 'lte'): void ns3::LteRlcSduStatusTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## lte-rlc-sdu-status-tag.h (module 'lte'): ns3::TypeId ns3::LteRlcSduStatusTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## lte-rlc-sdu-status-tag.h (module 'lte'): uint32_t ns3::LteRlcSduStatusTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## lte-rlc-sdu-status-tag.h (module 'lte'): uint8_t ns3::LteRlcSduStatusTag::GetStatus() const [member function]
cls.add_method('GetStatus',
'uint8_t',
[],
is_const=True)
## lte-rlc-sdu-status-tag.h (module 'lte'): static ns3::TypeId ns3::LteRlcSduStatusTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-rlc-sdu-status-tag.h (module 'lte'): void ns3::LteRlcSduStatusTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## lte-rlc-sdu-status-tag.h (module 'lte'): void ns3::LteRlcSduStatusTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## lte-rlc-sdu-status-tag.h (module 'lte'): void ns3::LteRlcSduStatusTag::SetStatus(uint8_t status) [member function]
cls.add_method('SetStatus',
'void',
[param('uint8_t', 'status')])
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_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_Ns3PacketBurst_methods(root_module, cls):
## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst(ns3::PacketBurst const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketBurst const &', 'arg0')])
## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst() [constructor]
cls.add_constructor([])
## packet-burst.h (module 'network'): void ns3::PacketBurst::AddPacket(ns3::Ptr<ns3::Packet> packet) [member function]
cls.add_method('AddPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet')])
## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): ns3::Ptr<ns3::PacketBurst> ns3::PacketBurst::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::PacketBurst >',
[],
is_const=True)
## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetNPackets() const [member function]
cls.add_method('GetNPackets',
'uint32_t',
[],
is_const=True)
## packet-burst.h (module 'network'): std::list<ns3::Ptr<ns3::Packet>, std::allocator<ns3::Ptr<ns3::Packet> > > ns3::PacketBurst::GetPackets() const [member function]
cls.add_method('GetPackets',
'std::list< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet-burst.h (module 'network'): static ns3::TypeId ns3::PacketBurst::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-burst.h (module 'network'): void ns3::PacketBurst::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
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_Ns3PdcpTag_methods(root_module, cls):
## lte-pdcp-tag.h (module 'lte'): ns3::PdcpTag::PdcpTag(ns3::PdcpTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PdcpTag const &', 'arg0')])
## lte-pdcp-tag.h (module 'lte'): ns3::PdcpTag::PdcpTag() [constructor]
cls.add_constructor([])
## lte-pdcp-tag.h (module 'lte'): ns3::PdcpTag::PdcpTag(ns3::Time senderTimestamp) [constructor]
cls.add_constructor([param('ns3::Time', 'senderTimestamp')])
## lte-pdcp-tag.h (module 'lte'): void ns3::PdcpTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## lte-pdcp-tag.h (module 'lte'): ns3::TypeId ns3::PdcpTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## lte-pdcp-tag.h (module 'lte'): ns3::Time ns3::PdcpTag::GetSenderTimestamp() const [member function]
cls.add_method('GetSenderTimestamp',
'ns3::Time',
[],
is_const=True)
## lte-pdcp-tag.h (module 'lte'): uint32_t ns3::PdcpTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## lte-pdcp-tag.h (module 'lte'): static ns3::TypeId ns3::PdcpTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-pdcp-tag.h (module 'lte'): void ns3::PdcpTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## lte-pdcp-tag.h (module 'lte'): void ns3::PdcpTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## lte-pdcp-tag.h (module 'lte'): void ns3::PdcpTag::SetSenderTimestamp(ns3::Time senderTimestamp) [member function]
cls.add_method('SetSenderTimestamp',
'void',
[param('ns3::Time', 'senderTimestamp')])
return
def register_Ns3RadioEnvironmentMapHelper_methods(root_module, cls):
## radio-environment-map-helper.h (module 'lte'): ns3::RadioEnvironmentMapHelper::RadioEnvironmentMapHelper() [constructor]
cls.add_constructor([])
## radio-environment-map-helper.h (module 'lte'): void ns3::RadioEnvironmentMapHelper::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## radio-environment-map-helper.h (module 'lte'): uint8_t ns3::RadioEnvironmentMapHelper::GetBandwidth() const [member function]
cls.add_method('GetBandwidth',
'uint8_t',
[],
is_const=True)
## radio-environment-map-helper.h (module 'lte'): static ns3::TypeId ns3::RadioEnvironmentMapHelper::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## radio-environment-map-helper.h (module 'lte'): void ns3::RadioEnvironmentMapHelper::Install() [member function]
cls.add_method('Install',
'void',
[])
## radio-environment-map-helper.h (module 'lte'): void ns3::RadioEnvironmentMapHelper::SetBandwidth(uint8_t bw) [member function]
cls.add_method('SetBandwidth',
'void',
[param('uint8_t', 'bw')])
return
def register_Ns3RlcTag_methods(root_module, cls):
## lte-rlc-tag.h (module 'lte'): ns3::RlcTag::RlcTag(ns3::RlcTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RlcTag const &', 'arg0')])
## lte-rlc-tag.h (module 'lte'): ns3::RlcTag::RlcTag() [constructor]
cls.add_constructor([])
## lte-rlc-tag.h (module 'lte'): ns3::RlcTag::RlcTag(ns3::Time senderTimestamp) [constructor]
cls.add_constructor([param('ns3::Time', 'senderTimestamp')])
## lte-rlc-tag.h (module 'lte'): void ns3::RlcTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## lte-rlc-tag.h (module 'lte'): ns3::TypeId ns3::RlcTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## lte-rlc-tag.h (module 'lte'): ns3::Time ns3::RlcTag::GetSenderTimestamp() const [member function]
cls.add_method('GetSenderTimestamp',
'ns3::Time',
[],
is_const=True)
## lte-rlc-tag.h (module 'lte'): uint32_t ns3::RlcTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## lte-rlc-tag.h (module 'lte'): static ns3::TypeId ns3::RlcTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-rlc-tag.h (module 'lte'): void ns3::RlcTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## lte-rlc-tag.h (module 'lte'): void ns3::RlcTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## lte-rlc-tag.h (module 'lte'): void ns3::RlcTag::SetSenderTimestamp(ns3::Time senderTimestamp) [member function]
cls.add_method('SetSenderTimestamp',
'void',
[param('ns3::Time', 'senderTimestamp')])
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__Ns3EpcTft_Ns3Empty_Ns3DefaultDeleter__lt__ns3EpcTft__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EpcTft, ns3::empty, ns3::DefaultDeleter<ns3::EpcTft> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EpcTft, ns3::empty, ns3::DefaultDeleter<ns3::EpcTft> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EpcTft, ns3::empty, ns3::DefaultDeleter<ns3::EpcTft> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::EpcTft, ns3::empty, ns3::DefaultDeleter< ns3::EpcTft > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EpcTft, ns3::empty, ns3::DefaultDeleter<ns3::EpcTft> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3EpcTftClassifier_Ns3Empty_Ns3DefaultDeleter__lt__ns3EpcTftClassifier__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EpcTftClassifier, ns3::empty, ns3::DefaultDeleter<ns3::EpcTftClassifier> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EpcTftClassifier, ns3::empty, ns3::DefaultDeleter<ns3::EpcTftClassifier> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EpcTftClassifier, ns3::empty, ns3::DefaultDeleter<ns3::EpcTftClassifier> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::EpcTftClassifier, ns3::empty, ns3::DefaultDeleter< ns3::EpcTftClassifier > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EpcTftClassifier, ns3::empty, ns3::DefaultDeleter<ns3::EpcTftClassifier> >::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__Ns3IdealControlMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3IdealControlMessage__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::IdealControlMessage, ns3::empty, ns3::DefaultDeleter<ns3::IdealControlMessage> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::IdealControlMessage, ns3::empty, ns3::DefaultDeleter<ns3::IdealControlMessage> >::SimpleRefCount(ns3::SimpleRefCount<ns3::IdealControlMessage, ns3::empty, ns3::DefaultDeleter<ns3::IdealControlMessage> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::IdealControlMessage, ns3::empty, ns3::DefaultDeleter< ns3::IdealControlMessage > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::IdealControlMessage, ns3::empty, ns3::DefaultDeleter<ns3::IdealControlMessage> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3LteSinrChunkProcessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3LteSinrChunkProcessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::LteSinrChunkProcessor, ns3::empty, ns3::DefaultDeleter<ns3::LteSinrChunkProcessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::LteSinrChunkProcessor, ns3::empty, ns3::DefaultDeleter<ns3::LteSinrChunkProcessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::LteSinrChunkProcessor, ns3::empty, ns3::DefaultDeleter<ns3::LteSinrChunkProcessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::LteSinrChunkProcessor, ns3::empty, ns3::DefaultDeleter< ns3::LteSinrChunkProcessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::LteSinrChunkProcessor, ns3::empty, ns3::DefaultDeleter<ns3::LteSinrChunkProcessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3SpectrumModel_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumModel__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter< ns3::SpectrumModel > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SpectrumModel, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumModel> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3SpectrumSignalParameters_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumSignalParameters__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter< ns3::SpectrumSignalParameters > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3SpectrumValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumValue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter< ns3::SpectrumValue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Socket_methods(root_module, cls):
## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Socket const &', 'arg0')])
## socket.h (module 'network'): ns3::Socket::Socket() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function]
cls.add_method('Bind',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind() [member function]
cls.add_method('Bind',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind6() [member function]
cls.add_method('Bind6',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function]
cls.add_method('BindToNetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'netdevice')],
is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Close() [member function]
cls.add_method('Close',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function]
cls.add_method('Connect',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')],
is_static=True)
## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function]
cls.add_method('GetAllowBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function]
cls.add_method('GetBoundNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[])
## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function]
cls.add_method('GetErrno',
'ns3::Socket::SocketErrno',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function]
cls.add_method('GetRxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function]
cls.add_method('GetSockName',
'int',
[param('ns3::Address &', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function]
cls.add_method('GetSocketType',
'ns3::Socket::SocketType',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function]
cls.add_method('GetTxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function]
cls.add_method('IsRecvPktInfo',
'bool',
[],
is_const=True)
## socket.h (module 'network'): int ns3::Socket::Listen() [member function]
cls.add_method('Listen',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[])
## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Recv',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function]
cls.add_method('SendTo',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function]
cls.add_method('SendTo',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')])
## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function]
cls.add_method('SetAcceptCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')])
## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function]
cls.add_method('SetAllowBroadcast',
'bool',
[param('bool', 'allowBroadcast')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function]
cls.add_method('SetCloseCallbacks',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')])
## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function]
cls.add_method('SetConnectCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')])
## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function]
cls.add_method('SetDataSentCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')])
## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function]
cls.add_method('SetRecvCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')])
## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function]
cls.add_method('SetRecvPktInfo',
'void',
[param('bool', 'flag')])
## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function]
cls.add_method('SetSendCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')])
## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function]
cls.add_method('ShutdownRecv',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function]
cls.add_method('ShutdownSend',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function]
cls.add_method('NotifyConnectionFailed',
'void',
[],
visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function]
cls.add_method('NotifyConnectionRequest',
'bool',
[param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function]
cls.add_method('NotifyConnectionSucceeded',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function]
cls.add_method('NotifyDataRecv',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function]
cls.add_method('NotifyDataSent',
'void',
[param('uint32_t', 'size')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function]
cls.add_method('NotifyErrorClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function]
cls.add_method('NotifyNewConnectionCreated',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function]
cls.add_method('NotifyNormalClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function]
cls.add_method('NotifySend',
'void',
[param('uint32_t', 'spaceAvailable')],
visibility='protected')
return
def register_Ns3SocketAddressTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::Address ns3::SocketAddressTag::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketAddressTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketAddressTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketAddressTag::SetAddress(ns3::Address addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'addr')])
return
def register_Ns3SocketIpTtlTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function]
cls.add_method('GetTtl',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function]
cls.add_method('SetTtl',
'void',
[param('uint8_t', 'ttl')])
return
def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
return
def register_Ns3SpectrumInterference_methods(root_module, cls):
## spectrum-interference.h (module 'spectrum'): ns3::SpectrumInterference::SpectrumInterference(ns3::SpectrumInterference const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SpectrumInterference const &', 'arg0')])
## spectrum-interference.h (module 'spectrum'): ns3::SpectrumInterference::SpectrumInterference() [constructor]
cls.add_constructor([])
## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::AbortRx() [member function]
cls.add_method('AbortRx',
'void',
[])
## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::AddSignal(ns3::Ptr<ns3::SpectrumValue const> spd, ns3::Time const duration) [member function]
cls.add_method('AddSignal',
'void',
[param('ns3::Ptr< ns3::SpectrumValue const >', 'spd'), param('ns3::Time const', 'duration')])
## spectrum-interference.h (module 'spectrum'): bool ns3::SpectrumInterference::EndRx() [member function]
cls.add_method('EndRx',
'bool',
[])
## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::SetErrorModel(ns3::Ptr<ns3::SpectrumErrorModel> e) [member function]
cls.add_method('SetErrorModel',
'void',
[param('ns3::Ptr< ns3::SpectrumErrorModel >', 'e')])
## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::SetNoisePowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> noisePsd) [member function]
cls.add_method('SetNoisePowerSpectralDensity',
'void',
[param('ns3::Ptr< ns3::SpectrumValue const >', 'noisePsd')])
## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::StartRx(ns3::Ptr<const ns3::Packet> p, ns3::Ptr<ns3::SpectrumValue const> rxPsd) [member function]
cls.add_method('StartRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ptr< ns3::SpectrumValue const >', 'rxPsd')])
## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3SpectrumModel_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## spectrum-model.h (module 'spectrum'): ns3::SpectrumModel::SpectrumModel(ns3::SpectrumModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SpectrumModel const &', 'arg0')])
## spectrum-model.h (module 'spectrum'): ns3::SpectrumModel::SpectrumModel(std::vector<double, std::allocator<double> > centerFreqs) [constructor]
cls.add_constructor([param('std::vector< double >', 'centerFreqs')])
## spectrum-model.h (module 'spectrum'): ns3::SpectrumModel::SpectrumModel(ns3::Bands bands) [constructor]
cls.add_constructor([param('ns3::Bands', 'bands')])
## spectrum-model.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const ns3::BandInfo*,std::vector<ns3::BandInfo, std::allocator<ns3::BandInfo> > > ns3::SpectrumModel::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::BandInfo const *, std::vector< ns3::BandInfo > >',
[],
is_const=True)
## spectrum-model.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const ns3::BandInfo*,std::vector<ns3::BandInfo, std::allocator<ns3::BandInfo> > > ns3::SpectrumModel::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::BandInfo const *, std::vector< ns3::BandInfo > >',
[],
is_const=True)
## spectrum-model.h (module 'spectrum'): size_t ns3::SpectrumModel::GetNumBands() const [member function]
cls.add_method('GetNumBands',
'size_t',
[],
is_const=True)
## spectrum-model.h (module 'spectrum'): ns3::SpectrumModelUid_t ns3::SpectrumModel::GetUid() const [member function]
cls.add_method('GetUid',
'ns3::SpectrumModelUid_t',
[],
is_const=True)
return
def register_Ns3SpectrumPhy_methods(root_module, cls):
## spectrum-phy.h (module 'spectrum'): ns3::SpectrumPhy::SpectrumPhy() [constructor]
cls.add_constructor([])
## spectrum-phy.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'd')],
is_pure_virtual=True, is_virtual=True)
## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::SpectrumPhy::GetDevice() [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_pure_virtual=True, is_virtual=True)
## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function]
cls.add_method('SetMobility',
'void',
[param('ns3::Ptr< ns3::MobilityModel >', 'm')],
is_pure_virtual=True, is_virtual=True)
## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::SpectrumPhy::GetMobility() [member function]
cls.add_method('GetMobility',
'ns3::Ptr< ns3::MobilityModel >',
[],
is_pure_virtual=True, is_virtual=True)
## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::SpectrumChannel >', 'c')],
is_pure_virtual=True, is_virtual=True)
## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::SpectrumPhy::GetRxSpectrumModel() const [member function]
cls.add_method('GetRxSpectrumModel',
'ns3::Ptr< ns3::SpectrumModel const >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::SpectrumPhy::GetRxAntenna() [member function]
cls.add_method('GetRxAntenna',
'ns3::Ptr< ns3::AntennaModel >',
[],
is_pure_virtual=True, is_virtual=True)
## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function]
cls.add_method('StartRx',
'void',
[param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3SpectrumPropagationLossModel_methods(root_module, cls):
## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::SpectrumPropagationLossModel::SpectrumPropagationLossModel(ns3::SpectrumPropagationLossModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SpectrumPropagationLossModel const &', 'arg0')])
## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::SpectrumPropagationLossModel::SpectrumPropagationLossModel() [constructor]
cls.add_constructor([])
## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumPropagationLossModel::CalcRxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> txPsd, ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function]
cls.add_method('CalcRxPowerSpectralDensity',
'ns3::Ptr< ns3::SpectrumValue >',
[param('ns3::Ptr< ns3::SpectrumValue const >', 'txPsd'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')],
is_const=True)
## spectrum-propagation-loss-model.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## spectrum-propagation-loss-model.h (module 'spectrum'): void ns3::SpectrumPropagationLossModel::SetNext(ns3::Ptr<ns3::SpectrumPropagationLossModel> next) [member function]
cls.add_method('SetNext',
'void',
[param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'next')])
## spectrum-propagation-loss-model.h (module 'spectrum'): void ns3::SpectrumPropagationLossModel::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumPropagationLossModel::DoCalcRxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> txPsd, ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPowerSpectralDensity',
'ns3::Ptr< ns3::SpectrumValue >',
[param('ns3::Ptr< ns3::SpectrumValue const >', 'txPsd'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3SpectrumSignalParameters_methods(root_module, cls):
## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::SpectrumSignalParameters() [constructor]
cls.add_constructor([])
## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::SpectrumSignalParameters(ns3::SpectrumSignalParameters const & p) [copy constructor]
cls.add_constructor([param('ns3::SpectrumSignalParameters const &', 'p')])
## spectrum-signal-parameters.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumSignalParameters> ns3::SpectrumSignalParameters::Copy() [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::SpectrumSignalParameters >',
[],
is_virtual=True)
## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::duration [variable]
cls.add_instance_attribute('duration', 'ns3::Time', is_const=False)
## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::psd [variable]
cls.add_instance_attribute('psd', 'ns3::Ptr< ns3::SpectrumValue >', is_const=False)
## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::txAntenna [variable]
cls.add_instance_attribute('txAntenna', 'ns3::Ptr< ns3::AntennaModel >', is_const=False)
## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::txPhy [variable]
cls.add_instance_attribute('txPhy', 'ns3::Ptr< ns3::SpectrumPhy >', is_const=False)
return
def register_Ns3SpectrumValue_methods(root_module, cls):
cls.add_binary_numeric_operator('*', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', 'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('-', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', 'right'))
cls.add_output_stream_operator()
cls.add_inplace_numeric_operator('*=', param('ns3::SpectrumValue const &', 'right'))
cls.add_inplace_numeric_operator('*=', param('double', 'right'))
cls.add_inplace_numeric_operator('+=', param('ns3::SpectrumValue const &', 'right'))
cls.add_inplace_numeric_operator('+=', param('double', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::SpectrumValue const &', 'right'))
cls.add_inplace_numeric_operator('-=', param('double', 'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::SpectrumValue const &', 'right'))
cls.add_inplace_numeric_operator('/=', param('double', 'right'))
## spectrum-value.h (module 'spectrum'): ns3::SpectrumValue::SpectrumValue(ns3::SpectrumValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SpectrumValue const &', 'arg0')])
## spectrum-value.h (module 'spectrum'): ns3::SpectrumValue::SpectrumValue(ns3::Ptr<ns3::SpectrumModel const> sm) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::SpectrumModel const >', 'sm')])
## spectrum-value.h (module 'spectrum'): ns3::SpectrumValue::SpectrumValue() [constructor]
cls.add_constructor([])
## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const ns3::BandInfo*,std::vector<ns3::BandInfo, std::allocator<ns3::BandInfo> > > ns3::SpectrumValue::ConstBandsBegin() const [member function]
cls.add_method('ConstBandsBegin',
'__gnu_cxx::__normal_iterator< ns3::BandInfo const *, std::vector< ns3::BandInfo > >',
[],
is_const=True)
## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const ns3::BandInfo*,std::vector<ns3::BandInfo, std::allocator<ns3::BandInfo> > > ns3::SpectrumValue::ConstBandsEnd() const [member function]
cls.add_method('ConstBandsEnd',
'__gnu_cxx::__normal_iterator< ns3::BandInfo const *, std::vector< ns3::BandInfo > >',
[],
is_const=True)
## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const double*,std::vector<double, std::allocator<double> > > ns3::SpectrumValue::ConstValuesBegin() const [member function]
cls.add_method('ConstValuesBegin',
'__gnu_cxx::__normal_iterator< double const *, std::vector< double > >',
[],
is_const=True)
## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<const double*,std::vector<double, std::allocator<double> > > ns3::SpectrumValue::ConstValuesEnd() const [member function]
cls.add_method('ConstValuesEnd',
'__gnu_cxx::__normal_iterator< double const *, std::vector< double > >',
[],
is_const=True)
## spectrum-value.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::SpectrumValue >',
[],
is_const=True)
## spectrum-value.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::SpectrumValue::GetSpectrumModel() const [member function]
cls.add_method('GetSpectrumModel',
'ns3::Ptr< ns3::SpectrumModel const >',
[],
is_const=True)
## spectrum-value.h (module 'spectrum'): ns3::SpectrumModelUid_t ns3::SpectrumValue::GetSpectrumModelUid() const [member function]
cls.add_method('GetSpectrumModelUid',
'ns3::SpectrumModelUid_t',
[],
is_const=True)
## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<double*,std::vector<double, std::allocator<double> > > ns3::SpectrumValue::ValuesBegin() [member function]
cls.add_method('ValuesBegin',
'__gnu_cxx::__normal_iterator< double *, std::vector< double > >',
[])
## spectrum-value.h (module 'spectrum'): __gnu_cxx::__normal_iterator<double*,std::vector<double, std::allocator<double> > > ns3::SpectrumValue::ValuesEnd() [member function]
cls.add_method('ValuesEnd',
'__gnu_cxx::__normal_iterator< double *, std::vector< double > >',
[])
return
def register_Ns3Time_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor]
cls.add_constructor([param('ns3::Time const &', 'o')])
## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'value')])
## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function]
cls.add_method('Compare',
'int',
[param('ns3::Time const &', 'o')],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function]
cls.add_method('GetFemtoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function]
cls.add_method('GetInteger',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function]
cls.add_method('GetMicroSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function]
cls.add_method('GetMilliSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function]
cls.add_method('GetNanoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function]
cls.add_method('GetPicoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function]
cls.add_method('GetResolution',
'ns3::Time::Unit',
[],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function]
cls.add_method('GetSeconds',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function]
cls.add_method('GetTimeStep',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function]
cls.add_method('IsNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function]
cls.add_method('IsPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function]
cls.add_method('IsStrictlyNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function]
cls.add_method('IsStrictlyPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function]
cls.add_method('IsZero',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function]
cls.add_method('SetResolution',
'void',
[param('ns3::Time::Unit', 'resolution')],
is_static=True)
## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
return
def register_Ns3TraceFadingLossModel_methods(root_module, cls):
## trace-fading-loss-model.h (module 'lte'): ns3::TraceFadingLossModel::TraceFadingLossModel(ns3::TraceFadingLossModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TraceFadingLossModel const &', 'arg0')])
## trace-fading-loss-model.h (module 'lte'): ns3::TraceFadingLossModel::TraceFadingLossModel() [constructor]
cls.add_constructor([])
## trace-fading-loss-model.h (module 'lte'): void ns3::TraceFadingLossModel::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
is_virtual=True)
## trace-fading-loss-model.h (module 'lte'): static ns3::TypeId ns3::TraceFadingLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## trace-fading-loss-model.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::TraceFadingLossModel::DoCalcRxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> txPsd, ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPowerSpectralDensity',
'ns3::Ptr< ns3::SpectrumValue >',
[param('ns3::Ptr< ns3::SpectrumValue const >', 'txPsd'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')],
is_const=True, visibility='private', is_virtual=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_Ns3UeInfo_methods(root_module, cls):
## lte-enb-rrc.h (module 'lte'): ns3::UeInfo::UeInfo(ns3::UeInfo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UeInfo const &', 'arg0')])
## lte-enb-rrc.h (module 'lte'): ns3::UeInfo::UeInfo() [constructor]
cls.add_constructor([])
## lte-enb-rrc.h (module 'lte'): ns3::UeInfo::UeInfo(uint64_t imsi) [constructor]
cls.add_constructor([param('uint64_t', 'imsi')])
## lte-enb-rrc.h (module 'lte'): uint8_t ns3::UeInfo::AddRadioBearer(ns3::Ptr<ns3::LteRadioBearerInfo> radioBearerInfo) [member function]
cls.add_method('AddRadioBearer',
'uint8_t',
[param('ns3::Ptr< ns3::LteRadioBearerInfo >', 'radioBearerInfo')])
## lte-enb-rrc.h (module 'lte'): uint64_t ns3::UeInfo::GetImsi() [member function]
cls.add_method('GetImsi',
'uint64_t',
[])
## lte-enb-rrc.h (module 'lte'): ns3::Ptr<ns3::LteRadioBearerInfo> ns3::UeInfo::GetRadioBearer(uint8_t lcid) [member function]
cls.add_method('GetRadioBearer',
'ns3::Ptr< ns3::LteRadioBearerInfo >',
[param('uint8_t', 'lcid')])
## lte-enb-rrc.h (module 'lte'): static ns3::TypeId ns3::UeInfo::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-enb-rrc.h (module 'lte'): void ns3::UeInfo::RemoveRadioBearer(uint8_t lcid) [member function]
cls.add_method('RemoveRadioBearer',
'void',
[param('uint8_t', 'lcid')])
return
def register_Ns3Application_methods(root_module, cls):
## application.h (module 'network'): ns3::Application::Application(ns3::Application const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Application const &', 'arg0')])
## application.h (module 'network'): ns3::Application::Application() [constructor]
cls.add_constructor([])
## application.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Application::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True)
## application.h (module 'network'): static ns3::TypeId ns3::Application::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## application.h (module 'network'): void ns3::Application::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## application.h (module 'network'): void ns3::Application::SetStartTime(ns3::Time start) [member function]
cls.add_method('SetStartTime',
'void',
[param('ns3::Time', 'start')])
## application.h (module 'network'): void ns3::Application::SetStopTime(ns3::Time stop) [member function]
cls.add_method('SetStopTime',
'void',
[param('ns3::Time', 'stop')])
## application.h (module 'network'): void ns3::Application::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## application.h (module 'network'): void ns3::Application::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
## application.h (module 'network'): void ns3::Application::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## application.h (module 'network'): void ns3::Application::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3BooleanChecker_methods(root_module, cls):
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')])
return
def register_Ns3BooleanValue_methods(root_module, cls):
cls.add_output_stream_operator()
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor]
cls.add_constructor([param('bool', 'value')])
## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function]
cls.add_method('Get',
'bool',
[],
is_const=True)
## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function]
cls.add_method('Set',
'void',
[param('bool', 'value')])
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): 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_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_Ns3DataCalculator_methods(root_module, cls):
## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator(ns3::DataCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataCalculator const &', 'arg0')])
## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator() [constructor]
cls.add_constructor([])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetContext() const [member function]
cls.add_method('GetContext',
'std::string',
[],
is_const=True)
## data-calculator.h (module 'stats'): bool ns3::DataCalculator::GetEnabled() const [member function]
cls.add_method('GetEnabled',
'bool',
[],
is_const=True)
## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetKey() const [member function]
cls.add_method('GetKey',
'std::string',
[],
is_const=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetContext(std::string const context) [member function]
cls.add_method('SetContext',
'void',
[param('std::string const', 'context')])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetKey(std::string const key) [member function]
cls.add_method('SetKey',
'void',
[param('std::string const', 'key')])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Start(ns3::Time const & startTime) [member function]
cls.add_method('Start',
'void',
[param('ns3::Time const &', 'startTime')],
is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Stop(ns3::Time const & stopTime) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'stopTime')],
is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3DataOutputInterface_methods(root_module, cls):
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface(ns3::DataOutputInterface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataOutputInterface const &', 'arg0')])
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface() [constructor]
cls.add_constructor([])
## data-output-interface.h (module 'stats'): std::string ns3::DataOutputInterface::GetFilePrefix() const [member function]
cls.add_method('GetFilePrefix',
'std::string',
[],
is_const=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::Output(ns3::DataCollector & dc) [member function]
cls.add_method('Output',
'void',
[param('ns3::DataCollector &', 'dc')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::SetFilePrefix(std::string const prefix) [member function]
cls.add_method('SetFilePrefix',
'void',
[param('std::string const', 'prefix')])
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3DataRateChecker_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')])
return
def register_Ns3DataRateValue_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor]
cls.add_constructor([param('ns3::DataRate const &', 'value')])
## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## data-rate.h (module 'network'): bool ns3::DataRateValue::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)
## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function]
cls.add_method('Get',
'ns3::DataRate',
[],
is_const=True)
## data-rate.h (module 'network'): std::string ns3::DataRateValue::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)
## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::DataRate const &', 'value')])
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_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, visibility='private', is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
visibility='private', is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EnumChecker_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): void ns3::EnumChecker::Add(int v, std::string name) [member function]
cls.add_method('Add',
'void',
[param('int', 'v'), param('std::string', 'name')])
## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int v, std::string name) [member function]
cls.add_method('AddDefault',
'void',
[param('int', 'v'), param('std::string', 'name')])
## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EnumValue_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumValue const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): ns3::EnumValue::EnumValue(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function]
cls.add_method('Get',
'int',
[],
is_const=True)
## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): void ns3::EnumValue::Set(int v) [member function]
cls.add_method('Set',
'void',
[param('int', 'v')])
return
def register_Ns3EpcEnbApplication_methods(root_module, cls):
## epc-enb-application.h (module 'lte'): ns3::EpcEnbApplication::EpcEnbApplication(ns3::EpcEnbApplication const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EpcEnbApplication const &', 'arg0')])
## epc-enb-application.h (module 'lte'): ns3::EpcEnbApplication::EpcEnbApplication(ns3::Ptr<ns3::Socket> lteSocket, ns3::Ptr<ns3::Socket> s1uSocket, ns3::Ipv4Address sgwAddress) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Socket >', 'lteSocket'), param('ns3::Ptr< ns3::Socket >', 's1uSocket'), param('ns3::Ipv4Address', 'sgwAddress')])
## epc-enb-application.h (module 'lte'): void ns3::EpcEnbApplication::ErabSetupRequest(uint32_t teid, uint16_t rnti, uint8_t lcid) [member function]
cls.add_method('ErabSetupRequest',
'void',
[param('uint32_t', 'teid'), param('uint16_t', 'rnti'), param('uint8_t', 'lcid')])
## epc-enb-application.h (module 'lte'): static ns3::TypeId ns3::EpcEnbApplication::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## epc-enb-application.h (module 'lte'): void ns3::EpcEnbApplication::RecvFromLteSocket(ns3::Ptr<ns3::Socket> socket) [member function]
cls.add_method('RecvFromLteSocket',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket')])
## epc-enb-application.h (module 'lte'): void ns3::EpcEnbApplication::RecvFromS1uSocket(ns3::Ptr<ns3::Socket> socket) [member function]
cls.add_method('RecvFromS1uSocket',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket')])
## epc-enb-application.h (module 'lte'): void ns3::EpcEnbApplication::SendToLteSocket(ns3::Ptr<ns3::Packet> packet, uint16_t rnti, uint8_t lcid) [member function]
cls.add_method('SendToLteSocket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint16_t', 'rnti'), param('uint8_t', 'lcid')])
## epc-enb-application.h (module 'lte'): void ns3::EpcEnbApplication::SendToS1uSocket(ns3::Ptr<ns3::Packet> packet, uint32_t teid) [member function]
cls.add_method('SendToS1uSocket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint32_t', 'teid')])
return
def register_Ns3EpcHelper_methods(root_module, cls):
## epc-helper.h (module 'lte'): ns3::EpcHelper::EpcHelper(ns3::EpcHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EpcHelper const &', 'arg0')])
## epc-helper.h (module 'lte'): ns3::EpcHelper::EpcHelper() [constructor]
cls.add_constructor([])
## epc-helper.h (module 'lte'): void ns3::EpcHelper::ActivateEpsBearer(ns3::Ptr<ns3::NetDevice> ueLteDevice, ns3::Ptr<ns3::NetDevice> enbLteDevice, ns3::Ptr<ns3::EpcTft> tft, uint16_t rnti, uint8_t lcid) [member function]
cls.add_method('ActivateEpsBearer',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'ueLteDevice'), param('ns3::Ptr< ns3::NetDevice >', 'enbLteDevice'), param('ns3::Ptr< ns3::EpcTft >', 'tft'), param('uint16_t', 'rnti'), param('uint8_t', 'lcid')])
## epc-helper.h (module 'lte'): void ns3::EpcHelper::AddEnb(ns3::Ptr<ns3::Node> enbNode, ns3::Ptr<ns3::NetDevice> lteEnbNetDevice) [member function]
cls.add_method('AddEnb',
'void',
[param('ns3::Ptr< ns3::Node >', 'enbNode'), param('ns3::Ptr< ns3::NetDevice >', 'lteEnbNetDevice')])
## epc-helper.h (module 'lte'): ns3::Ipv4InterfaceContainer ns3::EpcHelper::AssignUeIpv4Address(ns3::NetDeviceContainer ueDevices) [member function]
cls.add_method('AssignUeIpv4Address',
'ns3::Ipv4InterfaceContainer',
[param('ns3::NetDeviceContainer', 'ueDevices')])
## epc-helper.h (module 'lte'): void ns3::EpcHelper::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## epc-helper.h (module 'lte'): ns3::Ptr<ns3::Node> ns3::EpcHelper::GetPgwNode() [member function]
cls.add_method('GetPgwNode',
'ns3::Ptr< ns3::Node >',
[])
## epc-helper.h (module 'lte'): static ns3::TypeId ns3::EpcHelper::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## epc-helper.h (module 'lte'): ns3::Ipv4Address ns3::EpcHelper::GetUeDefaultGatewayAddress() [member function]
cls.add_method('GetUeDefaultGatewayAddress',
'ns3::Ipv4Address',
[])
return
def register_Ns3EpcSgwPgwApplication_methods(root_module, cls):
## epc-sgw-pgw-application.h (module 'lte'): ns3::EpcSgwPgwApplication::EpcSgwPgwApplication(ns3::EpcSgwPgwApplication const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EpcSgwPgwApplication const &', 'arg0')])
## epc-sgw-pgw-application.h (module 'lte'): ns3::EpcSgwPgwApplication::EpcSgwPgwApplication(ns3::Ptr<ns3::VirtualNetDevice> const tunDevice, ns3::Ptr<ns3::Socket> const s1uSocket) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::VirtualNetDevice > const', 'tunDevice'), param('ns3::Ptr< ns3::Socket > const', 's1uSocket')])
## epc-sgw-pgw-application.h (module 'lte'): uint32_t ns3::EpcSgwPgwApplication::ActivateS1Bearer(ns3::Ipv4Address ueAddr, ns3::Ipv4Address enbAddr, ns3::Ptr<ns3::EpcTft> tft) [member function]
cls.add_method('ActivateS1Bearer',
'uint32_t',
[param('ns3::Ipv4Address', 'ueAddr'), param('ns3::Ipv4Address', 'enbAddr'), param('ns3::Ptr< ns3::EpcTft >', 'tft')])
## epc-sgw-pgw-application.h (module 'lte'): void ns3::EpcSgwPgwApplication::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## epc-sgw-pgw-application.h (module 'lte'): static ns3::TypeId ns3::EpcSgwPgwApplication::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## epc-sgw-pgw-application.h (module 'lte'): void ns3::EpcSgwPgwApplication::RecvFromS1uSocket(ns3::Ptr<ns3::Socket> socket) [member function]
cls.add_method('RecvFromS1uSocket',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket')])
## epc-sgw-pgw-application.h (module 'lte'): bool ns3::EpcSgwPgwApplication::RecvFromTunDevice(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('RecvFromTunDevice',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')])
## epc-sgw-pgw-application.h (module 'lte'): void ns3::EpcSgwPgwApplication::SendToS1uSocket(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address enbS1uAddress, uint32_t teid) [member function]
cls.add_method('SendToS1uSocket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'enbS1uAddress'), param('uint32_t', 'teid')])
## epc-sgw-pgw-application.h (module 'lte'): void ns3::EpcSgwPgwApplication::SendToTunDevice(ns3::Ptr<ns3::Packet> packet, uint32_t teid) [member function]
cls.add_method('SendToTunDevice',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint32_t', 'teid')])
return
def register_Ns3EpcTft_methods(root_module, cls):
## epc-tft.h (module 'lte'): ns3::EpcTft::EpcTft(ns3::EpcTft const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EpcTft const &', 'arg0')])
## epc-tft.h (module 'lte'): ns3::EpcTft::EpcTft() [constructor]
cls.add_constructor([])
## epc-tft.h (module 'lte'): uint8_t ns3::EpcTft::Add(ns3::EpcTft::PacketFilter f) [member function]
cls.add_method('Add',
'uint8_t',
[param('ns3::EpcTft::PacketFilter', 'f')])
## epc-tft.h (module 'lte'): static ns3::Ptr<ns3::EpcTft> ns3::EpcTft::Default() [member function]
cls.add_method('Default',
'ns3::Ptr< ns3::EpcTft >',
[],
is_static=True)
## epc-tft.h (module 'lte'): bool ns3::EpcTft::Matches(ns3::EpcTft::Direction direction, ns3::Ipv4Address remoteAddress, ns3::Ipv4Address localAddress, uint16_t remotePort, uint16_t localPort, uint8_t typeOfService) [member function]
cls.add_method('Matches',
'bool',
[param('ns3::EpcTft::Direction', 'direction'), param('ns3::Ipv4Address', 'remoteAddress'), param('ns3::Ipv4Address', 'localAddress'), param('uint16_t', 'remotePort'), param('uint16_t', 'localPort'), param('uint8_t', 'typeOfService')])
return
def register_Ns3EpcTftPacketFilter_methods(root_module, cls):
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::PacketFilter(ns3::EpcTft::PacketFilter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EpcTft::PacketFilter const &', 'arg0')])
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::PacketFilter() [constructor]
cls.add_constructor([])
## epc-tft.h (module 'lte'): bool ns3::EpcTft::PacketFilter::Matches(ns3::EpcTft::Direction d, ns3::Ipv4Address ra, ns3::Ipv4Address la, uint16_t rp, uint16_t lp, uint8_t tos) [member function]
cls.add_method('Matches',
'bool',
[param('ns3::EpcTft::Direction', 'd'), param('ns3::Ipv4Address', 'ra'), param('ns3::Ipv4Address', 'la'), param('uint16_t', 'rp'), param('uint16_t', 'lp'), param('uint8_t', 'tos')])
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::direction [variable]
cls.add_instance_attribute('direction', 'ns3::EpcTft::Direction', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::localAddress [variable]
cls.add_instance_attribute('localAddress', 'ns3::Ipv4Address', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::localMask [variable]
cls.add_instance_attribute('localMask', 'ns3::Ipv4Mask', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::localPortEnd [variable]
cls.add_instance_attribute('localPortEnd', 'uint16_t', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::localPortStart [variable]
cls.add_instance_attribute('localPortStart', 'uint16_t', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::precedence [variable]
cls.add_instance_attribute('precedence', 'uint8_t', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::remoteAddress [variable]
cls.add_instance_attribute('remoteAddress', 'ns3::Ipv4Address', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::remoteMask [variable]
cls.add_instance_attribute('remoteMask', 'ns3::Ipv4Mask', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::remotePortEnd [variable]
cls.add_instance_attribute('remotePortEnd', 'uint16_t', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::remotePortStart [variable]
cls.add_instance_attribute('remotePortStart', 'uint16_t', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::typeOfService [variable]
cls.add_instance_attribute('typeOfService', 'uint8_t', is_const=False)
## epc-tft.h (module 'lte'): ns3::EpcTft::PacketFilter::typeOfServiceMask [variable]
cls.add_instance_attribute('typeOfServiceMask', 'uint8_t', is_const=False)
return
def register_Ns3EpcTftClassifier_methods(root_module, cls):
## epc-tft-classifier.h (module 'lte'): ns3::EpcTftClassifier::EpcTftClassifier(ns3::EpcTftClassifier const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EpcTftClassifier const &', 'arg0')])
## epc-tft-classifier.h (module 'lte'): ns3::EpcTftClassifier::EpcTftClassifier() [constructor]
cls.add_constructor([])
## epc-tft-classifier.h (module 'lte'): void ns3::EpcTftClassifier::Add(ns3::Ptr<ns3::EpcTft> tft, uint32_t id) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::EpcTft >', 'tft'), param('uint32_t', 'id')])
## epc-tft-classifier.h (module 'lte'): uint32_t ns3::EpcTftClassifier::Classify(ns3::Ptr<ns3::Packet> p, ns3::EpcTft::Direction direction) [member function]
cls.add_method('Classify',
'uint32_t',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::EpcTft::Direction', 'direction')])
## epc-tft-classifier.h (module 'lte'): void ns3::EpcTftClassifier::Delete(uint32_t id) [member function]
cls.add_method('Delete',
'void',
[param('uint32_t', 'id')])
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_Ns3FfMacScheduler_methods(root_module, cls):
## ff-mac-scheduler.h (module 'lte'): ns3::FfMacScheduler::FfMacScheduler() [constructor]
cls.add_constructor([])
## ff-mac-scheduler.h (module 'lte'): ns3::FfMacScheduler::FfMacScheduler(ns3::FfMacScheduler const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FfMacScheduler const &', 'arg0')])
## ff-mac-scheduler.h (module 'lte'): void ns3::FfMacScheduler::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## ff-mac-scheduler.h (module 'lte'): ns3::FfMacCschedSapProvider * ns3::FfMacScheduler::GetFfMacCschedSapProvider() [member function]
cls.add_method('GetFfMacCschedSapProvider',
'ns3::FfMacCschedSapProvider *',
[],
is_pure_virtual=True, is_virtual=True)
## ff-mac-scheduler.h (module 'lte'): ns3::FfMacSchedSapProvider * ns3::FfMacScheduler::GetFfMacSchedSapProvider() [member function]
cls.add_method('GetFfMacSchedSapProvider',
'ns3::FfMacSchedSapProvider *',
[],
is_pure_virtual=True, is_virtual=True)
## ff-mac-scheduler.h (module 'lte'): static ns3::TypeId ns3::FfMacScheduler::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ff-mac-scheduler.h (module 'lte'): void ns3::FfMacScheduler::SetFfMacCschedSapUser(ns3::FfMacCschedSapUser * s) [member function]
cls.add_method('SetFfMacCschedSapUser',
'void',
[param('ns3::FfMacCschedSapUser *', 's')],
is_pure_virtual=True, is_virtual=True)
## ff-mac-scheduler.h (module 'lte'): void ns3::FfMacScheduler::SetFfMacSchedSapUser(ns3::FfMacSchedSapUser * s) [member function]
cls.add_method('SetFfMacSchedSapUser',
'void',
[param('ns3::FfMacSchedSapUser *', 's')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3GtpuHeader_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## epc-gtpu-header.h (module 'lte'): ns3::GtpuHeader::GtpuHeader(ns3::GtpuHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::GtpuHeader const &', 'arg0')])
## epc-gtpu-header.h (module 'lte'): ns3::GtpuHeader::GtpuHeader() [constructor]
cls.add_constructor([])
## epc-gtpu-header.h (module 'lte'): uint32_t ns3::GtpuHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## epc-gtpu-header.h (module 'lte'): bool ns3::GtpuHeader::GetExtensionHeaderFlag() const [member function]
cls.add_method('GetExtensionHeaderFlag',
'bool',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): ns3::TypeId ns3::GtpuHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## epc-gtpu-header.h (module 'lte'): uint16_t ns3::GtpuHeader::GetLength() const [member function]
cls.add_method('GetLength',
'uint16_t',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): uint8_t ns3::GtpuHeader::GetMessageType() const [member function]
cls.add_method('GetMessageType',
'uint8_t',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): uint8_t ns3::GtpuHeader::GetNPduNumber() const [member function]
cls.add_method('GetNPduNumber',
'uint8_t',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): bool ns3::GtpuHeader::GetNPduNumberFlag() const [member function]
cls.add_method('GetNPduNumberFlag',
'bool',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): uint8_t ns3::GtpuHeader::GetNextExtensionType() const [member function]
cls.add_method('GetNextExtensionType',
'uint8_t',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): bool ns3::GtpuHeader::GetProtocolType() const [member function]
cls.add_method('GetProtocolType',
'bool',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): uint16_t ns3::GtpuHeader::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): bool ns3::GtpuHeader::GetSequenceNumberFlag() const [member function]
cls.add_method('GetSequenceNumberFlag',
'bool',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): uint32_t ns3::GtpuHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## epc-gtpu-header.h (module 'lte'): uint32_t ns3::GtpuHeader::GetTeid() const [member function]
cls.add_method('GetTeid',
'uint32_t',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): static ns3::TypeId ns3::GtpuHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## epc-gtpu-header.h (module 'lte'): uint8_t ns3::GtpuHeader::GetVersion() const [member function]
cls.add_method('GetVersion',
'uint8_t',
[],
is_const=True)
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetExtensionHeaderFlag(bool m_extensionHeaderFlag) [member function]
cls.add_method('SetExtensionHeaderFlag',
'void',
[param('bool', 'm_extensionHeaderFlag')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetLength(uint16_t m_length) [member function]
cls.add_method('SetLength',
'void',
[param('uint16_t', 'm_length')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetMessageType(uint8_t m_messageType) [member function]
cls.add_method('SetMessageType',
'void',
[param('uint8_t', 'm_messageType')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetNPduNumber(uint8_t m_nPduNumber) [member function]
cls.add_method('SetNPduNumber',
'void',
[param('uint8_t', 'm_nPduNumber')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetNPduNumberFlag(bool m_nPduNumberFlag) [member function]
cls.add_method('SetNPduNumberFlag',
'void',
[param('bool', 'm_nPduNumberFlag')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetNextExtensionType(uint8_t m_nextExtensionType) [member function]
cls.add_method('SetNextExtensionType',
'void',
[param('uint8_t', 'm_nextExtensionType')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetProtocolType(bool m_protocolType) [member function]
cls.add_method('SetProtocolType',
'void',
[param('bool', 'm_protocolType')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetSequenceNumber(uint16_t m_sequenceNumber) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'm_sequenceNumber')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetSequenceNumberFlag(bool m_sequenceNumberFlag) [member function]
cls.add_method('SetSequenceNumberFlag',
'void',
[param('bool', 'm_sequenceNumberFlag')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetTeid(uint32_t m_teid) [member function]
cls.add_method('SetTeid',
'void',
[param('uint32_t', 'm_teid')])
## epc-gtpu-header.h (module 'lte'): void ns3::GtpuHeader::SetVersion(uint8_t m_version) [member function]
cls.add_method('SetVersion',
'void',
[param('uint8_t', 'm_version')])
return
def register_Ns3IdealControlMessage_methods(root_module, cls):
## ideal-control-messages.h (module 'lte'): ns3::IdealControlMessage::IdealControlMessage(ns3::IdealControlMessage const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IdealControlMessage const &', 'arg0')])
## ideal-control-messages.h (module 'lte'): ns3::IdealControlMessage::IdealControlMessage() [constructor]
cls.add_constructor([])
## ideal-control-messages.h (module 'lte'): ns3::Ptr<ns3::LteNetDevice> ns3::IdealControlMessage::GetDestinationDevice() [member function]
cls.add_method('GetDestinationDevice',
'ns3::Ptr< ns3::LteNetDevice >',
[])
## ideal-control-messages.h (module 'lte'): ns3::IdealControlMessage::MessageType ns3::IdealControlMessage::GetMessageType() [member function]
cls.add_method('GetMessageType',
'ns3::IdealControlMessage::MessageType',
[])
## ideal-control-messages.h (module 'lte'): ns3::Ptr<ns3::LteNetDevice> ns3::IdealControlMessage::GetSourceDevice() [member function]
cls.add_method('GetSourceDevice',
'ns3::Ptr< ns3::LteNetDevice >',
[])
## ideal-control-messages.h (module 'lte'): void ns3::IdealControlMessage::SetDestinationDevice(ns3::Ptr<ns3::LteNetDevice> dst) [member function]
cls.add_method('SetDestinationDevice',
'void',
[param('ns3::Ptr< ns3::LteNetDevice >', 'dst')])
## ideal-control-messages.h (module 'lte'): void ns3::IdealControlMessage::SetMessageType(ns3::IdealControlMessage::MessageType type) [member function]
cls.add_method('SetMessageType',
'void',
[param('ns3::IdealControlMessage::MessageType', 'type')])
## ideal-control-messages.h (module 'lte'): void ns3::IdealControlMessage::SetSourceDevice(ns3::Ptr<ns3::LteNetDevice> src) [member function]
cls.add_method('SetSourceDevice',
'void',
[param('ns3::Ptr< ns3::LteNetDevice >', 'src')])
return
def register_Ns3IntegerValue_methods(root_module, cls):
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor]
cls.add_constructor([])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor]
cls.add_constructor([param('int64_t const &', 'value')])
## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## integer.h (module 'core'): bool ns3::IntegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function]
cls.add_method('Get',
'int64_t',
[],
is_const=True)
## integer.h (module 'core'): std::string ns3::IntegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('int64_t const &', 'value')])
return
def register_Ns3IpL4Protocol_methods(root_module, cls):
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol() [constructor]
cls.add_constructor([])
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol(ns3::IpL4Protocol const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IpL4Protocol const &', 'arg0')])
## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget() const [member function]
cls.add_method('GetDownTarget',
'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget6() const [member function]
cls.add_method('GetDownTarget6',
'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): int ns3::IpL4Protocol::GetProtocolNumber() const [member function]
cls.add_method('GetProtocolNumber',
'int',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::IpL4Protocol::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::Ipv4Interface> incomingInterface) [member function]
cls.add_method('Receive',
'ns3::IpL4Protocol::RxStatus',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::Ipv4Interface >', 'incomingInterface')],
is_pure_virtual=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address & src, ns3::Ipv6Address & dst, ns3::Ptr<ns3::Ipv6Interface> incomingInterface) [member function]
cls.add_method('Receive',
'ns3::IpL4Protocol::RxStatus',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address &', 'src'), param('ns3::Ipv6Address &', 'dst'), param('ns3::Ptr< ns3::Ipv6Interface >', 'incomingInterface')],
is_pure_virtual=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv4Address payloadSource, ns3::Ipv4Address payloadDestination, uint8_t const * payload) [member function]
cls.add_method('ReceiveIcmp',
'void',
[param('ns3::Ipv4Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv4Address', 'payloadSource'), param('ns3::Ipv4Address', 'payloadDestination'), param('uint8_t const *', 'payload')],
is_virtual=True)
## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv6Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv6Address payloadSource, ns3::Ipv6Address payloadDestination, uint8_t const * payload) [member function]
cls.add_method('ReceiveIcmp',
'void',
[param('ns3::Ipv6Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv6Address', 'payloadSource'), param('ns3::Ipv6Address', 'payloadDestination'), param('uint8_t const *', 'payload')],
is_virtual=True)
## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetDownTarget',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget6(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function]
cls.add_method('SetDownTarget6',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3Ipv4_methods(root_module, cls):
## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')])
## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor]
cls.add_constructor([])
## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function]
cls.add_method('AddAddress',
'bool',
[param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddInterface',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv4InterfaceAddress',
[param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function]
cls.add_method('GetInterfaceForAddress',
'int32_t',
[param('ns3::Ipv4Address', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function]
cls.add_method('GetInterfaceForDevice',
'int32_t',
[param('ns3::Ptr< ns3::NetDevice const >', 'device')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function]
cls.add_method('GetInterfaceForPrefix',
'int32_t',
[param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function]
cls.add_method('GetMetric',
'uint16_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function]
cls.add_method('GetMtu',
'uint16_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function]
cls.add_method('GetNInterfaces',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function]
cls.add_method('GetNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function]
cls.add_method('GetRoutingProtocol',
'ns3::Ptr< ns3::Ipv4RoutingProtocol >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function]
cls.add_method('Insert',
'void',
[param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function]
cls.add_method('IsDestinationAddress',
'bool',
[param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function]
cls.add_method('IsForwarding',
'bool',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function]
cls.add_method('IsUp',
'bool',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function]
cls.add_method('RemoveAddress',
'bool',
[param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function]
cls.add_method('SelectSourceAddress',
'ns3::Ipv4Address',
[param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function]
cls.add_method('SetDown',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function]
cls.add_method('SetForwarding',
'void',
[param('uint32_t', 'interface'), param('bool', 'val')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint32_t', 'interface'), param('uint16_t', 'metric')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function]
cls.add_method('SetRoutingProtocol',
'void',
[param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function]
cls.add_method('SetUp',
'void',
[param('uint32_t', 'interface')],
is_pure_virtual=True, is_virtual=True)
## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable]
cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function]
cls.add_method('GetIpForward',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function]
cls.add_method('GetWeakEsModel',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function]
cls.add_method('SetIpForward',
'void',
[param('bool', 'forward')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function]
cls.add_method('SetWeakEsModel',
'void',
[param('bool', 'model')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3Ipv4AddressChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv4AddressValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Address const &', 'value')])
return
def register_Ns3Ipv4MaskChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')])
return
def register_Ns3Ipv4MaskValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Mask const &', 'value')])
return
def register_Ns3Ipv4MulticastRoute_methods(root_module, cls):
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function]
cls.add_method('GetGroup',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function]
cls.add_method('GetOrigin',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetOutputTtl(uint32_t oif) [member function]
cls.add_method('GetOutputTtl',
'uint32_t',
[param('uint32_t', 'oif')],
deprecated=True)
## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function]
cls.add_method('GetOutputTtlMap',
'std::map< unsigned int, unsigned int >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function]
cls.add_method('GetParent',
'uint32_t',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function]
cls.add_method('SetGroup',
'void',
[param('ns3::Ipv4Address const', 'group')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function]
cls.add_method('SetOrigin',
'void',
[param('ns3::Ipv4Address const', 'origin')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function]
cls.add_method('SetOutputTtl',
'void',
[param('uint32_t', 'oif'), param('uint32_t', 'ttl')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function]
cls.add_method('SetParent',
'void',
[param('uint32_t', 'iif')])
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable]
cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable]
cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True)
return
def register_Ns3Ipv4Route_methods(root_module, cls):
cls.add_output_stream_operator()
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')])
## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor]
cls.add_constructor([])
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function]
cls.add_method('GetGateway',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function]
cls.add_method('GetOutputDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True)
## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Ipv4Address', 'dest')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function]
cls.add_method('SetGateway',
'void',
[param('ns3::Ipv4Address', 'gw')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function]
cls.add_method('SetOutputDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')])
## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Ipv4Address', 'src')])
return
def register_Ns3Ipv6AddressChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv6AddressValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Address const &', 'value')])
return
def register_Ns3Ipv6Interface_methods(root_module, cls):
## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface(ns3::Ipv6Interface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Interface const &', 'arg0')])
## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface() [constructor]
cls.add_constructor([])
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::AddAddress(ns3::Ipv6InterfaceAddress iface) [member function]
cls.add_method('AddAddress',
'bool',
[param('ns3::Ipv6InterfaceAddress', 'iface')])
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddress(uint32_t index) const [member function]
cls.add_method('GetAddress',
'ns3::Ipv6InterfaceAddress',
[param('uint32_t', 'index')],
is_const=True)
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddressMatchingDestination(ns3::Ipv6Address dst) [member function]
cls.add_method('GetAddressMatchingDestination',
'ns3::Ipv6InterfaceAddress',
[param('ns3::Ipv6Address', 'dst')])
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetBaseReachableTime() const [member function]
cls.add_method('GetBaseReachableTime',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint8_t ns3::Ipv6Interface::GetCurHopLimit() const [member function]
cls.add_method('GetCurHopLimit',
'uint8_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6Interface::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True, is_virtual=True)
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetLinkLocalAddress() const [member function]
cls.add_method('GetLinkLocalAddress',
'ns3::Ipv6InterfaceAddress',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetMetric() const [member function]
cls.add_method('GetMetric',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint32_t ns3::Ipv6Interface::GetNAddresses() const [member function]
cls.add_method('GetNAddresses',
'uint32_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetReachableTime() const [member function]
cls.add_method('GetReachableTime',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetRetransTimer() const [member function]
cls.add_method('GetRetransTimer',
'uint16_t',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv6Interface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsDown() const [member function]
cls.add_method('IsDown',
'bool',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsForwarding() const [member function]
cls.add_method('IsForwarding',
'bool',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsUp() const [member function]
cls.add_method('IsUp',
'bool',
[],
is_const=True)
## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(uint32_t index) [member function]
cls.add_method('RemoveAddress',
'ns3::Ipv6InterfaceAddress',
[param('uint32_t', 'index')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address dest) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address', 'dest')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetBaseReachableTime(uint16_t baseReachableTime) [member function]
cls.add_method('SetBaseReachableTime',
'void',
[param('uint16_t', 'baseReachableTime')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetCurHopLimit(uint8_t curHopLimit) [member function]
cls.add_method('SetCurHopLimit',
'void',
[param('uint8_t', 'curHopLimit')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDown() [member function]
cls.add_method('SetDown',
'void',
[])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetForwarding(bool forward) [member function]
cls.add_method('SetForwarding',
'void',
[param('bool', 'forward')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetMetric(uint16_t metric) [member function]
cls.add_method('SetMetric',
'void',
[param('uint16_t', 'metric')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNsDadUid(ns3::Ipv6Address address, uint32_t uid) [member function]
cls.add_method('SetNsDadUid',
'void',
[param('ns3::Ipv6Address', 'address'), param('uint32_t', 'uid')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetReachableTime(uint16_t reachableTime) [member function]
cls.add_method('SetReachableTime',
'void',
[param('uint16_t', 'reachableTime')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetRetransTimer(uint16_t retransTimer) [member function]
cls.add_method('SetRetransTimer',
'void',
[param('uint16_t', 'retransTimer')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetState(ns3::Ipv6Address address, ns3::Ipv6InterfaceAddress::State_e state) [member function]
cls.add_method('SetState',
'void',
[param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6InterfaceAddress::State_e', 'state')])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetUp() [member function]
cls.add_method('SetUp',
'void',
[])
## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3Ipv6PrefixChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')])
return
def register_Ns3Ipv6PrefixValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Prefix',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Prefix const &', 'value')])
return
def register_Ns3LteAmc_methods(root_module, cls):
## lte-amc.h (module 'lte'): ns3::LteAmc::LteAmc(ns3::LteAmc const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteAmc const &', 'arg0')])
## lte-amc.h (module 'lte'): ns3::LteAmc::LteAmc() [constructor]
cls.add_constructor([])
## lte-amc.h (module 'lte'): std::vector<int, std::allocator<int> > ns3::LteAmc::CreateCqiFeedbacks(ns3::SpectrumValue const & sinr, uint8_t rbgSize=0) [member function]
cls.add_method('CreateCqiFeedbacks',
'std::vector< int >',
[param('ns3::SpectrumValue const &', 'sinr'), param('uint8_t', 'rbgSize', default_value='0')])
## lte-amc.h (module 'lte'): int ns3::LteAmc::GetCqiFromSpectralEfficiency(double s) [member function]
cls.add_method('GetCqiFromSpectralEfficiency',
'int',
[param('double', 's')])
## lte-amc.h (module 'lte'): int ns3::LteAmc::GetMcsFromCqi(int cqi) [member function]
cls.add_method('GetMcsFromCqi',
'int',
[param('int', 'cqi')])
## lte-amc.h (module 'lte'): double ns3::LteAmc::GetSpectralEfficiencyFromCqi(int cqi) [member function]
cls.add_method('GetSpectralEfficiencyFromCqi',
'double',
[param('int', 'cqi')])
## lte-amc.h (module 'lte'): int ns3::LteAmc::GetTbSizeFromMcs(int mcs, int nprb) [member function]
cls.add_method('GetTbSizeFromMcs',
'int',
[param('int', 'mcs'), param('int', 'nprb')])
## lte-amc.h (module 'lte'): static ns3::TypeId ns3::LteAmc::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3LteEnbMac_methods(root_module, cls):
## lte-enb-mac.h (module 'lte'): ns3::LteEnbMac::LteEnbMac(ns3::LteEnbMac const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteEnbMac const &', 'arg0')])
## lte-enb-mac.h (module 'lte'): ns3::LteEnbMac::LteEnbMac() [constructor]
cls.add_constructor([])
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::DoReceiveIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('DoReceiveIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')])
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::DoReceivePhyPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoReceivePhyPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::DoUlCqiReport(UlCqi_s ulcqi) [member function]
cls.add_method('DoUlCqiReport',
'void',
[param('UlCqi_s', 'ulcqi')])
## lte-enb-mac.h (module 'lte'): ns3::FfMacCschedSapUser * ns3::LteEnbMac::GetFfMacCschedSapUser() [member function]
cls.add_method('GetFfMacCschedSapUser',
'ns3::FfMacCschedSapUser *',
[])
## lte-enb-mac.h (module 'lte'): ns3::FfMacSchedSapUser * ns3::LteEnbMac::GetFfMacSchedSapUser() [member function]
cls.add_method('GetFfMacSchedSapUser',
'ns3::FfMacSchedSapUser *',
[])
## lte-enb-mac.h (module 'lte'): ns3::LteEnbCmacSapProvider * ns3::LteEnbMac::GetLteEnbCmacSapProvider() [member function]
cls.add_method('GetLteEnbCmacSapProvider',
'ns3::LteEnbCmacSapProvider *',
[])
## lte-enb-mac.h (module 'lte'): ns3::LteEnbPhySapUser * ns3::LteEnbMac::GetLteEnbPhySapUser() [member function]
cls.add_method('GetLteEnbPhySapUser',
'ns3::LteEnbPhySapUser *',
[])
## lte-enb-mac.h (module 'lte'): ns3::LteMacSapProvider * ns3::LteEnbMac::GetLteMacSapProvider() [member function]
cls.add_method('GetLteMacSapProvider',
'ns3::LteMacSapProvider *',
[])
## lte-enb-mac.h (module 'lte'): static ns3::TypeId ns3::LteEnbMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::ReceiveBsrMessage(MacCeListElement_s bsr) [member function]
cls.add_method('ReceiveBsrMessage',
'void',
[param('MacCeListElement_s', 'bsr')])
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::ReceiveDlCqiIdealControlMessage(ns3::Ptr<ns3::DlCqiIdealControlMessage> msg) [member function]
cls.add_method('ReceiveDlCqiIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::DlCqiIdealControlMessage >', 'msg')])
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::SetFfMacCschedSapProvider(ns3::FfMacCschedSapProvider * s) [member function]
cls.add_method('SetFfMacCschedSapProvider',
'void',
[param('ns3::FfMacCschedSapProvider *', 's')])
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::SetFfMacSchedSapProvider(ns3::FfMacSchedSapProvider * s) [member function]
cls.add_method('SetFfMacSchedSapProvider',
'void',
[param('ns3::FfMacSchedSapProvider *', 's')])
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::SetLteEnbCmacSapUser(ns3::LteEnbCmacSapUser * s) [member function]
cls.add_method('SetLteEnbCmacSapUser',
'void',
[param('ns3::LteEnbCmacSapUser *', 's')])
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::SetLteEnbPhySapProvider(ns3::LteEnbPhySapProvider * s) [member function]
cls.add_method('SetLteEnbPhySapProvider',
'void',
[param('ns3::LteEnbPhySapProvider *', 's')])
## lte-enb-mac.h (module 'lte'): void ns3::LteEnbMac::SetLteMacSapUser(ns3::LteMacSapUser * s) [member function]
cls.add_method('SetLteMacSapUser',
'void',
[param('ns3::LteMacSapUser *', 's')])
return
def register_Ns3LteEnbRrc_methods(root_module, cls):
## lte-enb-rrc.h (module 'lte'): ns3::LteEnbRrc::LteEnbRrc(ns3::LteEnbRrc const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteEnbRrc const &', 'arg0')])
## lte-enb-rrc.h (module 'lte'): ns3::LteEnbRrc::LteEnbRrc() [constructor]
cls.add_constructor([])
## lte-enb-rrc.h (module 'lte'): uint16_t ns3::LteEnbRrc::AddUe(uint64_t imsi) [member function]
cls.add_method('AddUe',
'uint16_t',
[param('uint64_t', 'imsi')])
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::ConfigureCell(uint8_t ulBandwidth, uint8_t dlBandwidth) [member function]
cls.add_method('ConfigureCell',
'void',
[param('uint8_t', 'ulBandwidth'), param('uint8_t', 'dlBandwidth')])
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-enb-rrc.h (module 'lte'): uint16_t ns3::LteEnbRrc::GetLastAllocatedRnti() const [member function]
cls.add_method('GetLastAllocatedRnti',
'uint16_t',
[],
is_const=True)
## lte-enb-rrc.h (module 'lte'): ns3::LteEnbCmacSapUser * ns3::LteEnbRrc::GetLteEnbCmacSapUser() [member function]
cls.add_method('GetLteEnbCmacSapUser',
'ns3::LteEnbCmacSapUser *',
[])
## lte-enb-rrc.h (module 'lte'): static ns3::TypeId ns3::LteEnbRrc::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-enb-rrc.h (module 'lte'): std::map<unsigned short, ns3::Ptr<ns3::UeInfo>, std::less<unsigned short>, std::allocator<std::pair<unsigned short const, ns3::Ptr<ns3::UeInfo> > > > ns3::LteEnbRrc::GetUeMap() const [member function]
cls.add_method('GetUeMap',
'std::map< unsigned short, ns3::Ptr< ns3::UeInfo > >',
[],
is_const=True)
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::ReleaseRadioBearer(uint16_t rnti, uint8_t lcId) [member function]
cls.add_method('ReleaseRadioBearer',
'void',
[param('uint16_t', 'rnti'), param('uint8_t', 'lcId')])
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::RemoveUe(uint16_t rnti) [member function]
cls.add_method('RemoveUe',
'void',
[param('uint16_t', 'rnti')])
## lte-enb-rrc.h (module 'lte'): bool ns3::LteEnbRrc::Send(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::SetFfMacSchedSapProvider(ns3::FfMacSchedSapProvider * s) [member function]
cls.add_method('SetFfMacSchedSapProvider',
'void',
[param('ns3::FfMacSchedSapProvider *', 's')])
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')])
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::SetLastAllocatedRnti(uint16_t lastAllocatedRnti) [member function]
cls.add_method('SetLastAllocatedRnti',
'void',
[param('uint16_t', 'lastAllocatedRnti')])
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::SetLteEnbCmacSapProvider(ns3::LteEnbCmacSapProvider * s) [member function]
cls.add_method('SetLteEnbCmacSapProvider',
'void',
[param('ns3::LteEnbCmacSapProvider *', 's')])
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::SetLteMacSapProvider(ns3::LteMacSapProvider * s) [member function]
cls.add_method('SetLteMacSapProvider',
'void',
[param('ns3::LteMacSapProvider *', 's')])
## lte-enb-rrc.h (module 'lte'): void ns3::LteEnbRrc::SetUeMap(std::map<unsigned short, ns3::Ptr<ns3::UeInfo>, std::less<unsigned short>, std::allocator<std::pair<unsigned short const, ns3::Ptr<ns3::UeInfo> > > > ueMap) [member function]
cls.add_method('SetUeMap',
'void',
[param('std::map< unsigned short, ns3::Ptr< ns3::UeInfo > >', 'ueMap')])
## lte-enb-rrc.h (module 'lte'): uint8_t ns3::LteEnbRrc::SetupRadioBearer(uint16_t rnti, ns3::EpsBearer bearer, ns3::TypeId rlcTypeId) [member function]
cls.add_method('SetupRadioBearer',
'uint8_t',
[param('uint16_t', 'rnti'), param('ns3::EpsBearer', 'bearer'), param('ns3::TypeId', 'rlcTypeId')])
return
def register_Ns3LteHelper_methods(root_module, cls):
## lte-helper.h (module 'lte'): ns3::LteHelper::LteHelper(ns3::LteHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteHelper const &', 'arg0')])
## lte-helper.h (module 'lte'): ns3::LteHelper::LteHelper() [constructor]
cls.add_constructor([])
## lte-helper.h (module 'lte'): void ns3::LteHelper::ActivateEpsBearer(ns3::NetDeviceContainer ueDevices, ns3::EpsBearer bearer, ns3::Ptr<ns3::EpcTft> tft) [member function]
cls.add_method('ActivateEpsBearer',
'void',
[param('ns3::NetDeviceContainer', 'ueDevices'), param('ns3::EpsBearer', 'bearer'), param('ns3::Ptr< ns3::EpcTft >', 'tft')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::ActivateEpsBearer(ns3::Ptr<ns3::NetDevice> ueDevice, ns3::EpsBearer bearer, ns3::Ptr<ns3::EpcTft> tft) [member function]
cls.add_method('ActivateEpsBearer',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'ueDevice'), param('ns3::EpsBearer', 'bearer'), param('ns3::Ptr< ns3::EpcTft >', 'tft')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::Attach(ns3::NetDeviceContainer ueDevices, ns3::Ptr<ns3::NetDevice> enbDevice) [member function]
cls.add_method('Attach',
'void',
[param('ns3::NetDeviceContainer', 'ueDevices'), param('ns3::Ptr< ns3::NetDevice >', 'enbDevice')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::Attach(ns3::Ptr<ns3::NetDevice> ueDevice, ns3::Ptr<ns3::NetDevice> enbDevice) [member function]
cls.add_method('Attach',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'ueDevice'), param('ns3::Ptr< ns3::NetDevice >', 'enbDevice')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::AttachToClosestEnb(ns3::NetDeviceContainer ueDevices, ns3::NetDeviceContainer enbDevices) [member function]
cls.add_method('AttachToClosestEnb',
'void',
[param('ns3::NetDeviceContainer', 'ueDevices'), param('ns3::NetDeviceContainer', 'enbDevices')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::AttachToClosestEnb(ns3::Ptr<ns3::NetDevice> ueDevice, ns3::NetDeviceContainer enbDevices) [member function]
cls.add_method('AttachToClosestEnb',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'ueDevice'), param('ns3::NetDeviceContainer', 'enbDevices')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableDlMacTraces() [member function]
cls.add_method('EnableDlMacTraces',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableDlPdcpTraces() [member function]
cls.add_method('EnableDlPdcpTraces',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableDlRlcTraces() [member function]
cls.add_method('EnableDlRlcTraces',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableLogComponents() [member function]
cls.add_method('EnableLogComponents',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableMacTraces() [member function]
cls.add_method('EnableMacTraces',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnablePdcpTraces() [member function]
cls.add_method('EnablePdcpTraces',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableRlcTraces() [member function]
cls.add_method('EnableRlcTraces',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableTraces() [member function]
cls.add_method('EnableTraces',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableUlMacTraces() [member function]
cls.add_method('EnableUlMacTraces',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableUlPdcpTraces() [member function]
cls.add_method('EnableUlPdcpTraces',
'void',
[])
## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableUlRlcTraces() [member function]
cls.add_method('EnableUlRlcTraces',
'void',
[])
## lte-helper.h (module 'lte'): ns3::Ptr<ns3::RadioBearerStatsCalculator> ns3::LteHelper::GetPdcpStats() [member function]
cls.add_method('GetPdcpStats',
'ns3::Ptr< ns3::RadioBearerStatsCalculator >',
[])
## lte-helper.h (module 'lte'): ns3::Ptr<ns3::RadioBearerStatsCalculator> ns3::LteHelper::GetRlcStats() [member function]
cls.add_method('GetRlcStats',
'ns3::Ptr< ns3::RadioBearerStatsCalculator >',
[])
## lte-helper.h (module 'lte'): ns3::TypeId ns3::LteHelper::GetRlcType(ns3::EpsBearer bearer) [member function]
cls.add_method('GetRlcType',
'ns3::TypeId',
[param('ns3::EpsBearer', 'bearer')])
## lte-helper.h (module 'lte'): static ns3::TypeId ns3::LteHelper::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-helper.h (module 'lte'): ns3::NetDeviceContainer ns3::LteHelper::InstallEnbDevice(ns3::NodeContainer c) [member function]
cls.add_method('InstallEnbDevice',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer', 'c')])
## lte-helper.h (module 'lte'): ns3::NetDeviceContainer ns3::LteHelper::InstallUeDevice(ns3::NodeContainer c) [member function]
cls.add_method('InstallUeDevice',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer', 'c')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetEnbAntennaModelAttribute(std::string n, ns3::AttributeValue const & v) [member function]
cls.add_method('SetEnbAntennaModelAttribute',
'void',
[param('std::string', 'n'), param('ns3::AttributeValue const &', 'v')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetEnbAntennaModelType(std::string type) [member function]
cls.add_method('SetEnbAntennaModelType',
'void',
[param('std::string', 'type')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetEnbDeviceAttribute(std::string n, ns3::AttributeValue const & v) [member function]
cls.add_method('SetEnbDeviceAttribute',
'void',
[param('std::string', 'n'), param('ns3::AttributeValue const &', 'v')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetEpcHelper(ns3::Ptr<ns3::EpcHelper> h) [member function]
cls.add_method('SetEpcHelper',
'void',
[param('ns3::Ptr< ns3::EpcHelper >', 'h')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetFadingModel(std::string model) [member function]
cls.add_method('SetFadingModel',
'void',
[param('std::string', 'model')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetFadingModelAttribute(std::string n, ns3::AttributeValue const & v) [member function]
cls.add_method('SetFadingModelAttribute',
'void',
[param('std::string', 'n'), param('ns3::AttributeValue const &', 'v')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetPathlossModelAttribute(std::string n, ns3::AttributeValue const & v) [member function]
cls.add_method('SetPathlossModelAttribute',
'void',
[param('std::string', 'n'), param('ns3::AttributeValue const &', 'v')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetPathlossModelType(std::string type) [member function]
cls.add_method('SetPathlossModelType',
'void',
[param('std::string', 'type')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetSchedulerAttribute(std::string n, ns3::AttributeValue const & v) [member function]
cls.add_method('SetSchedulerAttribute',
'void',
[param('std::string', 'n'), param('ns3::AttributeValue const &', 'v')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetSchedulerType(std::string type) [member function]
cls.add_method('SetSchedulerType',
'void',
[param('std::string', 'type')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetSpectrumChannelAttribute(std::string n, ns3::AttributeValue const & v) [member function]
cls.add_method('SetSpectrumChannelAttribute',
'void',
[param('std::string', 'n'), param('ns3::AttributeValue const &', 'v')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetSpectrumChannelType(std::string type) [member function]
cls.add_method('SetSpectrumChannelType',
'void',
[param('std::string', 'type')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetUeAntennaModelAttribute(std::string n, ns3::AttributeValue const & v) [member function]
cls.add_method('SetUeAntennaModelAttribute',
'void',
[param('std::string', 'n'), param('ns3::AttributeValue const &', 'v')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::SetUeAntennaModelType(std::string type) [member function]
cls.add_method('SetUeAntennaModelType',
'void',
[param('std::string', 'type')])
## lte-helper.h (module 'lte'): void ns3::LteHelper::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3LteHexGridEnbTopologyHelper_methods(root_module, cls):
## lte-hex-grid-enb-topology-helper.h (module 'lte'): ns3::LteHexGridEnbTopologyHelper::LteHexGridEnbTopologyHelper(ns3::LteHexGridEnbTopologyHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteHexGridEnbTopologyHelper const &', 'arg0')])
## lte-hex-grid-enb-topology-helper.h (module 'lte'): ns3::LteHexGridEnbTopologyHelper::LteHexGridEnbTopologyHelper() [constructor]
cls.add_constructor([])
## lte-hex-grid-enb-topology-helper.h (module 'lte'): void ns3::LteHexGridEnbTopologyHelper::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-hex-grid-enb-topology-helper.h (module 'lte'): static ns3::TypeId ns3::LteHexGridEnbTopologyHelper::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-hex-grid-enb-topology-helper.h (module 'lte'): void ns3::LteHexGridEnbTopologyHelper::SetLteHelper(ns3::Ptr<ns3::LteHelper> h) [member function]
cls.add_method('SetLteHelper',
'void',
[param('ns3::Ptr< ns3::LteHelper >', 'h')])
## lte-hex-grid-enb-topology-helper.h (module 'lte'): ns3::NetDeviceContainer ns3::LteHexGridEnbTopologyHelper::SetPositionAndInstallEnbDevice(ns3::NodeContainer c) [member function]
cls.add_method('SetPositionAndInstallEnbDevice',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer', 'c')])
return
def register_Ns3LteInterference_methods(root_module, cls):
## lte-interference.h (module 'lte'): ns3::LteInterference::LteInterference(ns3::LteInterference const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteInterference const &', 'arg0')])
## lte-interference.h (module 'lte'): ns3::LteInterference::LteInterference() [constructor]
cls.add_constructor([])
## lte-interference.h (module 'lte'): void ns3::LteInterference::AddSignal(ns3::Ptr<ns3::SpectrumValue const> spd, ns3::Time const duration) [member function]
cls.add_method('AddSignal',
'void',
[param('ns3::Ptr< ns3::SpectrumValue const >', 'spd'), param('ns3::Time const', 'duration')])
## lte-interference.h (module 'lte'): void ns3::LteInterference::AddSinrChunkProcessor(ns3::Ptr<ns3::LteSinrChunkProcessor> p) [member function]
cls.add_method('AddSinrChunkProcessor',
'void',
[param('ns3::Ptr< ns3::LteSinrChunkProcessor >', 'p')])
## lte-interference.h (module 'lte'): void ns3::LteInterference::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-interference.h (module 'lte'): void ns3::LteInterference::EndRx() [member function]
cls.add_method('EndRx',
'void',
[])
## lte-interference.h (module 'lte'): static ns3::TypeId ns3::LteInterference::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-interference.h (module 'lte'): void ns3::LteInterference::SetNoisePowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> noisePsd) [member function]
cls.add_method('SetNoisePowerSpectralDensity',
'void',
[param('ns3::Ptr< ns3::SpectrumValue const >', 'noisePsd')])
## lte-interference.h (module 'lte'): void ns3::LteInterference::StartRx(ns3::Ptr<ns3::SpectrumValue const> rxPsd) [member function]
cls.add_method('StartRx',
'void',
[param('ns3::Ptr< ns3::SpectrumValue const >', 'rxPsd')])
return
def register_Ns3LtePdcp_methods(root_module, cls):
## lte-pdcp.h (module 'lte'): ns3::LtePdcp::LtePdcp(ns3::LtePdcp const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LtePdcp const &', 'arg0')])
## lte-pdcp.h (module 'lte'): ns3::LtePdcp::LtePdcp() [constructor]
cls.add_constructor([])
## lte-pdcp.h (module 'lte'): ns3::LtePdcpSapProvider * ns3::LtePdcp::GetLtePdcpSapProvider() [member function]
cls.add_method('GetLtePdcpSapProvider',
'ns3::LtePdcpSapProvider *',
[])
## lte-pdcp.h (module 'lte'): ns3::LteRlcSapUser * ns3::LtePdcp::GetLteRlcSapUser() [member function]
cls.add_method('GetLteRlcSapUser',
'ns3::LteRlcSapUser *',
[])
## lte-pdcp.h (module 'lte'): static ns3::TypeId ns3::LtePdcp::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-pdcp.h (module 'lte'): void ns3::LtePdcp::SetLcId(uint8_t lcId) [member function]
cls.add_method('SetLcId',
'void',
[param('uint8_t', 'lcId')])
## lte-pdcp.h (module 'lte'): void ns3::LtePdcp::SetLtePdcpSapUser(ns3::LtePdcpSapUser * s) [member function]
cls.add_method('SetLtePdcpSapUser',
'void',
[param('ns3::LtePdcpSapUser *', 's')])
## lte-pdcp.h (module 'lte'): void ns3::LtePdcp::SetLteRlcSapProvider(ns3::LteRlcSapProvider * s) [member function]
cls.add_method('SetLteRlcSapProvider',
'void',
[param('ns3::LteRlcSapProvider *', 's')])
## lte-pdcp.h (module 'lte'): void ns3::LtePdcp::SetRnti(uint16_t rnti) [member function]
cls.add_method('SetRnti',
'void',
[param('uint16_t', 'rnti')])
## lte-pdcp.h (module 'lte'): void ns3::LtePdcp::Start() [member function]
cls.add_method('Start',
'void',
[])
## lte-pdcp.h (module 'lte'): void ns3::LtePdcp::DoReceivePdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoReceivePdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='protected', is_virtual=True)
## lte-pdcp.h (module 'lte'): void ns3::LtePdcp::DoTransmitRrcPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoTransmitRrcPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='protected', is_virtual=True)
return
def register_Ns3LtePhy_methods(root_module, cls):
## lte-phy.h (module 'lte'): ns3::LtePhy::LtePhy(ns3::LtePhy const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LtePhy const &', 'arg0')])
## lte-phy.h (module 'lte'): ns3::LtePhy::LtePhy() [constructor]
cls.add_constructor([])
## lte-phy.h (module 'lte'): ns3::LtePhy::LtePhy(ns3::Ptr<ns3::LteSpectrumPhy> dlPhy, ns3::Ptr<ns3::LteSpectrumPhy> ulPhy) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::LteSpectrumPhy >', 'dlPhy'), param('ns3::Ptr< ns3::LteSpectrumPhy >', 'ulPhy')])
## lte-phy.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::LtePhy::CreateTxPowerSpectralDensity() [member function]
cls.add_method('CreateTxPowerSpectralDensity',
'ns3::Ptr< ns3::SpectrumValue >',
[],
is_pure_virtual=True, is_virtual=True)
## lte-phy.h (module 'lte'): void ns3::LtePhy::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-phy.h (module 'lte'): void ns3::LtePhy::DoSendMacPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoSendMacPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, is_virtual=True)
## lte-phy.h (module 'lte'): void ns3::LtePhy::DoSetBandwidth(uint8_t ulBandwidth, uint8_t dlBandwidth) [member function]
cls.add_method('DoSetBandwidth',
'void',
[param('uint8_t', 'ulBandwidth'), param('uint8_t', 'dlBandwidth')])
## lte-phy.h (module 'lte'): void ns3::LtePhy::DoSetCellId(uint16_t cellId) [member function]
cls.add_method('DoSetCellId',
'void',
[param('uint16_t', 'cellId')])
## lte-phy.h (module 'lte'): void ns3::LtePhy::DoSetDownlinkSubChannels() [member function]
cls.add_method('DoSetDownlinkSubChannels',
'void',
[],
is_virtual=True)
## lte-phy.h (module 'lte'): void ns3::LtePhy::DoSetEarfcn(uint16_t dlEarfcn, uint16_t ulEarfcn) [member function]
cls.add_method('DoSetEarfcn',
'void',
[param('uint16_t', 'dlEarfcn'), param('uint16_t', 'ulEarfcn')],
is_virtual=True)
## lte-phy.h (module 'lte'): void ns3::LtePhy::DoSetUplinkSubChannels() [member function]
cls.add_method('DoSetUplinkSubChannels',
'void',
[],
is_virtual=True)
## lte-phy.h (module 'lte'): void ns3::LtePhy::GenerateCqiReport(ns3::SpectrumValue const & sinr) [member function]
cls.add_method('GenerateCqiReport',
'void',
[param('ns3::SpectrumValue const &', 'sinr')],
is_pure_virtual=True, is_virtual=True)
## lte-phy.h (module 'lte'): std::list<ns3::Ptr<ns3::IdealControlMessage>,std::allocator<ns3::Ptr<ns3::IdealControlMessage> > > ns3::LtePhy::GetControlMessages() [member function]
cls.add_method('GetControlMessages',
'std::list< ns3::Ptr< ns3::IdealControlMessage > >',
[])
## lte-phy.h (module 'lte'): ns3::Ptr<ns3::LteNetDevice> ns3::LtePhy::GetDevice() [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::LteNetDevice >',
[])
## lte-phy.h (module 'lte'): ns3::Ptr<ns3::LteSpectrumPhy> ns3::LtePhy::GetDownlinkSpectrumPhy() [member function]
cls.add_method('GetDownlinkSpectrumPhy',
'ns3::Ptr< ns3::LteSpectrumPhy >',
[])
## lte-phy.h (module 'lte'): std::vector<int, std::allocator<int> > ns3::LtePhy::GetDownlinkSubChannels() [member function]
cls.add_method('GetDownlinkSubChannels',
'std::vector< int >',
[])
## lte-phy.h (module 'lte'): ns3::Ptr<ns3::PacketBurst> ns3::LtePhy::GetPacketBurst() [member function]
cls.add_method('GetPacketBurst',
'ns3::Ptr< ns3::PacketBurst >',
[])
## lte-phy.h (module 'lte'): uint8_t ns3::LtePhy::GetRbgSize() const [member function]
cls.add_method('GetRbgSize',
'uint8_t',
[],
is_const=True)
## lte-phy.h (module 'lte'): double ns3::LtePhy::GetTti() const [member function]
cls.add_method('GetTti',
'double',
[],
is_const=True)
## lte-phy.h (module 'lte'): static ns3::TypeId ns3::LtePhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-phy.h (module 'lte'): ns3::Ptr<ns3::LteSpectrumPhy> ns3::LtePhy::GetUplinkSpectrumPhy() [member function]
cls.add_method('GetUplinkSpectrumPhy',
'ns3::Ptr< ns3::LteSpectrumPhy >',
[])
## lte-phy.h (module 'lte'): std::vector<int, std::allocator<int> > ns3::LtePhy::GetUplinkSubChannels() [member function]
cls.add_method('GetUplinkSubChannels',
'std::vector< int >',
[])
## lte-phy.h (module 'lte'): void ns3::LtePhy::ReceiveIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('ReceiveIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')],
is_pure_virtual=True, is_virtual=True)
## lte-phy.h (module 'lte'): void ns3::LtePhy::SetControlMessages(ns3::Ptr<ns3::IdealControlMessage> m) [member function]
cls.add_method('SetControlMessages',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'm')])
## lte-phy.h (module 'lte'): void ns3::LtePhy::SetDevice(ns3::Ptr<ns3::LteNetDevice> d) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::LteNetDevice >', 'd')])
## lte-phy.h (module 'lte'): void ns3::LtePhy::SetDownlinkChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function]
cls.add_method('SetDownlinkChannel',
'void',
[param('ns3::Ptr< ns3::SpectrumChannel >', 'c')])
## lte-phy.h (module 'lte'): void ns3::LtePhy::SetDownlinkSubChannels(std::vector<int, std::allocator<int> > mask) [member function]
cls.add_method('SetDownlinkSubChannels',
'void',
[param('std::vector< int >', 'mask')])
## lte-phy.h (module 'lte'): void ns3::LtePhy::SetMacPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('SetMacPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## lte-phy.h (module 'lte'): void ns3::LtePhy::SetTti(double tti) [member function]
cls.add_method('SetTti',
'void',
[param('double', 'tti')])
## lte-phy.h (module 'lte'): void ns3::LtePhy::SetUplinkChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function]
cls.add_method('SetUplinkChannel',
'void',
[param('ns3::Ptr< ns3::SpectrumChannel >', 'c')])
## lte-phy.h (module 'lte'): void ns3::LtePhy::SetUplinkSubChannels(std::vector<int, std::allocator<int> > mask) [member function]
cls.add_method('SetUplinkSubChannels',
'void',
[param('std::vector< int >', 'mask')])
return
def register_Ns3LteRadioBearerInfo_methods(root_module, cls):
## lte-radio-bearer-info.h (module 'lte'): ns3::LteRadioBearerInfo::LteRadioBearerInfo(ns3::LteRadioBearerInfo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRadioBearerInfo const &', 'arg0')])
## lte-radio-bearer-info.h (module 'lte'): ns3::LteRadioBearerInfo::LteRadioBearerInfo() [constructor]
cls.add_constructor([])
## lte-radio-bearer-info.h (module 'lte'): static ns3::TypeId ns3::LteRadioBearerInfo::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-radio-bearer-info.h (module 'lte'): ns3::LteRadioBearerInfo::m_pdcp [variable]
cls.add_instance_attribute('m_pdcp', 'ns3::Ptr< ns3::LtePdcp >', is_const=False)
## lte-radio-bearer-info.h (module 'lte'): ns3::LteRadioBearerInfo::m_rlc [variable]
cls.add_instance_attribute('m_rlc', 'ns3::Ptr< ns3::LteRlc >', is_const=False)
return
def register_Ns3LteRlc_methods(root_module, cls):
## lte-rlc.h (module 'lte'): ns3::LteRlc::LteRlc(ns3::LteRlc const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlc const &', 'arg0')])
## lte-rlc.h (module 'lte'): ns3::LteRlc::LteRlc() [constructor]
cls.add_constructor([])
## lte-rlc.h (module 'lte'): ns3::LteMacSapUser * ns3::LteRlc::GetLteMacSapUser() [member function]
cls.add_method('GetLteMacSapUser',
'ns3::LteMacSapUser *',
[])
## lte-rlc.h (module 'lte'): ns3::LteRlcSapProvider * ns3::LteRlc::GetLteRlcSapProvider() [member function]
cls.add_method('GetLteRlcSapProvider',
'ns3::LteRlcSapProvider *',
[])
## lte-rlc.h (module 'lte'): static ns3::TypeId ns3::LteRlc::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-rlc.h (module 'lte'): void ns3::LteRlc::SetLcId(uint8_t lcId) [member function]
cls.add_method('SetLcId',
'void',
[param('uint8_t', 'lcId')])
## lte-rlc.h (module 'lte'): void ns3::LteRlc::SetLteMacSapProvider(ns3::LteMacSapProvider * s) [member function]
cls.add_method('SetLteMacSapProvider',
'void',
[param('ns3::LteMacSapProvider *', 's')])
## lte-rlc.h (module 'lte'): void ns3::LteRlc::SetLteRlcSapUser(ns3::LteRlcSapUser * s) [member function]
cls.add_method('SetLteRlcSapUser',
'void',
[param('ns3::LteRlcSapUser *', 's')])
## lte-rlc.h (module 'lte'): void ns3::LteRlc::SetRnti(uint16_t rnti) [member function]
cls.add_method('SetRnti',
'void',
[param('uint16_t', 'rnti')])
## lte-rlc.h (module 'lte'): void ns3::LteRlc::DoNotifyHarqDeliveryFailure() [member function]
cls.add_method('DoNotifyHarqDeliveryFailure',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## lte-rlc.h (module 'lte'): void ns3::LteRlc::DoNotifyTxOpportunity(uint32_t bytes, uint8_t layer) [member function]
cls.add_method('DoNotifyTxOpportunity',
'void',
[param('uint32_t', 'bytes'), param('uint8_t', 'layer')],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## lte-rlc.h (module 'lte'): void ns3::LteRlc::DoReceivePdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoReceivePdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, visibility='protected', is_virtual=True)
## lte-rlc.h (module 'lte'): void ns3::LteRlc::DoTransmitPdcpPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoTransmitPdcpPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3LteRlcAm_methods(root_module, cls):
## lte-rlc-am.h (module 'lte'): ns3::LteRlcAm::LteRlcAm(ns3::LteRlcAm const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlcAm const &', 'arg0')])
## lte-rlc-am.h (module 'lte'): ns3::LteRlcAm::LteRlcAm() [constructor]
cls.add_constructor([])
## lte-rlc-am.h (module 'lte'): void ns3::LteRlcAm::DoNotifyHarqDeliveryFailure() [member function]
cls.add_method('DoNotifyHarqDeliveryFailure',
'void',
[],
is_virtual=True)
## lte-rlc-am.h (module 'lte'): void ns3::LteRlcAm::DoNotifyTxOpportunity(uint32_t bytes, uint8_t layer) [member function]
cls.add_method('DoNotifyTxOpportunity',
'void',
[param('uint32_t', 'bytes'), param('uint8_t', 'layer')],
is_virtual=True)
## lte-rlc-am.h (module 'lte'): void ns3::LteRlcAm::DoReceivePdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoReceivePdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_virtual=True)
## lte-rlc-am.h (module 'lte'): void ns3::LteRlcAm::DoTransmitPdcpPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoTransmitPdcpPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_virtual=True)
## lte-rlc-am.h (module 'lte'): static ns3::TypeId ns3::LteRlcAm::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-rlc-am.h (module 'lte'): void ns3::LteRlcAm::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_Ns3LteRlcSm_methods(root_module, cls):
## lte-rlc.h (module 'lte'): ns3::LteRlcSm::LteRlcSm(ns3::LteRlcSm const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlcSm const &', 'arg0')])
## lte-rlc.h (module 'lte'): ns3::LteRlcSm::LteRlcSm() [constructor]
cls.add_constructor([])
## lte-rlc.h (module 'lte'): void ns3::LteRlcSm::DoNotifyHarqDeliveryFailure() [member function]
cls.add_method('DoNotifyHarqDeliveryFailure',
'void',
[],
is_virtual=True)
## lte-rlc.h (module 'lte'): void ns3::LteRlcSm::DoNotifyTxOpportunity(uint32_t bytes, uint8_t layer) [member function]
cls.add_method('DoNotifyTxOpportunity',
'void',
[param('uint32_t', 'bytes'), param('uint8_t', 'layer')],
is_virtual=True)
## lte-rlc.h (module 'lte'): void ns3::LteRlcSm::DoReceivePdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoReceivePdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_virtual=True)
## lte-rlc.h (module 'lte'): void ns3::LteRlcSm::DoTransmitPdcpPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoTransmitPdcpPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_virtual=True)
## lte-rlc.h (module 'lte'): static ns3::TypeId ns3::LteRlcSm::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-rlc.h (module 'lte'): void ns3::LteRlcSm::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_Ns3LteRlcUm_methods(root_module, cls):
## lte-rlc-um.h (module 'lte'): ns3::LteRlcUm::LteRlcUm(ns3::LteRlcUm const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteRlcUm const &', 'arg0')])
## lte-rlc-um.h (module 'lte'): ns3::LteRlcUm::LteRlcUm() [constructor]
cls.add_constructor([])
## lte-rlc-um.h (module 'lte'): void ns3::LteRlcUm::DoNotifyHarqDeliveryFailure() [member function]
cls.add_method('DoNotifyHarqDeliveryFailure',
'void',
[],
is_virtual=True)
## lte-rlc-um.h (module 'lte'): void ns3::LteRlcUm::DoNotifyTxOpportunity(uint32_t bytes, uint8_t layer) [member function]
cls.add_method('DoNotifyTxOpportunity',
'void',
[param('uint32_t', 'bytes'), param('uint8_t', 'layer')],
is_virtual=True)
## lte-rlc-um.h (module 'lte'): void ns3::LteRlcUm::DoReceivePdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoReceivePdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_virtual=True)
## lte-rlc-um.h (module 'lte'): void ns3::LteRlcUm::DoTransmitPdcpPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoTransmitPdcpPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_virtual=True)
## lte-rlc-um.h (module 'lte'): static ns3::TypeId ns3::LteRlcUm::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-rlc-um.h (module 'lte'): void ns3::LteRlcUm::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_Ns3LteSinrChunkProcessor_methods(root_module, cls):
## lte-sinr-chunk-processor.h (module 'lte'): ns3::LteSinrChunkProcessor::LteSinrChunkProcessor() [constructor]
cls.add_constructor([])
## lte-sinr-chunk-processor.h (module 'lte'): ns3::LteSinrChunkProcessor::LteSinrChunkProcessor(ns3::LteSinrChunkProcessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteSinrChunkProcessor const &', 'arg0')])
## lte-sinr-chunk-processor.h (module 'lte'): void ns3::LteSinrChunkProcessor::End() [member function]
cls.add_method('End',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## lte-sinr-chunk-processor.h (module 'lte'): void ns3::LteSinrChunkProcessor::EvaluateSinrChunk(ns3::SpectrumValue const & sinr, ns3::Time duration) [member function]
cls.add_method('EvaluateSinrChunk',
'void',
[param('ns3::SpectrumValue const &', 'sinr'), param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## lte-sinr-chunk-processor.h (module 'lte'): void ns3::LteSinrChunkProcessor::Start() [member function]
cls.add_method('Start',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3LteSpectrumPhy_methods(root_module, cls):
## lte-spectrum-phy.h (module 'lte'): ns3::LteSpectrumPhy::LteSpectrumPhy() [constructor]
cls.add_constructor([])
## lte-spectrum-phy.h (module 'lte'): static ns3::TypeId ns3::LteSpectrumPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::SpectrumChannel >', 'c')],
is_virtual=True)
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function]
cls.add_method('SetMobility',
'void',
[param('ns3::Ptr< ns3::MobilityModel >', 'm')],
is_virtual=True)
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'd')],
is_virtual=True)
## lte-spectrum-phy.h (module 'lte'): ns3::Ptr<ns3::MobilityModel> ns3::LteSpectrumPhy::GetMobility() [member function]
cls.add_method('GetMobility',
'ns3::Ptr< ns3::MobilityModel >',
[],
is_virtual=True)
## lte-spectrum-phy.h (module 'lte'): ns3::Ptr<ns3::NetDevice> ns3::LteSpectrumPhy::GetDevice() [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_virtual=True)
## lte-spectrum-phy.h (module 'lte'): ns3::Ptr<ns3::SpectrumModel const> ns3::LteSpectrumPhy::GetRxSpectrumModel() const [member function]
cls.add_method('GetRxSpectrumModel',
'ns3::Ptr< ns3::SpectrumModel const >',
[],
is_const=True, is_virtual=True)
## lte-spectrum-phy.h (module 'lte'): ns3::Ptr<ns3::AntennaModel> ns3::LteSpectrumPhy::GetRxAntenna() [member function]
cls.add_method('GetRxAntenna',
'ns3::Ptr< ns3::AntennaModel >',
[],
is_virtual=True)
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function]
cls.add_method('StartRx',
'void',
[param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')],
is_virtual=True)
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetTxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> txPsd) [member function]
cls.add_method('SetTxPowerSpectralDensity',
'void',
[param('ns3::Ptr< ns3::SpectrumValue >', 'txPsd')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetNoisePowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> noisePsd) [member function]
cls.add_method('SetNoisePowerSpectralDensity',
'void',
[param('ns3::Ptr< ns3::SpectrumValue const >', 'noisePsd')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetAntenna(ns3::Ptr<ns3::AntennaModel> a) [member function]
cls.add_method('SetAntenna',
'void',
[param('ns3::Ptr< ns3::AntennaModel >', 'a')])
## lte-spectrum-phy.h (module 'lte'): bool ns3::LteSpectrumPhy::StartTx(ns3::Ptr<ns3::PacketBurst> pb) [member function]
cls.add_method('StartTx',
'bool',
[param('ns3::Ptr< ns3::PacketBurst >', 'pb')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetGenericPhyTxEndCallback(ns3::GenericPhyTxEndCallback c) [member function]
cls.add_method('SetGenericPhyTxEndCallback',
'void',
[param('ns3::GenericPhyTxEndCallback', 'c')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetGenericPhyRxEndErrorCallback(ns3::GenericPhyRxEndErrorCallback c) [member function]
cls.add_method('SetGenericPhyRxEndErrorCallback',
'void',
[param('ns3::GenericPhyRxEndErrorCallback', 'c')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetGenericPhyRxEndOkCallback(ns3::GenericPhyRxEndOkCallback c) [member function]
cls.add_method('SetGenericPhyRxEndOkCallback',
'void',
[param('ns3::GenericPhyRxEndOkCallback', 'c')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetState(ns3::LteSpectrumPhy::State newState) [member function]
cls.add_method('SetState',
'void',
[param('ns3::LteSpectrumPhy::State', 'newState')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetCellId(uint16_t cellId) [member function]
cls.add_method('SetCellId',
'void',
[param('uint16_t', 'cellId')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::AddSinrChunkProcessor(ns3::Ptr<ns3::LteSinrChunkProcessor> p) [member function]
cls.add_method('AddSinrChunkProcessor',
'void',
[param('ns3::Ptr< ns3::LteSinrChunkProcessor >', 'p')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::AddExpectedTb(uint16_t rnti, uint16_t size, uint8_t mcs, std::vector<int, std::allocator<int> > map, uint8_t layer) [member function]
cls.add_method('AddExpectedTb',
'void',
[param('uint16_t', 'rnti'), param('uint16_t', 'size'), param('uint8_t', 'mcs'), param('std::vector< int >', 'map'), param('uint8_t', 'layer')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::UpdateSinrPerceived(ns3::SpectrumValue const & sinr) [member function]
cls.add_method('UpdateSinrPerceived',
'void',
[param('ns3::SpectrumValue const &', 'sinr')])
## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::SetTransmissionMode(uint8_t txMode) [member function]
cls.add_method('SetTransmissionMode',
'void',
[param('uint8_t', 'txMode')])
return
def register_Ns3LteSpectrumSignalParameters_methods(root_module, cls):
## lte-spectrum-signal-parameters.h (module 'lte'): ns3::LteSpectrumSignalParameters::LteSpectrumSignalParameters() [constructor]
cls.add_constructor([])
## lte-spectrum-signal-parameters.h (module 'lte'): ns3::LteSpectrumSignalParameters::LteSpectrumSignalParameters(ns3::LteSpectrumSignalParameters const & p) [copy constructor]
cls.add_constructor([param('ns3::LteSpectrumSignalParameters const &', 'p')])
## lte-spectrum-signal-parameters.h (module 'lte'): ns3::Ptr<ns3::SpectrumSignalParameters> ns3::LteSpectrumSignalParameters::Copy() [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::SpectrumSignalParameters >',
[],
is_virtual=True)
## lte-spectrum-signal-parameters.h (module 'lte'): ns3::LteSpectrumSignalParameters::packetBurst [variable]
cls.add_instance_attribute('packetBurst', 'ns3::Ptr< ns3::PacketBurst >', is_const=False)
return
def register_Ns3LteStatsCalculator_methods(root_module, cls):
## lte-stats-calculator.h (module 'lte'): ns3::LteStatsCalculator::LteStatsCalculator(ns3::LteStatsCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteStatsCalculator const &', 'arg0')])
## lte-stats-calculator.h (module 'lte'): ns3::LteStatsCalculator::LteStatsCalculator() [constructor]
cls.add_constructor([])
## lte-stats-calculator.h (module 'lte'): bool ns3::LteStatsCalculator::ExistsCellIdPath(std::string path) [member function]
cls.add_method('ExistsCellIdPath',
'bool',
[param('std::string', 'path')])
## lte-stats-calculator.h (module 'lte'): bool ns3::LteStatsCalculator::ExistsImsiPath(std::string path) [member function]
cls.add_method('ExistsImsiPath',
'bool',
[param('std::string', 'path')])
## lte-stats-calculator.h (module 'lte'): uint16_t ns3::LteStatsCalculator::GetCellIdPath(std::string path) [member function]
cls.add_method('GetCellIdPath',
'uint16_t',
[param('std::string', 'path')])
## lte-stats-calculator.h (module 'lte'): std::string ns3::LteStatsCalculator::GetDlOutputFilename() [member function]
cls.add_method('GetDlOutputFilename',
'std::string',
[])
## lte-stats-calculator.h (module 'lte'): uint64_t ns3::LteStatsCalculator::GetImsiPath(std::string path) [member function]
cls.add_method('GetImsiPath',
'uint64_t',
[param('std::string', 'path')])
## lte-stats-calculator.h (module 'lte'): static ns3::TypeId ns3::LteStatsCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-stats-calculator.h (module 'lte'): std::string ns3::LteStatsCalculator::GetUlOutputFilename() [member function]
cls.add_method('GetUlOutputFilename',
'std::string',
[])
## lte-stats-calculator.h (module 'lte'): void ns3::LteStatsCalculator::SetCellIdPath(std::string path, uint16_t cellId) [member function]
cls.add_method('SetCellIdPath',
'void',
[param('std::string', 'path'), param('uint16_t', 'cellId')])
## lte-stats-calculator.h (module 'lte'): void ns3::LteStatsCalculator::SetDlOutputFilename(std::string outputFilename) [member function]
cls.add_method('SetDlOutputFilename',
'void',
[param('std::string', 'outputFilename')])
## lte-stats-calculator.h (module 'lte'): void ns3::LteStatsCalculator::SetImsiPath(std::string path, uint64_t imsi) [member function]
cls.add_method('SetImsiPath',
'void',
[param('std::string', 'path'), param('uint64_t', 'imsi')])
## lte-stats-calculator.h (module 'lte'): void ns3::LteStatsCalculator::SetUlOutputFilename(std::string outputFilename) [member function]
cls.add_method('SetUlOutputFilename',
'void',
[param('std::string', 'outputFilename')])
return
def register_Ns3LteUeMac_methods(root_module, cls):
## lte-ue-mac.h (module 'lte'): ns3::LteUeMac::LteUeMac(ns3::LteUeMac const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteUeMac const &', 'arg0')])
## lte-ue-mac.h (module 'lte'): ns3::LteUeMac::LteUeMac() [constructor]
cls.add_constructor([])
## lte-ue-mac.h (module 'lte'): void ns3::LteUeMac::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-ue-mac.h (module 'lte'): void ns3::LteUeMac::DoSubframeIndication(uint32_t frameNo, uint32_t subframeNo) [member function]
cls.add_method('DoSubframeIndication',
'void',
[param('uint32_t', 'frameNo'), param('uint32_t', 'subframeNo')])
## lte-ue-mac.h (module 'lte'): ns3::LteMacSapProvider * ns3::LteUeMac::GetLteMacSapProvider() [member function]
cls.add_method('GetLteMacSapProvider',
'ns3::LteMacSapProvider *',
[])
## lte-ue-mac.h (module 'lte'): ns3::LteUeCmacSapProvider * ns3::LteUeMac::GetLteUeCmacSapProvider() [member function]
cls.add_method('GetLteUeCmacSapProvider',
'ns3::LteUeCmacSapProvider *',
[])
## lte-ue-mac.h (module 'lte'): ns3::LteUePhySapUser * ns3::LteUeMac::GetLteUePhySapUser() [member function]
cls.add_method('GetLteUePhySapUser',
'ns3::LteUePhySapUser *',
[])
## lte-ue-mac.h (module 'lte'): static ns3::TypeId ns3::LteUeMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-ue-mac.h (module 'lte'): void ns3::LteUeMac::SetLteUeCmacSapUser(ns3::LteUeCmacSapUser * s) [member function]
cls.add_method('SetLteUeCmacSapUser',
'void',
[param('ns3::LteUeCmacSapUser *', 's')])
## lte-ue-mac.h (module 'lte'): void ns3::LteUeMac::SetLteUePhySapProvider(ns3::LteUePhySapProvider * s) [member function]
cls.add_method('SetLteUePhySapProvider',
'void',
[param('ns3::LteUePhySapProvider *', 's')])
return
def register_Ns3LteUePhy_methods(root_module, cls):
## lte-ue-phy.h (module 'lte'): ns3::LteUePhy::LteUePhy(ns3::LteUePhy const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteUePhy const &', 'arg0')])
## lte-ue-phy.h (module 'lte'): ns3::LteUePhy::LteUePhy() [constructor]
cls.add_constructor([])
## lte-ue-phy.h (module 'lte'): ns3::LteUePhy::LteUePhy(ns3::Ptr<ns3::LteSpectrumPhy> dlPhy, ns3::Ptr<ns3::LteSpectrumPhy> ulPhy) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::LteSpectrumPhy >', 'dlPhy'), param('ns3::Ptr< ns3::LteSpectrumPhy >', 'ulPhy')])
## lte-ue-phy.h (module 'lte'): ns3::Ptr<ns3::DlCqiIdealControlMessage> ns3::LteUePhy::CreateDlCqiFeedbackMessage(ns3::SpectrumValue const & sinr) [member function]
cls.add_method('CreateDlCqiFeedbackMessage',
'ns3::Ptr< ns3::DlCqiIdealControlMessage >',
[param('ns3::SpectrumValue const &', 'sinr')])
## lte-ue-phy.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::LteUePhy::CreateTxPowerSpectralDensity() [member function]
cls.add_method('CreateTxPowerSpectralDensity',
'ns3::Ptr< ns3::SpectrumValue >',
[],
is_virtual=True)
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::DoSendIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('DoSendIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')],
is_virtual=True)
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::DoSendMacPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoSendMacPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_virtual=True)
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::DoSetTransmissionMode(uint8_t txMode) [member function]
cls.add_method('DoSetTransmissionMode',
'void',
[param('uint8_t', 'txMode')],
is_virtual=True)
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::DoSetUplinkSubChannels() [member function]
cls.add_method('DoSetUplinkSubChannels',
'void',
[],
is_virtual=True)
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
is_virtual=True)
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::GenerateCqiReport(ns3::SpectrumValue const & sinr) [member function]
cls.add_method('GenerateCqiReport',
'void',
[param('ns3::SpectrumValue const &', 'sinr')],
is_virtual=True)
## lte-ue-phy.h (module 'lte'): ns3::LteUePhySapProvider * ns3::LteUePhy::GetLteUePhySapProvider() [member function]
cls.add_method('GetLteUePhySapProvider',
'ns3::LteUePhySapProvider *',
[])
## lte-ue-phy.h (module 'lte'): uint8_t ns3::LteUePhy::GetMacChDelay() const [member function]
cls.add_method('GetMacChDelay',
'uint8_t',
[],
is_const=True)
## lte-ue-phy.h (module 'lte'): double ns3::LteUePhy::GetNoiseFigure() const [member function]
cls.add_method('GetNoiseFigure',
'double',
[],
is_const=True)
## lte-ue-phy.h (module 'lte'): std::vector<int, std::allocator<int> > ns3::LteUePhy::GetSubChannelsForReception() [member function]
cls.add_method('GetSubChannelsForReception',
'std::vector< int >',
[])
## lte-ue-phy.h (module 'lte'): std::vector<int, std::allocator<int> > ns3::LteUePhy::GetSubChannelsForTransmission() [member function]
cls.add_method('GetSubChannelsForTransmission',
'std::vector< int >',
[])
## lte-ue-phy.h (module 'lte'): double ns3::LteUePhy::GetTxPower() const [member function]
cls.add_method('GetTxPower',
'double',
[],
is_const=True)
## lte-ue-phy.h (module 'lte'): static ns3::TypeId ns3::LteUePhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::PhyPduReceived(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('PhyPduReceived',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::ReceiveIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('ReceiveIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')],
is_virtual=True)
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::SetEnbCellId(uint16_t cellId) [member function]
cls.add_method('SetEnbCellId',
'void',
[param('uint16_t', 'cellId')])
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::SetLteUePhySapUser(ns3::LteUePhySapUser * s) [member function]
cls.add_method('SetLteUePhySapUser',
'void',
[param('ns3::LteUePhySapUser *', 's')])
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::SetNoiseFigure(double pow) [member function]
cls.add_method('SetNoiseFigure',
'void',
[param('double', 'pow')])
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::SetRnti(uint16_t rnti) [member function]
cls.add_method('SetRnti',
'void',
[param('uint16_t', 'rnti')])
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::SetSubChannelsForReception(std::vector<int, std::allocator<int> > mask) [member function]
cls.add_method('SetSubChannelsForReception',
'void',
[param('std::vector< int >', 'mask')])
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::SetSubChannelsForTransmission(std::vector<int, std::allocator<int> > mask) [member function]
cls.add_method('SetSubChannelsForTransmission',
'void',
[param('std::vector< int >', 'mask')])
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::SetTxPower(double pow) [member function]
cls.add_method('SetTxPower',
'void',
[param('double', 'pow')])
## lte-ue-phy.h (module 'lte'): void ns3::LteUePhy::SubframeIndication(uint32_t frameNo, uint32_t subframeNo) [member function]
cls.add_method('SubframeIndication',
'void',
[param('uint32_t', 'frameNo'), param('uint32_t', 'subframeNo')])
return
def register_Ns3LteUeRrc_methods(root_module, cls):
## lte-ue-rrc.h (module 'lte'): ns3::LteUeRrc::LteUeRrc(ns3::LteUeRrc const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteUeRrc const &', 'arg0')])
## lte-ue-rrc.h (module 'lte'): ns3::LteUeRrc::LteUeRrc() [constructor]
cls.add_constructor([])
## lte-ue-rrc.h (module 'lte'): void ns3::LteUeRrc::ConfigureUe(uint16_t rnti, uint16_t cellId) [member function]
cls.add_method('ConfigureUe',
'void',
[param('uint16_t', 'rnti'), param('uint16_t', 'cellId')])
## lte-ue-rrc.h (module 'lte'): void ns3::LteUeRrc::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-ue-rrc.h (module 'lte'): void ns3::LteUeRrc::DoRrcConfigurationUpdateInd(ns3::LteUeConfig_t params) [member function]
cls.add_method('DoRrcConfigurationUpdateInd',
'void',
[param('ns3::LteUeConfig_t', 'params')])
## lte-ue-rrc.h (module 'lte'): uint16_t ns3::LteUeRrc::GetCellId() [member function]
cls.add_method('GetCellId',
'uint16_t',
[])
## lte-ue-rrc.h (module 'lte'): std::vector<unsigned char, std::allocator<unsigned char> > ns3::LteUeRrc::GetLcIdVector() [member function]
cls.add_method('GetLcIdVector',
'std::vector< unsigned char >',
[])
## lte-ue-rrc.h (module 'lte'): ns3::LteUeCmacSapUser * ns3::LteUeRrc::GetLteUeCmacSapUser() [member function]
cls.add_method('GetLteUeCmacSapUser',
'ns3::LteUeCmacSapUser *',
[])
## lte-ue-rrc.h (module 'lte'): uint16_t ns3::LteUeRrc::GetRnti() [member function]
cls.add_method('GetRnti',
'uint16_t',
[])
## lte-ue-rrc.h (module 'lte'): static ns3::TypeId ns3::LteUeRrc::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-ue-rrc.h (module 'lte'): void ns3::LteUeRrc::ReleaseRadioBearer(uint16_t rnti, uint8_t lcId) [member function]
cls.add_method('ReleaseRadioBearer',
'void',
[param('uint16_t', 'rnti'), param('uint8_t', 'lcId')])
## lte-ue-rrc.h (module 'lte'): bool ns3::LteUeRrc::Send(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## lte-ue-rrc.h (module 'lte'): void ns3::LteUeRrc::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetForwardUpCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')])
## lte-ue-rrc.h (module 'lte'): void ns3::LteUeRrc::SetLteMacSapProvider(ns3::LteMacSapProvider * s) [member function]
cls.add_method('SetLteMacSapProvider',
'void',
[param('ns3::LteMacSapProvider *', 's')])
## lte-ue-rrc.h (module 'lte'): void ns3::LteUeRrc::SetLteUeCmacSapProvider(ns3::LteUeCmacSapProvider * s) [member function]
cls.add_method('SetLteUeCmacSapProvider',
'void',
[param('ns3::LteUeCmacSapProvider *', 's')])
## lte-ue-rrc.h (module 'lte'): void ns3::LteUeRrc::SetupRadioBearer(uint16_t rnti, ns3::EpsBearer bearer, ns3::TypeId rlcTypeId, uint8_t lcid, ns3::Ptr<ns3::EpcTft> tft) [member function]
cls.add_method('SetupRadioBearer',
'void',
[param('uint16_t', 'rnti'), param('ns3::EpsBearer', 'bearer'), param('ns3::TypeId', 'rlcTypeId'), param('uint8_t', 'lcid'), param('ns3::Ptr< ns3::EpcTft >', 'tft')])
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_Ns3MacStatsCalculator_methods(root_module, cls):
## mac-stats-calculator.h (module 'lte'): ns3::MacStatsCalculator::MacStatsCalculator(ns3::MacStatsCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacStatsCalculator const &', 'arg0')])
## mac-stats-calculator.h (module 'lte'): ns3::MacStatsCalculator::MacStatsCalculator() [constructor]
cls.add_constructor([])
## mac-stats-calculator.h (module 'lte'): void ns3::MacStatsCalculator::DlScheduling(uint16_t cellId, uint64_t imsi, uint32_t frameNo, uint32_t subframeNo, uint16_t rnti, uint8_t mcsTb1, uint16_t sizeTb1, uint8_t mcsTb2, uint16_t sizeTb2) [member function]
cls.add_method('DlScheduling',
'void',
[param('uint16_t', 'cellId'), param('uint64_t', 'imsi'), param('uint32_t', 'frameNo'), param('uint32_t', 'subframeNo'), param('uint16_t', 'rnti'), param('uint8_t', 'mcsTb1'), param('uint16_t', 'sizeTb1'), param('uint8_t', 'mcsTb2'), param('uint16_t', 'sizeTb2')])
## mac-stats-calculator.h (module 'lte'): std::string ns3::MacStatsCalculator::GetDlOutputFilename() [member function]
cls.add_method('GetDlOutputFilename',
'std::string',
[])
## mac-stats-calculator.h (module 'lte'): static ns3::TypeId ns3::MacStatsCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mac-stats-calculator.h (module 'lte'): std::string ns3::MacStatsCalculator::GetUlOutputFilename() [member function]
cls.add_method('GetUlOutputFilename',
'std::string',
[])
## mac-stats-calculator.h (module 'lte'): void ns3::MacStatsCalculator::SetDlOutputFilename(std::string outputFilename) [member function]
cls.add_method('SetDlOutputFilename',
'void',
[param('std::string', 'outputFilename')])
## mac-stats-calculator.h (module 'lte'): void ns3::MacStatsCalculator::SetUlOutputFilename(std::string outputFilename) [member function]
cls.add_method('SetUlOutputFilename',
'void',
[param('std::string', 'outputFilename')])
## mac-stats-calculator.h (module 'lte'): void ns3::MacStatsCalculator::UlScheduling(uint16_t cellId, uint64_t imsi, uint32_t frameNo, uint32_t subframeNo, uint16_t rnti, uint8_t mcs, uint16_t sizeTb) [member function]
cls.add_method('UlScheduling',
'void',
[param('uint16_t', 'cellId'), param('uint64_t', 'imsi'), param('uint32_t', 'frameNo'), param('uint32_t', 'subframeNo'), param('uint16_t', 'rnti'), param('uint8_t', 'mcs'), param('uint16_t', 'sizeTb')])
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<const ns3::MobilityModel> position) const [member function]
cls.add_method('GetDistanceFrom',
'double',
[param('ns3::Ptr< ns3::MobilityModel const >', 'position')],
is_const=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetPosition() const [member function]
cls.add_method('GetPosition',
'ns3::Vector',
[],
is_const=True)
## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetRelativeSpeed(ns3::Ptr<const ns3::MobilityModel> other) const [member function]
cls.add_method('GetRelativeSpeed',
'double',
[param('ns3::Ptr< ns3::MobilityModel const >', 'other')],
is_const=True)
## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function]
cls.add_method('GetVelocity',
'ns3::Vector',
[],
is_const=True)
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function]
cls.add_method('SetPosition',
'void',
[param('ns3::Vector const &', 'position')])
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function]
cls.add_method('NotifyCourseChange',
'void',
[],
is_const=True, visibility='protected')
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function]
cls.add_method('DoGetPosition',
'ns3::Vector',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function]
cls.add_method('DoGetVelocity',
'ns3::Vector',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function]
cls.add_method('DoSetPosition',
'void',
[param('ns3::Vector const &', 'position')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3NetDevice_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDevice const &', 'arg0')])
## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3NixVector_methods(root_module, cls):
cls.add_output_stream_operator()
## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor]
cls.add_constructor([])
## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor]
cls.add_constructor([param('ns3::NixVector const &', 'o')])
## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function]
cls.add_method('AddNeighborIndex',
'void',
[param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function]
cls.add_method('BitCount',
'uint32_t',
[param('uint32_t', 'numberOfNeighbors')],
is_const=True)
## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint32_t const *', 'buffer'), param('uint32_t', 'size')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function]
cls.add_method('ExtractNeighborIndex',
'uint32_t',
[param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function]
cls.add_method('GetRemainingBits',
'uint32_t',
[])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3Node_methods(root_module, cls):
## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Node const &', 'arg0')])
## node.h (module 'network'): ns3::Node::Node() [constructor]
cls.add_constructor([])
## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor]
cls.add_constructor([param('uint32_t', 'systemId')])
## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('AddApplication',
'uint32_t',
[param('ns3::Ptr< ns3::Application >', 'application')])
## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddDevice',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function]
cls.add_method('ChecksumEnabled',
'bool',
[],
is_static=True)
## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function]
cls.add_method('GetApplication',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function]
cls.add_method('GetNApplications',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('RegisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function]
cls.add_method('RegisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')])
## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('UnregisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function]
cls.add_method('UnregisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')])
## node.h (module 'network'): void ns3::Node::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## node.h (module 'network'): void ns3::Node::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_Ns3Packet_methods(root_module, cls):
cls.add_output_stream_operator()
## packet.h (module 'network'): ns3::Packet::Packet() [constructor]
cls.add_constructor([])
## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor]
cls.add_constructor([param('ns3::Packet const &', 'o')])
## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor]
cls.add_constructor([param('uint32_t', 'size')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddByteTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header')])
## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddPacketTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer')])
## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function]
cls.add_method('EnablePrinting',
'void',
[],
is_static=True)
## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function]
cls.add_method('FindFirstMatchingByteTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function]
cls.add_method('GetByteTagIterator',
'ns3::ByteTagIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function]
cls.add_method('GetNixVector',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function]
cls.add_method('GetPacketTagIterator',
'ns3::PacketTagIterator',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet.h (module 'network'): 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_Ns3PfFfMacScheduler_methods(root_module, cls):
## pf-ff-mac-scheduler.h (module 'lte'): ns3::PfFfMacScheduler::PfFfMacScheduler(ns3::PfFfMacScheduler const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PfFfMacScheduler const &', 'arg0')])
## pf-ff-mac-scheduler.h (module 'lte'): ns3::PfFfMacScheduler::PfFfMacScheduler() [constructor]
cls.add_constructor([])
## pf-ff-mac-scheduler.h (module 'lte'): void ns3::PfFfMacScheduler::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## pf-ff-mac-scheduler.h (module 'lte'): ns3::FfMacCschedSapProvider * ns3::PfFfMacScheduler::GetFfMacCschedSapProvider() [member function]
cls.add_method('GetFfMacCschedSapProvider',
'ns3::FfMacCschedSapProvider *',
[],
is_virtual=True)
## pf-ff-mac-scheduler.h (module 'lte'): ns3::FfMacSchedSapProvider * ns3::PfFfMacScheduler::GetFfMacSchedSapProvider() [member function]
cls.add_method('GetFfMacSchedSapProvider',
'ns3::FfMacSchedSapProvider *',
[],
is_virtual=True)
## pf-ff-mac-scheduler.h (module 'lte'): static ns3::TypeId ns3::PfFfMacScheduler::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## pf-ff-mac-scheduler.h (module 'lte'): void ns3::PfFfMacScheduler::SetFfMacCschedSapUser(ns3::FfMacCschedSapUser * s) [member function]
cls.add_method('SetFfMacCschedSapUser',
'void',
[param('ns3::FfMacCschedSapUser *', 's')],
is_virtual=True)
## pf-ff-mac-scheduler.h (module 'lte'): void ns3::PfFfMacScheduler::SetFfMacSchedSapUser(ns3::FfMacSchedSapUser * s) [member function]
cls.add_method('SetFfMacSchedSapUser',
'void',
[param('ns3::FfMacSchedSapUser *', 's')],
is_virtual=True)
## pf-ff-mac-scheduler.h (module 'lte'): void ns3::PfFfMacScheduler::TransmissionModeConfigurationUpdate(uint16_t rnti, uint8_t txMode) [member function]
cls.add_method('TransmissionModeConfigurationUpdate',
'void',
[param('uint16_t', 'rnti'), param('uint8_t', 'txMode')])
return
def register_Ns3PointerChecker_methods(root_module, cls):
## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker() [constructor]
cls.add_constructor([])
## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker(ns3::PointerChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PointerChecker const &', 'arg0')])
## pointer.h (module 'core'): ns3::TypeId ns3::PointerChecker::GetPointeeTypeId() const [member function]
cls.add_method('GetPointeeTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3PointerValue_methods(root_module, cls):
## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::PointerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PointerValue const &', 'arg0')])
## pointer.h (module 'core'): ns3::PointerValue::PointerValue() [constructor]
cls.add_constructor([])
## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::Ptr<ns3::Object> object) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Object >', 'object')])
## pointer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::PointerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## pointer.h (module 'core'): bool ns3::PointerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## pointer.h (module 'core'): ns3::Ptr<ns3::Object> ns3::PointerValue::GetObject() const [member function]
cls.add_method('GetObject',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## pointer.h (module 'core'): std::string ns3::PointerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## pointer.h (module 'core'): void ns3::PointerValue::SetObject(ns3::Ptr<ns3::Object> object) [member function]
cls.add_method('SetObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'object')])
return
def register_Ns3RadioBearerStatsCalculator_methods(root_module, cls):
## radio-bearer-stats-calculator.h (module 'lte'): ns3::RadioBearerStatsCalculator::RadioBearerStatsCalculator(ns3::RadioBearerStatsCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RadioBearerStatsCalculator const &', 'arg0')])
## radio-bearer-stats-calculator.h (module 'lte'): ns3::RadioBearerStatsCalculator::RadioBearerStatsCalculator() [constructor]
cls.add_constructor([])
## radio-bearer-stats-calculator.h (module 'lte'): ns3::RadioBearerStatsCalculator::RadioBearerStatsCalculator(std::string protocolType) [constructor]
cls.add_constructor([param('std::string', 'protocolType')])
## radio-bearer-stats-calculator.h (module 'lte'): void ns3::RadioBearerStatsCalculator::DlRxPdu(uint64_t imsi, uint16_t rnti, uint8_t lcid, uint32_t packetSize, uint64_t delay) [member function]
cls.add_method('DlRxPdu',
'void',
[param('uint64_t', 'imsi'), param('uint16_t', 'rnti'), param('uint8_t', 'lcid'), param('uint32_t', 'packetSize'), param('uint64_t', 'delay')])
## radio-bearer-stats-calculator.h (module 'lte'): void ns3::RadioBearerStatsCalculator::DlTxPdu(uint16_t cellId, uint64_t imsi, uint16_t rnti, uint8_t lcid, uint32_t packetSize) [member function]
cls.add_method('DlTxPdu',
'void',
[param('uint16_t', 'cellId'), param('uint64_t', 'imsi'), param('uint16_t', 'rnti'), param('uint8_t', 'lcid'), param('uint32_t', 'packetSize')])
## radio-bearer-stats-calculator.h (module 'lte'): void ns3::RadioBearerStatsCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## radio-bearer-stats-calculator.h (module 'lte'): uint32_t ns3::RadioBearerStatsCalculator::GetDlCellId(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetDlCellId',
'uint32_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): double ns3::RadioBearerStatsCalculator::GetDlDelay(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetDlDelay',
'double',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): std::vector<double, std::allocator<double> > ns3::RadioBearerStatsCalculator::GetDlDelayStats(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetDlDelayStats',
'std::vector< double >',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): std::string ns3::RadioBearerStatsCalculator::GetDlOutputFilename() [member function]
cls.add_method('GetDlOutputFilename',
'std::string',
[])
## radio-bearer-stats-calculator.h (module 'lte'): std::string ns3::RadioBearerStatsCalculator::GetDlPdcpOutputFilename() [member function]
cls.add_method('GetDlPdcpOutputFilename',
'std::string',
[])
## radio-bearer-stats-calculator.h (module 'lte'): std::vector<double, std::allocator<double> > ns3::RadioBearerStatsCalculator::GetDlPduSizeStats(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetDlPduSizeStats',
'std::vector< double >',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): uint64_t ns3::RadioBearerStatsCalculator::GetDlRxData(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetDlRxData',
'uint64_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): uint32_t ns3::RadioBearerStatsCalculator::GetDlRxPackets(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetDlRxPackets',
'uint32_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): uint64_t ns3::RadioBearerStatsCalculator::GetDlTxData(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetDlTxData',
'uint64_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): uint32_t ns3::RadioBearerStatsCalculator::GetDlTxPackets(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetDlTxPackets',
'uint32_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): static ns3::TypeId ns3::RadioBearerStatsCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## radio-bearer-stats-calculator.h (module 'lte'): uint32_t ns3::RadioBearerStatsCalculator::GetUlCellId(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetUlCellId',
'uint32_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): double ns3::RadioBearerStatsCalculator::GetUlDelay(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetUlDelay',
'double',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): std::vector<double, std::allocator<double> > ns3::RadioBearerStatsCalculator::GetUlDelayStats(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetUlDelayStats',
'std::vector< double >',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): std::string ns3::RadioBearerStatsCalculator::GetUlOutputFilename() [member function]
cls.add_method('GetUlOutputFilename',
'std::string',
[])
## radio-bearer-stats-calculator.h (module 'lte'): std::string ns3::RadioBearerStatsCalculator::GetUlPdcpOutputFilename() [member function]
cls.add_method('GetUlPdcpOutputFilename',
'std::string',
[])
## radio-bearer-stats-calculator.h (module 'lte'): std::vector<double, std::allocator<double> > ns3::RadioBearerStatsCalculator::GetUlPduSizeStats(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetUlPduSizeStats',
'std::vector< double >',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): uint64_t ns3::RadioBearerStatsCalculator::GetUlRxData(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetUlRxData',
'uint64_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): uint32_t ns3::RadioBearerStatsCalculator::GetUlRxPackets(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetUlRxPackets',
'uint32_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): uint64_t ns3::RadioBearerStatsCalculator::GetUlTxData(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetUlTxData',
'uint64_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): uint32_t ns3::RadioBearerStatsCalculator::GetUlTxPackets(uint64_t imsi, uint8_t lcid) [member function]
cls.add_method('GetUlTxPackets',
'uint32_t',
[param('uint64_t', 'imsi'), param('uint8_t', 'lcid')])
## radio-bearer-stats-calculator.h (module 'lte'): void ns3::RadioBearerStatsCalculator::SetDlPdcpOutputFilename(std::string outputFilename) [member function]
cls.add_method('SetDlPdcpOutputFilename',
'void',
[param('std::string', 'outputFilename')])
## radio-bearer-stats-calculator.h (module 'lte'): void ns3::RadioBearerStatsCalculator::SetUlPdcpOutputFilename(std::string outputFilename) [member function]
cls.add_method('SetUlPdcpOutputFilename',
'void',
[param('std::string', 'outputFilename')])
## radio-bearer-stats-calculator.h (module 'lte'): void ns3::RadioBearerStatsCalculator::UlRxPdu(uint16_t cellId, uint64_t imsi, uint16_t rnti, uint8_t lcid, uint32_t packetSize, uint64_t delay) [member function]
cls.add_method('UlRxPdu',
'void',
[param('uint16_t', 'cellId'), param('uint64_t', 'imsi'), param('uint16_t', 'rnti'), param('uint8_t', 'lcid'), param('uint32_t', 'packetSize'), param('uint64_t', 'delay')])
## radio-bearer-stats-calculator.h (module 'lte'): void ns3::RadioBearerStatsCalculator::UlTxPdu(uint64_t imsi, uint16_t rnti, uint8_t lcid, uint32_t packetSize) [member function]
cls.add_method('UlTxPdu',
'void',
[param('uint64_t', 'imsi'), param('uint16_t', 'rnti'), param('uint8_t', 'lcid'), param('uint32_t', 'packetSize')])
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_Ns3RemSpectrumPhy_methods(root_module, cls):
## rem-spectrum-phy.h (module 'lte'): ns3::RemSpectrumPhy::RemSpectrumPhy() [constructor]
cls.add_constructor([])
## rem-spectrum-phy.h (module 'lte'): void ns3::RemSpectrumPhy::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## rem-spectrum-phy.h (module 'lte'): static ns3::TypeId ns3::RemSpectrumPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## rem-spectrum-phy.h (module 'lte'): void ns3::RemSpectrumPhy::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::SpectrumChannel >', 'c')],
is_virtual=True)
## rem-spectrum-phy.h (module 'lte'): void ns3::RemSpectrumPhy::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function]
cls.add_method('SetMobility',
'void',
[param('ns3::Ptr< ns3::MobilityModel >', 'm')],
is_virtual=True)
## rem-spectrum-phy.h (module 'lte'): void ns3::RemSpectrumPhy::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'd')],
is_virtual=True)
## rem-spectrum-phy.h (module 'lte'): ns3::Ptr<ns3::MobilityModel> ns3::RemSpectrumPhy::GetMobility() [member function]
cls.add_method('GetMobility',
'ns3::Ptr< ns3::MobilityModel >',
[],
is_virtual=True)
## rem-spectrum-phy.h (module 'lte'): ns3::Ptr<ns3::NetDevice> ns3::RemSpectrumPhy::GetDevice() [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[],
is_virtual=True)
## rem-spectrum-phy.h (module 'lte'): ns3::Ptr<ns3::SpectrumModel const> ns3::RemSpectrumPhy::GetRxSpectrumModel() const [member function]
cls.add_method('GetRxSpectrumModel',
'ns3::Ptr< ns3::SpectrumModel const >',
[],
is_const=True, is_virtual=True)
## rem-spectrum-phy.h (module 'lte'): ns3::Ptr<ns3::AntennaModel> ns3::RemSpectrumPhy::GetRxAntenna() [member function]
cls.add_method('GetRxAntenna',
'ns3::Ptr< ns3::AntennaModel >',
[],
is_virtual=True)
## rem-spectrum-phy.h (module 'lte'): void ns3::RemSpectrumPhy::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function]
cls.add_method('StartRx',
'void',
[param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')],
is_virtual=True)
## rem-spectrum-phy.h (module 'lte'): void ns3::RemSpectrumPhy::SetRxSpectrumModel(ns3::Ptr<ns3::SpectrumModel const> m) [member function]
cls.add_method('SetRxSpectrumModel',
'void',
[param('ns3::Ptr< ns3::SpectrumModel const >', 'm')])
## rem-spectrum-phy.h (module 'lte'): double ns3::RemSpectrumPhy::GetSinr(double noisePower) [member function]
cls.add_method('GetSinr',
'double',
[param('double', 'noisePower')])
## rem-spectrum-phy.h (module 'lte'): void ns3::RemSpectrumPhy::Deactivate() [member function]
cls.add_method('Deactivate',
'void',
[])
## rem-spectrum-phy.h (module 'lte'): bool ns3::RemSpectrumPhy::IsActive() [member function]
cls.add_method('IsActive',
'bool',
[])
## rem-spectrum-phy.h (module 'lte'): void ns3::RemSpectrumPhy::Reset() [member function]
cls.add_method('Reset',
'void',
[])
return
def register_Ns3RrFfMacScheduler_methods(root_module, cls):
## rr-ff-mac-scheduler.h (module 'lte'): ns3::RrFfMacScheduler::RrFfMacScheduler(ns3::RrFfMacScheduler const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RrFfMacScheduler const &', 'arg0')])
## rr-ff-mac-scheduler.h (module 'lte'): ns3::RrFfMacScheduler::RrFfMacScheduler() [constructor]
cls.add_constructor([])
## rr-ff-mac-scheduler.h (module 'lte'): void ns3::RrFfMacScheduler::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## rr-ff-mac-scheduler.h (module 'lte'): ns3::FfMacCschedSapProvider * ns3::RrFfMacScheduler::GetFfMacCschedSapProvider() [member function]
cls.add_method('GetFfMacCschedSapProvider',
'ns3::FfMacCschedSapProvider *',
[],
is_virtual=True)
## rr-ff-mac-scheduler.h (module 'lte'): ns3::FfMacSchedSapProvider * ns3::RrFfMacScheduler::GetFfMacSchedSapProvider() [member function]
cls.add_method('GetFfMacSchedSapProvider',
'ns3::FfMacSchedSapProvider *',
[],
is_virtual=True)
## rr-ff-mac-scheduler.h (module 'lte'): static ns3::TypeId ns3::RrFfMacScheduler::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## rr-ff-mac-scheduler.h (module 'lte'): void ns3::RrFfMacScheduler::SetFfMacCschedSapUser(ns3::FfMacCschedSapUser * s) [member function]
cls.add_method('SetFfMacCschedSapUser',
'void',
[param('ns3::FfMacCschedSapUser *', 's')],
is_virtual=True)
## rr-ff-mac-scheduler.h (module 'lte'): void ns3::RrFfMacScheduler::SetFfMacSchedSapUser(ns3::FfMacSchedSapUser * s) [member function]
cls.add_method('SetFfMacSchedSapUser',
'void',
[param('ns3::FfMacSchedSapUser *', 's')],
is_virtual=True)
## rr-ff-mac-scheduler.h (module 'lte'): void ns3::RrFfMacScheduler::TransmissionModeConfigurationUpdate(uint16_t rnti, uint8_t txMode) [member function]
cls.add_method('TransmissionModeConfigurationUpdate',
'void',
[param('uint16_t', 'rnti'), param('uint8_t', 'txMode')])
return
def register_Ns3SpectrumChannel_methods(root_module, cls):
## spectrum-channel.h (module 'spectrum'): ns3::SpectrumChannel::SpectrumChannel() [constructor]
cls.add_constructor([])
## spectrum-channel.h (module 'spectrum'): ns3::SpectrumChannel::SpectrumChannel(ns3::SpectrumChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SpectrumChannel const &', 'arg0')])
## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::AddPropagationLossModel(ns3::Ptr<ns3::PropagationLossModel> loss) [member function]
cls.add_method('AddPropagationLossModel',
'void',
[param('ns3::Ptr< ns3::PropagationLossModel >', 'loss')],
is_pure_virtual=True, is_virtual=True)
## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::AddRx(ns3::Ptr<ns3::SpectrumPhy> phy) [member function]
cls.add_method('AddRx',
'void',
[param('ns3::Ptr< ns3::SpectrumPhy >', 'phy')],
is_pure_virtual=True, is_virtual=True)
## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::AddSpectrumPropagationLossModel(ns3::Ptr<ns3::SpectrumPropagationLossModel> loss) [member function]
cls.add_method('AddSpectrumPropagationLossModel',
'void',
[param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'loss')],
is_pure_virtual=True, is_virtual=True)
## spectrum-channel.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::SetPropagationDelayModel(ns3::Ptr<ns3::PropagationDelayModel> delay) [member function]
cls.add_method('SetPropagationDelayModel',
'void',
[param('ns3::Ptr< ns3::PropagationDelayModel >', 'delay')],
is_pure_virtual=True, is_virtual=True)
## spectrum-channel.h (module 'spectrum'): void ns3::SpectrumChannel::StartTx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function]
cls.add_method('StartTx',
'void',
[param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3StringChecker_methods(root_module, cls):
## string.h (module 'core'): ns3::StringChecker::StringChecker() [constructor]
cls.add_constructor([])
## string.h (module 'core'): ns3::StringChecker::StringChecker(ns3::StringChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StringChecker const &', 'arg0')])
return
def register_Ns3StringValue_methods(root_module, cls):
## string.h (module 'core'): ns3::StringValue::StringValue() [constructor]
cls.add_constructor([])
## string.h (module 'core'): ns3::StringValue::StringValue(ns3::StringValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StringValue const &', 'arg0')])
## string.h (module 'core'): ns3::StringValue::StringValue(std::string const & value) [constructor]
cls.add_constructor([param('std::string const &', 'value')])
## string.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::StringValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## string.h (module 'core'): bool ns3::StringValue::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)
## string.h (module 'core'): std::string ns3::StringValue::Get() const [member function]
cls.add_method('Get',
'std::string',
[],
is_const=True)
## string.h (module 'core'): std::string ns3::StringValue::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)
## string.h (module 'core'): void ns3::StringValue::Set(std::string const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string const &', 'value')])
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_Ns3UlDciIdealControlMessage_methods(root_module, cls):
## ideal-control-messages.h (module 'lte'): ns3::UlDciIdealControlMessage::UlDciIdealControlMessage(ns3::UlDciIdealControlMessage const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UlDciIdealControlMessage const &', 'arg0')])
## ideal-control-messages.h (module 'lte'): ns3::UlDciIdealControlMessage::UlDciIdealControlMessage() [constructor]
cls.add_constructor([])
## ideal-control-messages.h (module 'lte'): UlDciListElement_s ns3::UlDciIdealControlMessage::GetDci() [member function]
cls.add_method('GetDci',
'UlDciListElement_s',
[])
## ideal-control-messages.h (module 'lte'): void ns3::UlDciIdealControlMessage::SetDci(UlDciListElement_s dci) [member function]
cls.add_method('SetDci',
'void',
[param('UlDciListElement_s', 'dci')])
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_Ns3VirtualNetDevice_methods(root_module, cls):
## virtual-net-device.h (module 'virtual-net-device'): ns3::VirtualNetDevice::VirtualNetDevice(ns3::VirtualNetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::VirtualNetDevice const &', 'arg0')])
## virtual-net-device.h (module 'virtual-net-device'): ns3::VirtualNetDevice::VirtualNetDevice() [constructor]
cls.add_constructor([])
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::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)
## virtual-net-device.h (module 'virtual-net-device'): ns3::Address ns3::VirtualNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): ns3::Address ns3::VirtualNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): ns3::Ptr<ns3::Channel> ns3::VirtualNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): uint32_t ns3::VirtualNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): uint16_t ns3::VirtualNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): ns3::Address ns3::VirtualNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): ns3::Address ns3::VirtualNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): ns3::Ptr<ns3::Node> ns3::VirtualNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): static ns3::TypeId ns3::VirtualNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::Receive(ns3::Ptr<ns3::Packet> packet, uint16_t protocol, ns3::Address const & source, ns3::Address const & destination, ns3::NetDevice::PacketType packetType) [member function]
cls.add_method('Receive',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'destination'), param('ns3::NetDevice::PacketType', 'packetType')])
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::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)
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::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)
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::SetIsPointToPoint(bool isPointToPoint) [member function]
cls.add_method('SetIsPointToPoint',
'void',
[param('bool', 'isPointToPoint')])
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::SetNeedsArp(bool needsArp) [member function]
cls.add_method('SetNeedsArp',
'void',
[param('bool', 'needsArp')])
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::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)
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::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)
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::SetSendCallback(ns3::Callback<bool, ns3::Ptr<ns3::Packet>, ns3::Address const&, ns3::Address const&, unsigned short, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> transmitCb) [member function]
cls.add_method('SetSendCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::Address const &, ns3::Address const &, unsigned short, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'transmitCb')])
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::SetSupportsSendFrom(bool supportsSendFrom) [member function]
cls.add_method('SetSupportsSendFrom',
'void',
[param('bool', 'supportsSendFrom')])
## virtual-net-device.h (module 'virtual-net-device'): bool ns3::VirtualNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## virtual-net-device.h (module 'virtual-net-device'): void ns3::VirtualNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3AddressChecker_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')])
return
def register_Ns3AddressValue_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressValue const &', 'arg0')])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor]
cls.add_constructor([param('ns3::Address const &', 'value')])
## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Address',
[],
is_const=True)
## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Address const &', 'value')])
return
def register_Ns3BsrIdealControlMessage_methods(root_module, cls):
## ideal-control-messages.h (module 'lte'): ns3::BsrIdealControlMessage::BsrIdealControlMessage(ns3::BsrIdealControlMessage const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BsrIdealControlMessage const &', 'arg0')])
## ideal-control-messages.h (module 'lte'): ns3::BsrIdealControlMessage::BsrIdealControlMessage() [constructor]
cls.add_constructor([])
## ideal-control-messages.h (module 'lte'): MacCeListElement_s ns3::BsrIdealControlMessage::GetBsr() [member function]
cls.add_method('GetBsr',
'MacCeListElement_s',
[])
## ideal-control-messages.h (module 'lte'): void ns3::BsrIdealControlMessage::SetBsr(MacCeListElement_s ulcqi) [member function]
cls.add_method('SetBsr',
'void',
[param('MacCeListElement_s', 'ulcqi')])
return
def register_Ns3DlCqiIdealControlMessage_methods(root_module, cls):
## ideal-control-messages.h (module 'lte'): ns3::DlCqiIdealControlMessage::DlCqiIdealControlMessage(ns3::DlCqiIdealControlMessage const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DlCqiIdealControlMessage const &', 'arg0')])
## ideal-control-messages.h (module 'lte'): ns3::DlCqiIdealControlMessage::DlCqiIdealControlMessage() [constructor]
cls.add_constructor([])
## ideal-control-messages.h (module 'lte'): CqiListElement_s ns3::DlCqiIdealControlMessage::GetDlCqi() [member function]
cls.add_method('GetDlCqi',
'CqiListElement_s',
[])
## ideal-control-messages.h (module 'lte'): void ns3::DlCqiIdealControlMessage::SetDlCqi(CqiListElement_s dlcqi) [member function]
cls.add_method('SetDlCqi',
'void',
[param('CqiListElement_s', 'dlcqi')])
return
def register_Ns3DlDciIdealControlMessage_methods(root_module, cls):
## ideal-control-messages.h (module 'lte'): ns3::DlDciIdealControlMessage::DlDciIdealControlMessage(ns3::DlDciIdealControlMessage const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DlDciIdealControlMessage const &', 'arg0')])
## ideal-control-messages.h (module 'lte'): ns3::DlDciIdealControlMessage::DlDciIdealControlMessage() [constructor]
cls.add_constructor([])
## ideal-control-messages.h (module 'lte'): DlDciListElement_s ns3::DlDciIdealControlMessage::GetDci() [member function]
cls.add_method('GetDci',
'DlDciListElement_s',
[])
## ideal-control-messages.h (module 'lte'): void ns3::DlDciIdealControlMessage::SetDci(DlDciListElement_s dci) [member function]
cls.add_method('SetDci',
'void',
[param('DlDciListElement_s', 'dci')])
return
def register_Ns3LteCqiSinrChunkProcessor_methods(root_module, cls):
## lte-sinr-chunk-processor.h (module 'lte'): ns3::LteCqiSinrChunkProcessor::LteCqiSinrChunkProcessor(ns3::LteCqiSinrChunkProcessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteCqiSinrChunkProcessor const &', 'arg0')])
## lte-sinr-chunk-processor.h (module 'lte'): ns3::LteCqiSinrChunkProcessor::LteCqiSinrChunkProcessor(ns3::Ptr<ns3::LtePhy> p) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::LtePhy >', 'p')])
## lte-sinr-chunk-processor.h (module 'lte'): void ns3::LteCqiSinrChunkProcessor::End() [member function]
cls.add_method('End',
'void',
[],
is_virtual=True)
## lte-sinr-chunk-processor.h (module 'lte'): void ns3::LteCqiSinrChunkProcessor::EvaluateSinrChunk(ns3::SpectrumValue const & sinr, ns3::Time duration) [member function]
cls.add_method('EvaluateSinrChunk',
'void',
[param('ns3::SpectrumValue const &', 'sinr'), param('ns3::Time', 'duration')],
is_virtual=True)
## lte-sinr-chunk-processor.h (module 'lte'): void ns3::LteCqiSinrChunkProcessor::Start() [member function]
cls.add_method('Start',
'void',
[],
is_virtual=True)
return
def register_Ns3LteEnbPhy_methods(root_module, cls):
## lte-enb-phy.h (module 'lte'): ns3::LteEnbPhy::LteEnbPhy(ns3::LteEnbPhy const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LteEnbPhy const &', 'arg0')])
## lte-enb-phy.h (module 'lte'): ns3::LteEnbPhy::LteEnbPhy() [constructor]
cls.add_constructor([])
## lte-enb-phy.h (module 'lte'): ns3::LteEnbPhy::LteEnbPhy(ns3::Ptr<ns3::LteSpectrumPhy> dlPhy, ns3::Ptr<ns3::LteSpectrumPhy> ulPhy) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::LteSpectrumPhy >', 'dlPhy'), param('ns3::Ptr< ns3::LteSpectrumPhy >', 'ulPhy')])
## lte-enb-phy.h (module 'lte'): bool ns3::LteEnbPhy::AddUePhy(uint16_t rnti, ns3::Ptr<ns3::LteUePhy> phy) [member function]
cls.add_method('AddUePhy',
'bool',
[param('uint16_t', 'rnti'), param('ns3::Ptr< ns3::LteUePhy >', 'phy')])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::CalcChannelQualityForUe(std::vector<double, std::allocator<double> > sinr, ns3::Ptr<ns3::LteSpectrumPhy> ue) [member function]
cls.add_method('CalcChannelQualityForUe',
'void',
[param('std::vector< double >', 'sinr'), param('ns3::Ptr< ns3::LteSpectrumPhy >', 'ue')])
## lte-enb-phy.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::LteEnbPhy::CreateTxPowerSpectralDensity() [member function]
cls.add_method('CreateTxPowerSpectralDensity',
'ns3::Ptr< ns3::SpectrumValue >',
[],
is_virtual=True)
## lte-enb-phy.h (module 'lte'): UlCqi_s ns3::LteEnbPhy::CreateUlCqiReport(ns3::SpectrumValue const & sinr) [member function]
cls.add_method('CreateUlCqiReport',
'UlCqi_s',
[param('ns3::SpectrumValue const &', 'sinr')])
## lte-enb-phy.h (module 'lte'): bool ns3::LteEnbPhy::DeleteUePhy(uint16_t rnti) [member function]
cls.add_method('DeleteUePhy',
'bool',
[param('uint16_t', 'rnti')])
## lte-enb-phy.h (module 'lte'): std::list<ns3::UlDciIdealControlMessage,std::allocator<ns3::UlDciIdealControlMessage> > ns3::LteEnbPhy::DequeueUlDci() [member function]
cls.add_method('DequeueUlDci',
'std::list< ns3::UlDciIdealControlMessage >',
[])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-enb-phy.h (module 'lte'): uint8_t ns3::LteEnbPhy::DoGetMacChTtiDelay() [member function]
cls.add_method('DoGetMacChTtiDelay',
'uint8_t',
[],
is_virtual=True)
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::DoSendIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('DoSendIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::DoSendMacPdu(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoSendMacPdu',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')],
is_virtual=True)
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::DoSetDownlinkSubChannels() [member function]
cls.add_method('DoSetDownlinkSubChannels',
'void',
[],
is_virtual=True)
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::DoSetTransmissionMode(uint16_t rnti, uint8_t txMode) [member function]
cls.add_method('DoSetTransmissionMode',
'void',
[param('uint16_t', 'rnti'), param('uint8_t', 'txMode')],
is_virtual=True)
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
is_virtual=True)
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::EndFrame() [member function]
cls.add_method('EndFrame',
'void',
[])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::EndSubFrame() [member function]
cls.add_method('EndSubFrame',
'void',
[])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::GenerateCqiReport(ns3::SpectrumValue const & sinr) [member function]
cls.add_method('GenerateCqiReport',
'void',
[param('ns3::SpectrumValue const &', 'sinr')],
is_virtual=True)
## lte-enb-phy.h (module 'lte'): ns3::LteEnbPhySapProvider * ns3::LteEnbPhy::GetLteEnbPhySapProvider() [member function]
cls.add_method('GetLteEnbPhySapProvider',
'ns3::LteEnbPhySapProvider *',
[])
## lte-enb-phy.h (module 'lte'): uint8_t ns3::LteEnbPhy::GetMacChDelay() const [member function]
cls.add_method('GetMacChDelay',
'uint8_t',
[],
is_const=True)
## lte-enb-phy.h (module 'lte'): double ns3::LteEnbPhy::GetNoiseFigure() const [member function]
cls.add_method('GetNoiseFigure',
'double',
[],
is_const=True)
## lte-enb-phy.h (module 'lte'): double ns3::LteEnbPhy::GetTxPower() const [member function]
cls.add_method('GetTxPower',
'double',
[],
is_const=True)
## lte-enb-phy.h (module 'lte'): static ns3::TypeId ns3::LteEnbPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::PhyPduReceived(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('PhyPduReceived',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::QueueUlDci(ns3::UlDciIdealControlMessage m) [member function]
cls.add_method('QueueUlDci',
'void',
[param('ns3::UlDciIdealControlMessage', 'm')])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::ReceiveIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function]
cls.add_method('ReceiveIdealControlMessage',
'void',
[param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')],
is_virtual=True)
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::SetLteEnbPhySapUser(ns3::LteEnbPhySapUser * s) [member function]
cls.add_method('SetLteEnbPhySapUser',
'void',
[param('ns3::LteEnbPhySapUser *', 's')])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::SetMacChDelay(uint8_t delay) [member function]
cls.add_method('SetMacChDelay',
'void',
[param('uint8_t', 'delay')])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::SetNoiseFigure(double pow) [member function]
cls.add_method('SetNoiseFigure',
'void',
[param('double', 'pow')])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::SetTxPower(double pow) [member function]
cls.add_method('SetTxPower',
'void',
[param('double', 'pow')])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::StartFrame() [member function]
cls.add_method('StartFrame',
'void',
[])
## lte-enb-phy.h (module 'lte'): void ns3::LteEnbPhy::StartSubFrame() [member function]
cls.add_method('StartSubFrame',
'void',
[])
return
def register_Ns3LteNetDevice_methods(root_module, cls):
## lte-net-device.h (module 'lte'): static ns3::TypeId ns3::LteNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-net-device.h (module 'lte'): ns3::LteNetDevice::LteNetDevice() [constructor]
cls.add_constructor([])
## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## lte-net-device.h (module 'lte'): uint32_t ns3::LteNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): ns3::Ptr<ns3::Channel> ns3::LteNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## lte-net-device.h (module 'lte'): uint16_t ns3::LteNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## lte-net-device.h (module 'lte'): ns3::Address ns3::LteNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::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)
## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): ns3::Address ns3::LteNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): ns3::Ptr<ns3::Node> ns3::LteNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::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)
## lte-net-device.h (module 'lte'): ns3::Address ns3::LteNetDevice::GetMulticast(ns3::Ipv4Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'addr')],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): ns3::Address ns3::LteNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::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)
## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::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)
## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::Receive(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p')])
return
def register_Ns3LtePemSinrChunkProcessor_methods(root_module, cls):
## lte-sinr-chunk-processor.h (module 'lte'): ns3::LtePemSinrChunkProcessor::LtePemSinrChunkProcessor(ns3::LtePemSinrChunkProcessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LtePemSinrChunkProcessor const &', 'arg0')])
## lte-sinr-chunk-processor.h (module 'lte'): ns3::LtePemSinrChunkProcessor::LtePemSinrChunkProcessor(ns3::Ptr<ns3::LteSpectrumPhy> p) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::LteSpectrumPhy >', 'p')])
## lte-sinr-chunk-processor.h (module 'lte'): void ns3::LtePemSinrChunkProcessor::End() [member function]
cls.add_method('End',
'void',
[],
is_virtual=True)
## lte-sinr-chunk-processor.h (module 'lte'): void ns3::LtePemSinrChunkProcessor::EvaluateSinrChunk(ns3::SpectrumValue const & sinr, ns3::Time duration) [member function]
cls.add_method('EvaluateSinrChunk',
'void',
[param('ns3::SpectrumValue const &', 'sinr'), param('ns3::Time', 'duration')],
is_virtual=True)
## lte-sinr-chunk-processor.h (module 'lte'): void ns3::LtePemSinrChunkProcessor::Start() [member function]
cls.add_method('Start',
'void',
[],
is_virtual=True)
return
def register_Ns3LteUeNetDevice_methods(root_module, cls):
## lte-ue-net-device.h (module 'lte'): static ns3::TypeId ns3::LteUeNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-ue-net-device.h (module 'lte'): ns3::LteUeNetDevice::LteUeNetDevice() [constructor]
cls.add_constructor([])
## lte-ue-net-device.h (module 'lte'): ns3::LteUeNetDevice::LteUeNetDevice(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::LteUePhy> phy, ns3::Ptr<ns3::LteUeMac> mac, ns3::Ptr<ns3::LteUeRrc> rrc) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::LteUePhy >', 'phy'), param('ns3::Ptr< ns3::LteUeMac >', 'mac'), param('ns3::Ptr< ns3::LteUeRrc >', 'rrc')])
## lte-ue-net-device.h (module 'lte'): void ns3::LteUeNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-ue-net-device.h (module 'lte'): bool ns3::LteUeNetDevice::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)
## lte-ue-net-device.h (module 'lte'): ns3::Ptr<ns3::LteUeMac> ns3::LteUeNetDevice::GetMac() [member function]
cls.add_method('GetMac',
'ns3::Ptr< ns3::LteUeMac >',
[])
## lte-ue-net-device.h (module 'lte'): ns3::Ptr<ns3::LteUeRrc> ns3::LteUeNetDevice::GetRrc() [member function]
cls.add_method('GetRrc',
'ns3::Ptr< ns3::LteUeRrc >',
[])
## lte-ue-net-device.h (module 'lte'): ns3::Ptr<ns3::LteUePhy> ns3::LteUeNetDevice::GetPhy() const [member function]
cls.add_method('GetPhy',
'ns3::Ptr< ns3::LteUePhy >',
[],
is_const=True)
## lte-ue-net-device.h (module 'lte'): void ns3::LteUeNetDevice::SetTargetEnb(ns3::Ptr<ns3::LteEnbNetDevice> enb) [member function]
cls.add_method('SetTargetEnb',
'void',
[param('ns3::Ptr< ns3::LteEnbNetDevice >', 'enb')])
## lte-ue-net-device.h (module 'lte'): ns3::Ptr<ns3::LteEnbNetDevice> ns3::LteUeNetDevice::GetTargetEnb() [member function]
cls.add_method('GetTargetEnb',
'ns3::Ptr< ns3::LteEnbNetDevice >',
[])
## lte-ue-net-device.h (module 'lte'): uint64_t ns3::LteUeNetDevice::GetImsi() [member function]
cls.add_method('GetImsi',
'uint64_t',
[])
## lte-ue-net-device.h (module 'lte'): void ns3::LteUeNetDevice::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3LteEnbNetDevice_methods(root_module, cls):
## lte-enb-net-device.h (module 'lte'): static ns3::TypeId ns3::LteEnbNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## lte-enb-net-device.h (module 'lte'): ns3::LteEnbNetDevice::LteEnbNetDevice() [constructor]
cls.add_constructor([])
## lte-enb-net-device.h (module 'lte'): void ns3::LteEnbNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## lte-enb-net-device.h (module 'lte'): bool ns3::LteEnbNetDevice::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)
## lte-enb-net-device.h (module 'lte'): ns3::Ptr<ns3::LteEnbMac> ns3::LteEnbNetDevice::GetMac() const [member function]
cls.add_method('GetMac',
'ns3::Ptr< ns3::LteEnbMac >',
[],
is_const=True)
## lte-enb-net-device.h (module 'lte'): ns3::Ptr<ns3::LteEnbPhy> ns3::LteEnbNetDevice::GetPhy() const [member function]
cls.add_method('GetPhy',
'ns3::Ptr< ns3::LteEnbPhy >',
[],
is_const=True)
## lte-enb-net-device.h (module 'lte'): ns3::Ptr<ns3::LteEnbRrc> ns3::LteEnbNetDevice::GetRrc() const [member function]
cls.add_method('GetRrc',
'ns3::Ptr< ns3::LteEnbRrc >',
[],
is_const=True)
## lte-enb-net-device.h (module 'lte'): uint16_t ns3::LteEnbNetDevice::GetCellId() const [member function]
cls.add_method('GetCellId',
'uint16_t',
[],
is_const=True)
## lte-enb-net-device.h (module 'lte'): uint8_t ns3::LteEnbNetDevice::GetUlBandwidth() const [member function]
cls.add_method('GetUlBandwidth',
'uint8_t',
[],
is_const=True)
## lte-enb-net-device.h (module 'lte'): void ns3::LteEnbNetDevice::SetUlBandwidth(uint8_t bw) [member function]
cls.add_method('SetUlBandwidth',
'void',
[param('uint8_t', 'bw')])
## lte-enb-net-device.h (module 'lte'): uint8_t ns3::LteEnbNetDevice::GetDlBandwidth() const [member function]
cls.add_method('GetDlBandwidth',
'uint8_t',
[],
is_const=True)
## lte-enb-net-device.h (module 'lte'): void ns3::LteEnbNetDevice::SetDlBandwidth(uint8_t bw) [member function]
cls.add_method('SetDlBandwidth',
'void',
[param('uint8_t', 'bw')])
## lte-enb-net-device.h (module 'lte'): uint16_t ns3::LteEnbNetDevice::GetDlEarfcn() const [member function]
cls.add_method('GetDlEarfcn',
'uint16_t',
[],
is_const=True)
## lte-enb-net-device.h (module 'lte'): void ns3::LteEnbNetDevice::SetDlEarfcn(uint16_t earfcn) [member function]
cls.add_method('SetDlEarfcn',
'void',
[param('uint16_t', 'earfcn')])
## lte-enb-net-device.h (module 'lte'): uint16_t ns3::LteEnbNetDevice::GetUlEarfcn() const [member function]
cls.add_method('GetUlEarfcn',
'uint16_t',
[],
is_const=True)
## lte-enb-net-device.h (module 'lte'): void ns3::LteEnbNetDevice::SetUlEarfcn(uint16_t earfcn) [member function]
cls.add_method('SetUlEarfcn',
'void',
[param('uint16_t', 'earfcn')])
## lte-enb-net-device.h (module 'lte'): void ns3::LteEnbNetDevice::DoStart() [member function]
cls.add_method('DoStart',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ConfigMatchContainer_methods(root_module, cls):
## config.h (module 'core'): ns3::Config::MatchContainer::MatchContainer(ns3::Config::MatchContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Config::MatchContainer const &', 'arg0')])
## config.h (module 'core'): ns3::Config::MatchContainer::MatchContainer() [constructor]
cls.add_constructor([])
## config.h (module 'core'): ns3::Config::MatchContainer::MatchContainer(std::vector<ns3::Ptr<ns3::Object>, std::allocator<ns3::Ptr<ns3::Object> > > const & objects, std::vector<std::string, std::allocator<std::string> > const & contexts, std::string path) [constructor]
cls.add_constructor([param('std::vector< ns3::Ptr< ns3::Object > > const &', 'objects'), param('std::vector< std::string > const &', 'contexts'), param('std::string', 'path')])
## config.h (module 'core'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Object>*,std::vector<ns3::Ptr<ns3::Object>, std::allocator<ns3::Ptr<ns3::Object> > > > ns3::Config::MatchContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Object > const, std::vector< ns3::Ptr< ns3::Object > > >',
[],
is_const=True)
## config.h (module 'core'): void ns3::Config::MatchContainer::Connect(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('Connect',
'void',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): void ns3::Config::MatchContainer::ConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('ConnectWithoutContext',
'void',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): void ns3::Config::MatchContainer::Disconnect(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('Disconnect',
'void',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): void ns3::Config::MatchContainer::DisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('DisconnectWithoutContext',
'void',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## config.h (module 'core'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Object>*,std::vector<ns3::Ptr<ns3::Object>, std::allocator<ns3::Ptr<ns3::Object> > > > ns3::Config::MatchContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Object > const, std::vector< ns3::Ptr< ns3::Object > > >',
[],
is_const=True)
## config.h (module 'core'): ns3::Ptr<ns3::Object> ns3::Config::MatchContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Object >',
[param('uint32_t', 'i')],
is_const=True)
## config.h (module 'core'): std::string ns3::Config::MatchContainer::GetMatchedPath(uint32_t i) const [member function]
cls.add_method('GetMatchedPath',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## config.h (module 'core'): uint32_t ns3::Config::MatchContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## config.h (module 'core'): std::string ns3::Config::MatchContainer::GetPath() const [member function]
cls.add_method('GetPath',
'std::string',
[],
is_const=True)
## config.h (module 'core'): void ns3::Config::MatchContainer::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_functions(root_module):
module = root_module
register_functions_ns3_Config(module.get_submodule('Config'), root_module)
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_Config(module, 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 | 5,235,231,210,830,579,000 | 66.153057 | 426 | 0.62755 | false |
JunyaKaneko/pys3client | s3client/path.py | 1 | 1508 | import os
import botocore
import s3client
__author__ = 'Junya Kaneko <[email protected]>'
def abspath(path, root_delimiter=True):
path = os.path.normpath(os.path.join(s3client.getcwd(), path))
if root_delimiter:
return path
else:
return path[1:]
def join(path, *paths):
return os.path.join(path, *paths)
def kind(path):
path = abspath(path)
if path == '/':
try:
s3client._s3.meta.client.head_bucket(Bucket=s3client._conf['bucket'])
except botocore.exceptions.ClientError as e:
error_code = int(e.response['Error']['Code'])
if error_code == 404:
raise FileNotFoundError
return 'dir'
path = path[1:]
try:
s3client._s3.Object(s3client._conf['bucket'], path).load()
except botocore.exceptions.ClientError as e:
keys = s3client._bucket.objects.filter(MaxKeys=1, Prefix=path + '/')
if sum(1 for _ in keys):
return 'dir'
else:
raise FileNotFoundError(path)
return 'file'
def exists(path):
try:
kind(path)
return True
except FileNotFoundError:
return False
def isdir(path):
if kind(path) == 'dir':
return True
else:
return False
def isfile(path):
if kind(path) == 'file':
return True
else:
return False
def basename(path):
return os.path.basename(path)
def dirname(path):
return os.path.dirname(path)
| mit | 7,217,153,023,544,114,000 | 19.657534 | 81 | 0.584218 | false |
mhnatiuk/phd_sociology_of_religion | scrapper/build/cryptography/tests/hazmat/primitives/test_rsa.py | 1 | 57075 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import binascii
import itertools
import math
import os
import pytest
from cryptography import utils
from cryptography.exceptions import (
AlreadyFinalized, InvalidSignature, _Reasons
)
from cryptography.hazmat.backends.interfaces import RSABackend
from cryptography.hazmat.primitives import hashes, interfaces
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.asymmetric.rsa import (
RSAPrivateNumbers, RSAPublicNumbers
)
from .fixtures_rsa import (
RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027, RSA_KEY_1028,
RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031, RSA_KEY_1536, RSA_KEY_2048,
RSA_KEY_512, RSA_KEY_512_ALT, RSA_KEY_522, RSA_KEY_599, RSA_KEY_745,
RSA_KEY_768,
)
from .utils import (
_check_rsa_private_numbers, generate_rsa_verification_test
)
from ...utils import (
load_pkcs1_vectors, load_rsa_nist_vectors, load_vectors_from_file,
raises_unsupported_algorithm
)
@utils.register_interface(interfaces.AsymmetricPadding)
class DummyPadding(object):
name = "UNSUPPORTED-PADDING"
class DummyMGF(object):
_salt_length = 0
def _flatten_pkcs1_examples(vectors):
flattened_vectors = []
for vector in vectors:
examples = vector[0].pop("examples")
for example in examples:
merged_vector = (vector[0], vector[1], example)
flattened_vectors.append(merged_vector)
return flattened_vectors
def test_modular_inverse():
p = int(
"d1f9f6c09fd3d38987f7970247b85a6da84907753d42ec52bc23b745093f4fff5cff3"
"617ce43d00121a9accc0051f519c76e08cf02fc18acfe4c9e6aea18da470a2b611d2e"
"56a7b35caa2c0239bc041a53cc5875ca0b668ae6377d4b23e932d8c995fd1e58ecfd8"
"c4b73259c0d8a54d691cca3f6fb85c8a5c1baf588e898d481", 16
)
q = int(
"d1519255eb8f678c86cfd06802d1fbef8b664441ac46b73d33d13a8404580a33a8e74"
"cb2ea2e2963125b3d454d7a922cef24dd13e55f989cbabf64255a736671f4629a47b5"
"b2347cfcd669133088d1c159518531025297c2d67c9da856a12e80222cd03b4c6ec0f"
"86c957cb7bb8de7a127b645ec9e820aa94581e4762e209f01", 16
)
assert rsa._modinv(q, p) == int(
"0275e06afa722999315f8f322275483e15e2fb46d827b17800f99110b269a6732748f"
"624a382fa2ed1ec68c99f7fc56fb60e76eea51614881f497ba7034c17dde955f92f15"
"772f8b2b41f3e56d88b1e096cdd293eba4eae1e82db815e0fadea0c4ec971bc6fd875"
"c20e67e48c31a611e98d32c6213ae4c4d7b53023b2f80c538", 16
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSA(object):
@pytest.mark.parametrize(
("public_exponent", "key_size"),
itertools.product(
(3, 5, 65537),
(1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1536, 2048)
)
)
def test_generate_rsa_keys(self, backend, public_exponent, key_size):
skey = rsa.generate_private_key(public_exponent, key_size, backend)
assert skey.key_size == key_size
if isinstance(skey, interfaces.RSAPrivateKeyWithNumbers):
_check_rsa_private_numbers(skey.private_numbers())
pkey = skey.public_key()
assert isinstance(pkey.public_numbers(), rsa.RSAPublicNumbers)
def test_generate_bad_public_exponent(self, backend):
with pytest.raises(ValueError):
rsa.generate_private_key(public_exponent=1,
key_size=2048,
backend=backend)
with pytest.raises(ValueError):
rsa.generate_private_key(public_exponent=4,
key_size=2048,
backend=backend)
def test_cant_generate_insecure_tiny_key(self, backend):
with pytest.raises(ValueError):
rsa.generate_private_key(public_exponent=65537,
key_size=511,
backend=backend)
with pytest.raises(ValueError):
rsa.generate_private_key(public_exponent=65537,
key_size=256,
backend=backend)
@pytest.mark.parametrize(
"pkcs1_example",
load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"),
load_pkcs1_vectors
)
)
def test_load_pss_vect_example_keys(self, pkcs1_example):
secret, public = pkcs1_example
private_num = rsa.RSAPrivateNumbers(
p=secret["p"],
q=secret["q"],
d=secret["private_exponent"],
dmp1=secret["dmp1"],
dmq1=secret["dmq1"],
iqmp=secret["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
e=secret["public_exponent"],
n=secret["modulus"]
)
)
_check_rsa_private_numbers(private_num)
public_num = rsa.RSAPublicNumbers(
e=public["public_exponent"],
n=public["modulus"]
)
assert public_num
public_num2 = private_num.public_numbers
assert public_num2
assert public_num.n == public_num2.n
assert public_num.e == public_num2.e
def test_rsa_generate_invalid_backend():
pretend_backend = object()
with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE):
rsa.generate_private_key(65537, 2048, pretend_backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSASignature(object):
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
@pytest.mark.parametrize(
"pkcs1_example",
_flatten_pkcs1_examples(load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs1v15sign-vectors.txt"),
load_pkcs1_vectors
))
)
def test_pkcs1v15_signing(self, pkcs1_example, backend):
private, public, example = pkcs1_example
private_key = rsa.RSAPrivateNumbers(
p=private["p"],
q=private["q"],
d=private["private_exponent"],
dmp1=private["dmp1"],
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
e=private["public_exponent"],
n=private["modulus"]
)
).private_key(backend)
signer = private_key.signer(padding.PKCS1v15(), hashes.SHA1())
signer.update(binascii.unhexlify(example["message"]))
signature = signer.finalize()
assert binascii.hexlify(signature) == example["signature"]
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS."
)
@pytest.mark.parametrize(
"pkcs1_example",
_flatten_pkcs1_examples(load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"),
load_pkcs1_vectors
))
)
def test_pss_signing(self, pkcs1_example, backend):
private, public, example = pkcs1_example
private_key = rsa.RSAPrivateNumbers(
p=private["p"],
q=private["q"],
d=private["private_exponent"],
dmp1=private["dmp1"],
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
e=private["public_exponent"],
n=private["modulus"]
)
).private_key(backend)
public_key = rsa.RSAPublicNumbers(
e=public["public_exponent"],
n=public["modulus"]
).public_key(backend)
signer = private_key.signer(
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA1()
)
signer.update(binascii.unhexlify(example["message"]))
signature = signer.finalize()
assert len(signature) == math.ceil(private_key.key_size / 8.0)
# PSS signatures contain randomness so we can't do an exact
# signature check. Instead we'll verify that the signature created
# successfully verifies.
verifier = public_key.verifier(
signature,
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA1(),
)
verifier.update(binascii.unhexlify(example["message"]))
verifier.verify()
@pytest.mark.parametrize(
"hash_alg",
[hashes.SHA224(), hashes.SHA256(), hashes.SHA384(), hashes.SHA512()]
)
def test_pss_signing_sha2(self, hash_alg, backend):
if not backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hash_alg),
salt_length=padding.PSS.MAX_LENGTH
)
):
pytest.skip(
"Does not support {0} in MGF1 using PSS.".format(hash_alg.name)
)
private_key = RSA_KEY_768.private_key(backend)
public_key = private_key.public_key()
pss = padding.PSS(
mgf=padding.MGF1(hash_alg),
salt_length=padding.PSS.MAX_LENGTH
)
signer = private_key.signer(pss, hash_alg)
signer.update(b"testing signature")
signature = signer.finalize()
verifier = public_key.verifier(signature, pss, hash_alg)
verifier.update(b"testing signature")
verifier.verify()
@pytest.mark.supported(
only_if=lambda backend: (
backend.hash_supported(hashes.SHA512()) and
backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
)
),
skip_message="Does not support SHA512."
)
def test_pss_minimum_key_size_for_digest(self, backend):
private_key = RSA_KEY_522.private_key(backend)
signer = private_key.signer(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA512()
)
signer.update(b"no failure")
signer.finalize()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS."
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA512()),
skip_message="Does not support SHA512."
)
def test_pss_signing_digest_too_large_for_key_size(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with pytest.raises(ValueError):
private_key.signer(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA512()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS."
)
def test_pss_signing_salt_length_too_long(self, backend):
private_key = RSA_KEY_512.private_key(backend)
signer = private_key.signer(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=1000000
),
hashes.SHA1()
)
signer.update(b"failure coming")
with pytest.raises(ValueError):
signer.finalize()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
def test_use_after_finalize(self, backend):
private_key = RSA_KEY_512.private_key(backend)
signer = private_key.signer(padding.PKCS1v15(), hashes.SHA1())
signer.update(b"sign me")
signer.finalize()
with pytest.raises(AlreadyFinalized):
signer.finalize()
with pytest.raises(AlreadyFinalized):
signer.update(b"more data")
def test_unsupported_padding(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
private_key.signer(DummyPadding(), hashes.SHA1())
def test_padding_incorrect_type(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with pytest.raises(TypeError):
private_key.signer("notpadding", hashes.SHA1())
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
skip_message="Does not support PSS."
)
def test_unsupported_pss_mgf(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_MGF):
private_key.signer(
padding.PSS(
mgf=DummyMGF(),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA1()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
def test_pkcs1_digest_too_large_for_key_size(self, backend):
private_key = RSA_KEY_599.private_key(backend)
signer = private_key.signer(
padding.PKCS1v15(),
hashes.SHA512()
)
signer.update(b"failure coming")
with pytest.raises(ValueError):
signer.finalize()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
def test_pkcs1_minimum_key_size(self, backend):
private_key = RSA_KEY_745.private_key(backend)
signer = private_key.signer(
padding.PKCS1v15(),
hashes.SHA512()
)
signer.update(b"no failure")
signer.finalize()
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSAVerification(object):
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
@pytest.mark.parametrize(
"pkcs1_example",
_flatten_pkcs1_examples(load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs1v15sign-vectors.txt"),
load_pkcs1_vectors
))
)
def test_pkcs1v15_verification(self, pkcs1_example, backend):
private, public, example = pkcs1_example
public_key = rsa.RSAPublicNumbers(
e=public["public_exponent"],
n=public["modulus"]
).public_key(backend)
verifier = public_key.verifier(
binascii.unhexlify(example["signature"]),
padding.PKCS1v15(),
hashes.SHA1()
)
verifier.update(binascii.unhexlify(example["message"]))
verifier.verify()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
def test_invalid_pkcs1v15_signature_wrong_data(self, backend):
private_key = RSA_KEY_512.private_key(backend)
public_key = private_key.public_key()
signer = private_key.signer(padding.PKCS1v15(), hashes.SHA1())
signer.update(b"sign me")
signature = signer.finalize()
verifier = public_key.verifier(
signature,
padding.PKCS1v15(),
hashes.SHA1()
)
verifier.update(b"incorrect data")
with pytest.raises(InvalidSignature):
verifier.verify()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
def test_invalid_pkcs1v15_signature_wrong_key(self, backend):
private_key = RSA_KEY_512.private_key(backend)
private_key2 = RSA_KEY_512_ALT.private_key(backend)
public_key = private_key2.public_key()
signer = private_key.signer(padding.PKCS1v15(), hashes.SHA1())
signer.update(b"sign me")
signature = signer.finalize()
verifier = public_key.verifier(
signature,
padding.PKCS1v15(),
hashes.SHA1()
)
verifier.update(b"sign me")
with pytest.raises(InvalidSignature):
verifier.verify()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=20
)
),
skip_message="Does not support PSS."
)
@pytest.mark.parametrize(
"pkcs1_example",
_flatten_pkcs1_examples(load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"),
load_pkcs1_vectors
))
)
def test_pss_verification(self, pkcs1_example, backend):
private, public, example = pkcs1_example
public_key = rsa.RSAPublicNumbers(
e=public["public_exponent"],
n=public["modulus"]
).public_key(backend)
verifier = public_key.verifier(
binascii.unhexlify(example["signature"]),
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=20
),
hashes.SHA1()
)
verifier.update(binascii.unhexlify(example["message"]))
verifier.verify()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS."
)
def test_invalid_pss_signature_wrong_data(self, backend):
public_key = rsa.RSAPublicNumbers(
n=int(
b"dffc2137d5e810cde9e4b4612f5796447218bab913b3fa98bdf7982e4fa6"
b"ec4d6653ef2b29fb1642b095befcbea6decc178fb4bed243d3c3592c6854"
b"6af2d3f3", 16
),
e=65537
).public_key(backend)
signature = binascii.unhexlify(
b"0e68c3649df91c5bc3665f96e157efa75b71934aaa514d91e94ca8418d100f45"
b"6f05288e58525f99666bab052adcffdf7186eb40f583bd38d98c97d3d524808b"
)
verifier = public_key.verifier(
signature,
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA1()
)
verifier.update(b"incorrect data")
with pytest.raises(InvalidSignature):
verifier.verify()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS."
)
def test_invalid_pss_signature_wrong_key(self, backend):
signature = binascii.unhexlify(
b"3a1880165014ba6eb53cc1449d13e5132ebcc0cfd9ade6d7a2494a0503bd0826"
b"f8a46c431e0d7be0ca3e453f8b2b009e2733764da7927cc6dbe7a021437a242e"
)
public_key = rsa.RSAPublicNumbers(
n=int(
b"381201f4905d67dfeb3dec131a0fbea773489227ec7a1448c3109189ac68"
b"5a95441be90866a14c4d2e139cd16db540ec6c7abab13ffff91443fd46a8"
b"960cbb7658ded26a5c95c86f6e40384e1c1239c63e541ba221191c4dd303"
b"231b42e33c6dbddf5ec9a746f09bf0c25d0f8d27f93ee0ae5c0d723348f4"
b"030d3581e13522e1", 16
),
e=65537
).public_key(backend)
verifier = public_key.verifier(
signature,
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA1()
)
verifier.update(b"sign me")
with pytest.raises(InvalidSignature):
verifier.verify()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS."
)
def test_invalid_pss_signature_data_too_large_for_modulus(self, backend):
signature = binascii.unhexlify(
b"cb43bde4f7ab89eb4a79c6e8dd67e0d1af60715da64429d90c716a490b799c29"
b"194cf8046509c6ed851052367a74e2e92d9b38947ed74332acb115a03fcc0222"
)
public_key = rsa.RSAPublicNumbers(
n=int(
b"381201f4905d67dfeb3dec131a0fbea773489227ec7a1448c3109189ac68"
b"5a95441be90866a14c4d2e139cd16db540ec6c7abab13ffff91443fd46a8"
b"960cbb7658ded26a5c95c86f6e40384e1c1239c63e541ba221191c4dd303"
b"231b42e33c6dbddf5ec9a746f09bf0c25d0f8d27f93ee0ae5c0d723348f4"
b"030d3581e13522", 16
),
e=65537
).public_key(backend)
verifier = public_key.verifier(
signature,
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA1()
)
verifier.update(b"sign me")
with pytest.raises(InvalidSignature):
verifier.verify()
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
def test_use_after_finalize(self, backend):
private_key = RSA_KEY_512.private_key(backend)
public_key = private_key.public_key()
signer = private_key.signer(padding.PKCS1v15(), hashes.SHA1())
signer.update(b"sign me")
signature = signer.finalize()
verifier = public_key.verifier(
signature,
padding.PKCS1v15(),
hashes.SHA1()
)
verifier.update(b"sign me")
verifier.verify()
with pytest.raises(AlreadyFinalized):
verifier.verify()
with pytest.raises(AlreadyFinalized):
verifier.update(b"more data")
def test_unsupported_padding(self, backend):
private_key = RSA_KEY_512.private_key(backend)
public_key = private_key.public_key()
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
public_key.verifier(b"sig", DummyPadding(), hashes.SHA1())
def test_padding_incorrect_type(self, backend):
private_key = RSA_KEY_512.private_key(backend)
public_key = private_key.public_key()
with pytest.raises(TypeError):
public_key.verifier(b"sig", "notpadding", hashes.SHA1())
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
skip_message="Does not support PSS."
)
def test_unsupported_pss_mgf(self, backend):
private_key = RSA_KEY_512.private_key(backend)
public_key = private_key.public_key()
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_MGF):
public_key.verifier(
b"sig",
padding.PSS(
mgf=DummyMGF(),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA1()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS."
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA512()),
skip_message="Does not support SHA512."
)
def test_pss_verify_digest_too_large_for_key_size(self, backend):
private_key = RSA_KEY_512.private_key(backend)
signature = binascii.unhexlify(
b"8b9a3ae9fb3b64158f3476dd8d8a1f1425444e98940e0926378baa9944d219d8"
b"534c050ef6b19b1bdc6eb4da422e89161106a6f5b5cc16135b11eb6439b646bd"
)
public_key = private_key.public_key()
with pytest.raises(ValueError):
public_key.verifier(
signature,
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA512()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS."
)
def test_pss_verify_salt_length_too_long(self, backend):
signature = binascii.unhexlify(
b"8b9a3ae9fb3b64158f3476dd8d8a1f1425444e98940e0926378baa9944d219d8"
b"534c050ef6b19b1bdc6eb4da422e89161106a6f5b5cc16135b11eb6439b646bd"
)
public_key = rsa.RSAPublicNumbers(
n=int(
b"d309e4612809437548b747d7f9eb9cd3340f54fe42bb3f84a36933b0839c"
b"11b0c8b7f67e11f7252370161e31159c49c784d4bc41c42a78ce0f0b40a3"
b"ca8ffb91", 16
),
e=65537
).public_key(backend)
verifier = public_key.verifier(
signature,
padding.PSS(
mgf=padding.MGF1(
algorithm=hashes.SHA1(),
),
salt_length=1000000
),
hashes.SHA1()
)
verifier.update(b"sign me")
with pytest.raises(InvalidSignature):
verifier.verify()
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSAPSSMGF1Verification(object):
test_rsa_pss_mgf1_sha1 = pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS using MGF1 with SHA1."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGenPSS_186-2.rsp",
"SigGenPSS_186-3.rsp",
"SigVerPSS_186-3.rsp",
],
hashes.SHA1(),
lambda params, hash_alg: padding.PSS(
mgf=padding.MGF1(
algorithm=hash_alg,
),
salt_length=params["salt_length"]
)
))
test_rsa_pss_mgf1_sha224 = pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA224()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS using MGF1 with SHA224."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGenPSS_186-2.rsp",
"SigGenPSS_186-3.rsp",
"SigVerPSS_186-3.rsp",
],
hashes.SHA224(),
lambda params, hash_alg: padding.PSS(
mgf=padding.MGF1(
algorithm=hash_alg,
),
salt_length=params["salt_length"]
)
))
test_rsa_pss_mgf1_sha256 = pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS using MGF1 with SHA256."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGenPSS_186-2.rsp",
"SigGenPSS_186-3.rsp",
"SigVerPSS_186-3.rsp",
],
hashes.SHA256(),
lambda params, hash_alg: padding.PSS(
mgf=padding.MGF1(
algorithm=hash_alg,
),
salt_length=params["salt_length"]
)
))
test_rsa_pss_mgf1_sha384 = pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA384()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS using MGF1 with SHA384."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGenPSS_186-2.rsp",
"SigGenPSS_186-3.rsp",
"SigVerPSS_186-3.rsp",
],
hashes.SHA384(),
lambda params, hash_alg: padding.PSS(
mgf=padding.MGF1(
algorithm=hash_alg,
),
salt_length=params["salt_length"]
)
))
test_rsa_pss_mgf1_sha512 = pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA512()),
salt_length=padding.PSS.MAX_LENGTH
)
),
skip_message="Does not support PSS using MGF1 with SHA512."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGenPSS_186-2.rsp",
"SigGenPSS_186-3.rsp",
"SigVerPSS_186-3.rsp",
],
hashes.SHA512(),
lambda params, hash_alg: padding.PSS(
mgf=padding.MGF1(
algorithm=hash_alg,
),
salt_length=params["salt_length"]
)
))
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSAPKCS1Verification(object):
test_rsa_pkcs1v15_verify_sha1 = pytest.mark.supported(
only_if=lambda backend: (
backend.hash_supported(hashes.SHA1()) and
backend.rsa_padding_supported(padding.PKCS1v15())
),
skip_message="Does not support SHA1 and PKCS1v1.5."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGen15_186-2.rsp",
"SigGen15_186-3.rsp",
"SigVer15_186-3.rsp",
],
hashes.SHA1(),
lambda params, hash_alg: padding.PKCS1v15()
))
test_rsa_pkcs1v15_verify_sha224 = pytest.mark.supported(
only_if=lambda backend: (
backend.hash_supported(hashes.SHA224()) and
backend.rsa_padding_supported(padding.PKCS1v15())
),
skip_message="Does not support SHA224 and PKCS1v1.5."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGen15_186-2.rsp",
"SigGen15_186-3.rsp",
"SigVer15_186-3.rsp",
],
hashes.SHA224(),
lambda params, hash_alg: padding.PKCS1v15()
))
test_rsa_pkcs1v15_verify_sha256 = pytest.mark.supported(
only_if=lambda backend: (
backend.hash_supported(hashes.SHA256()) and
backend.rsa_padding_supported(padding.PKCS1v15())
),
skip_message="Does not support SHA256 and PKCS1v1.5."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGen15_186-2.rsp",
"SigGen15_186-3.rsp",
"SigVer15_186-3.rsp",
],
hashes.SHA256(),
lambda params, hash_alg: padding.PKCS1v15()
))
test_rsa_pkcs1v15_verify_sha384 = pytest.mark.supported(
only_if=lambda backend: (
backend.hash_supported(hashes.SHA384()) and
backend.rsa_padding_supported(padding.PKCS1v15())
),
skip_message="Does not support SHA384 and PKCS1v1.5."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGen15_186-2.rsp",
"SigGen15_186-3.rsp",
"SigVer15_186-3.rsp",
],
hashes.SHA384(),
lambda params, hash_alg: padding.PKCS1v15()
))
test_rsa_pkcs1v15_verify_sha512 = pytest.mark.supported(
only_if=lambda backend: (
backend.hash_supported(hashes.SHA512()) and
backend.rsa_padding_supported(padding.PKCS1v15())
),
skip_message="Does not support SHA512 and PKCS1v1.5."
)(generate_rsa_verification_test(
load_rsa_nist_vectors,
os.path.join("asymmetric", "RSA", "FIPS_186-2"),
[
"SigGen15_186-2.rsp",
"SigGen15_186-3.rsp",
"SigVer15_186-3.rsp",
],
hashes.SHA512(),
lambda params, hash_alg: padding.PKCS1v15()
))
class TestPSS(object):
def test_invalid_salt_length_not_integer(self):
with pytest.raises(TypeError):
padding.PSS(
mgf=padding.MGF1(
hashes.SHA1()
),
salt_length=b"not_a_length"
)
def test_invalid_salt_length_negative_integer(self):
with pytest.raises(ValueError):
padding.PSS(
mgf=padding.MGF1(
hashes.SHA1()
),
salt_length=-1
)
def test_valid_pss_parameters(self):
algorithm = hashes.SHA1()
salt_length = algorithm.digest_size
mgf = padding.MGF1(algorithm)
pss = padding.PSS(mgf=mgf, salt_length=salt_length)
assert pss._mgf == mgf
assert pss._salt_length == salt_length
def test_valid_pss_parameters_maximum(self):
algorithm = hashes.SHA1()
mgf = padding.MGF1(algorithm)
pss = padding.PSS(mgf=mgf, salt_length=padding.PSS.MAX_LENGTH)
assert pss._mgf == mgf
assert pss._salt_length == padding.PSS.MAX_LENGTH
class TestMGF1(object):
def test_invalid_hash_algorithm(self):
with pytest.raises(TypeError):
padding.MGF1(b"not_a_hash")
def test_valid_mgf1_parameters(self):
algorithm = hashes.SHA1()
mgf = padding.MGF1(algorithm)
assert mgf._algorithm == algorithm
class TestOAEP(object):
def test_invalid_algorithm(self):
mgf = padding.MGF1(hashes.SHA1())
with pytest.raises(TypeError):
padding.OAEP(
mgf=mgf,
algorithm=b"",
label=None
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSADecryption(object):
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
@pytest.mark.parametrize(
"vector",
_flatten_pkcs1_examples(load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"),
load_pkcs1_vectors
))
)
def test_decrypt_pkcs1v15_vectors(self, vector, backend):
private, public, example = vector
skey = rsa.RSAPrivateNumbers(
p=private["p"],
q=private["q"],
d=private["private_exponent"],
dmp1=private["dmp1"],
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
e=private["public_exponent"],
n=private["modulus"]
)
).private_key(backend)
ciphertext = binascii.unhexlify(example["encryption"])
assert len(ciphertext) == math.ceil(skey.key_size / 8.0)
message = skey.decrypt(ciphertext, padding.PKCS1v15())
assert message == binascii.unhexlify(example["message"])
def test_unsupported_padding(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
private_key.decrypt(b"0" * 64, DummyPadding())
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
def test_decrypt_invalid_decrypt(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with pytest.raises(ValueError):
private_key.decrypt(
b"\x00" * 64,
padding.PKCS1v15()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
def test_decrypt_ciphertext_too_large(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with pytest.raises(ValueError):
private_key.decrypt(
b"\x00" * 65,
padding.PKCS1v15()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
def test_decrypt_ciphertext_too_small(self, backend):
private_key = RSA_KEY_512.private_key(backend)
ct = binascii.unhexlify(
b"50b4c14136bd198c2f3c3ed243fce036e168d56517984a263cd66492b80804f1"
b"69d210f2b9bdfb48b12f9ea05009c77da257cc600ccefe3a6283789d8ea0"
)
with pytest.raises(ValueError):
private_key.decrypt(
ct,
padding.PKCS1v15()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
),
skip_message="Does not support OAEP."
)
@pytest.mark.parametrize(
"vector",
_flatten_pkcs1_examples(load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs-1v2-1d2-vec", "oaep-vect.txt"),
load_pkcs1_vectors
))
)
def test_decrypt_oaep_vectors(self, vector, backend):
private, public, example = vector
skey = rsa.RSAPrivateNumbers(
p=private["p"],
q=private["q"],
d=private["private_exponent"],
dmp1=private["dmp1"],
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
e=private["public_exponent"],
n=private["modulus"]
)
).private_key(backend)
message = skey.decrypt(
binascii.unhexlify(example["encryption"]),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
assert message == binascii.unhexlify(example["message"])
def test_unsupported_oaep_mgf(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_MGF):
private_key.decrypt(
b"0" * 64,
padding.OAEP(
mgf=DummyMGF(),
algorithm=hashes.SHA1(),
label=None
)
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSAEncryption(object):
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
),
skip_message="Does not support OAEP."
)
@pytest.mark.parametrize(
("key_data", "pad"),
itertools.product(
(RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027,
RSA_KEY_1028, RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031,
RSA_KEY_1536, RSA_KEY_2048),
[
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
]
)
)
def test_rsa_encrypt_oaep(self, key_data, pad, backend):
private_key = key_data.private_key(backend)
pt = b"encrypt me!"
public_key = private_key.public_key()
ct = public_key.encrypt(pt, pad)
assert ct != pt
assert len(ct) == math.ceil(public_key.key_size / 8.0)
recovered_pt = private_key.decrypt(ct, pad)
assert recovered_pt == pt
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5."
)
@pytest.mark.parametrize(
("key_data", "pad"),
itertools.product(
(RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027,
RSA_KEY_1028, RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031,
RSA_KEY_1536, RSA_KEY_2048),
[padding.PKCS1v15()]
)
)
def test_rsa_encrypt_pkcs1v15(self, key_data, pad, backend):
private_key = key_data.private_key(backend)
pt = b"encrypt me!"
public_key = private_key.public_key()
ct = public_key.encrypt(pt, pad)
assert ct != pt
assert len(ct) == math.ceil(public_key.key_size / 8.0)
recovered_pt = private_key.decrypt(ct, pad)
assert recovered_pt == pt
@pytest.mark.parametrize(
("key_data", "pad"),
itertools.product(
(RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027,
RSA_KEY_1028, RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031,
RSA_KEY_1536, RSA_KEY_2048),
(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
),
padding.PKCS1v15()
)
)
)
def test_rsa_encrypt_key_too_small(self, key_data, pad, backend):
private_key = key_data.private_key(backend)
public_key = private_key.public_key()
# Slightly smaller than the key size but not enough for padding.
with pytest.raises(ValueError):
public_key.encrypt(
b"\x00" * (private_key.key_size // 8 - 1),
pad
)
# Larger than the key size.
with pytest.raises(ValueError):
public_key.encrypt(
b"\x00" * (private_key.key_size // 8 + 5),
pad
)
def test_unsupported_padding(self, backend):
private_key = RSA_KEY_512.private_key(backend)
public_key = private_key.public_key()
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
public_key.encrypt(b"somedata", DummyPadding())
with pytest.raises(TypeError):
public_key.encrypt(b"somedata", padding=object())
def test_unsupported_oaep_mgf(self, backend):
private_key = RSA_KEY_512.private_key(backend)
public_key = private_key.public_key()
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_MGF):
public_key.encrypt(
b"ciphertext",
padding.OAEP(
mgf=DummyMGF(),
algorithm=hashes.SHA1(),
label=None
)
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSANumbers(object):
def test_rsa_public_numbers(self):
public_numbers = rsa.RSAPublicNumbers(e=1, n=15)
assert public_numbers.e == 1
assert public_numbers.n == 15
def test_rsa_private_numbers(self):
public_numbers = rsa.RSAPublicNumbers(e=1, n=15)
private_numbers = rsa.RSAPrivateNumbers(
p=3,
q=5,
d=1,
dmp1=1,
dmq1=1,
iqmp=2,
public_numbers=public_numbers
)
assert private_numbers.p == 3
assert private_numbers.q == 5
assert private_numbers.d == 1
assert private_numbers.dmp1 == 1
assert private_numbers.dmq1 == 1
assert private_numbers.iqmp == 2
assert private_numbers.public_numbers == public_numbers
def test_rsa_private_numbers_create_key(self, backend):
private_key = RSA_KEY_1024.private_key(backend)
assert private_key
def test_rsa_public_numbers_create_key(self, backend):
public_key = RSA_KEY_1024.public_numbers.public_key(backend)
assert public_key
def test_public_numbers_invalid_types(self):
with pytest.raises(TypeError):
rsa.RSAPublicNumbers(e=None, n=15)
with pytest.raises(TypeError):
rsa.RSAPublicNumbers(e=1, n=None)
def test_private_numbers_invalid_types(self):
public_numbers = rsa.RSAPublicNumbers(e=1, n=15)
with pytest.raises(TypeError):
rsa.RSAPrivateNumbers(
p=None,
q=5,
d=1,
dmp1=1,
dmq1=1,
iqmp=2,
public_numbers=public_numbers
)
with pytest.raises(TypeError):
rsa.RSAPrivateNumbers(
p=3,
q=None,
d=1,
dmp1=1,
dmq1=1,
iqmp=2,
public_numbers=public_numbers
)
with pytest.raises(TypeError):
rsa.RSAPrivateNumbers(
p=3,
q=5,
d=None,
dmp1=1,
dmq1=1,
iqmp=2,
public_numbers=public_numbers
)
with pytest.raises(TypeError):
rsa.RSAPrivateNumbers(
p=3,
q=5,
d=1,
dmp1=None,
dmq1=1,
iqmp=2,
public_numbers=public_numbers
)
with pytest.raises(TypeError):
rsa.RSAPrivateNumbers(
p=3,
q=5,
d=1,
dmp1=1,
dmq1=None,
iqmp=2,
public_numbers=public_numbers
)
with pytest.raises(TypeError):
rsa.RSAPrivateNumbers(
p=3,
q=5,
d=1,
dmp1=1,
dmq1=1,
iqmp=None,
public_numbers=public_numbers
)
with pytest.raises(TypeError):
rsa.RSAPrivateNumbers(
p=3,
q=5,
d=1,
dmp1=1,
dmq1=1,
iqmp=2,
public_numbers=None
)
def test_invalid_public_numbers_argument_values(self, backend):
# Start with public_exponent=7, modulus=15. Then change one value at a
# time to test the bounds.
# Test a modulus < 3.
with pytest.raises(ValueError):
rsa.RSAPublicNumbers(e=7, n=2).public_key(backend)
# Test a public_exponent < 3
with pytest.raises(ValueError):
rsa.RSAPublicNumbers(e=1, n=15).public_key(backend)
# Test a public_exponent > modulus
with pytest.raises(ValueError):
rsa.RSAPublicNumbers(e=17, n=15).public_key(backend)
# Test a public_exponent that is not odd.
with pytest.raises(ValueError):
rsa.RSAPublicNumbers(e=14, n=15).public_key(backend)
def test_invalid_private_numbers_argument_values(self, backend):
# Start with p=3, q=11, private_exponent=3, public_exponent=7,
# modulus=33, dmp1=1, dmq1=3, iqmp=2. Then change one value at
# a time to test the bounds.
# Test a modulus < 3.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=1,
dmq1=3,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=2
)
).private_key(backend)
# Test a modulus != p * q.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=1,
dmq1=3,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=35
)
).private_key(backend)
# Test a p > modulus.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=37,
q=11,
d=3,
dmp1=1,
dmq1=3,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=33
)
).private_key(backend)
# Test a q > modulus.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=37,
d=3,
dmp1=1,
dmq1=3,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=33
)
).private_key(backend)
# Test a dmp1 > modulus.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=35,
dmq1=3,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=33
)
).private_key(backend)
# Test a dmq1 > modulus.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=1,
dmq1=35,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=33
)
).private_key(backend)
# Test an iqmp > modulus.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=1,
dmq1=3,
iqmp=35,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=33
)
).private_key(backend)
# Test a private_exponent > modulus
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=37,
dmp1=1,
dmq1=3,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=33
)
).private_key(backend)
# Test a public_exponent < 3
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=1,
dmq1=3,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=1,
n=33
)
).private_key(backend)
# Test a public_exponent > modulus
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=1,
dmq1=3,
iqmp=35,
public_numbers=rsa.RSAPublicNumbers(
e=65537,
n=33
)
).private_key(backend)
# Test a public_exponent that is not odd.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=1,
dmq1=3,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=6,
n=33
)
).private_key(backend)
# Test a dmp1 that is not odd.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=2,
dmq1=3,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=33
)
).private_key(backend)
# Test a dmq1 that is not odd.
with pytest.raises(ValueError):
rsa.RSAPrivateNumbers(
p=3,
q=11,
d=3,
dmp1=1,
dmq1=4,
iqmp=2,
public_numbers=rsa.RSAPublicNumbers(
e=7,
n=33
)
).private_key(backend)
def test_public_number_repr(self):
num = RSAPublicNumbers(1, 1)
assert repr(num) == "<RSAPublicNumbers(e=1, n=1)>"
class TestRSANumbersEquality(object):
def test_public_numbers_eq(self):
num = RSAPublicNumbers(1, 2)
num2 = RSAPublicNumbers(1, 2)
assert num == num2
def test_public_numbers_ne(self):
num = RSAPublicNumbers(1, 2)
assert num != RSAPublicNumbers(2, 2)
assert num != RSAPublicNumbers(1, 3)
assert num != object()
def test_private_numbers_eq(self):
pub = RSAPublicNumbers(1, 2)
num = RSAPrivateNumbers(1, 2, 3, 4, 5, 6, pub)
pub2 = RSAPublicNumbers(1, 2)
num2 = RSAPrivateNumbers(1, 2, 3, 4, 5, 6, pub2)
assert num == num2
def test_private_numbers_ne(self):
pub = RSAPublicNumbers(1, 2)
num = RSAPrivateNumbers(1, 2, 3, 4, 5, 6, pub)
assert num != RSAPrivateNumbers(
1, 2, 3, 4, 5, 7, RSAPublicNumbers(1, 2)
)
assert num != RSAPrivateNumbers(
1, 2, 3, 4, 4, 6, RSAPublicNumbers(1, 2)
)
assert num != RSAPrivateNumbers(
1, 2, 3, 5, 5, 6, RSAPublicNumbers(1, 2)
)
assert num != RSAPrivateNumbers(
1, 2, 4, 4, 5, 6, RSAPublicNumbers(1, 2)
)
assert num != RSAPrivateNumbers(
1, 3, 3, 4, 5, 6, RSAPublicNumbers(1, 2)
)
assert num != RSAPrivateNumbers(
2, 2, 3, 4, 5, 6, RSAPublicNumbers(1, 2)
)
assert num != RSAPrivateNumbers(
1, 2, 3, 4, 5, 6, RSAPublicNumbers(2, 2)
)
assert num != RSAPrivateNumbers(
1, 2, 3, 4, 5, 6, RSAPublicNumbers(1, 3)
)
assert num != object()
| gpl-2.0 | -3,008,254,266,136,403,000 | 32.573529 | 79 | 0.546754 | false |
abusesa/abusehelper | abusehelper/core/cymruwhois.py | 1 | 5556 | from __future__ import absolute_import
import socket
import idiokit
from idiokit import dns
from . import utils, transformation
def _parse_ip(string, families=(socket.AF_INET, socket.AF_INET6)):
for family in families:
try:
return socket.inet_ntop(family, socket.inet_pton(family, string))
except (ValueError, socket.error):
pass
return None
def _nibbles(ipv6, _hex="0123456789abcdef"):
result = []
for ch in socket.inet_pton(socket.AF_INET6, ipv6):
num = ord(ch)
result.append(_hex[num >> 4])
result.append(_hex[num & 0xf])
return result
def _split(txt_results, keys):
results = set()
for strings in txt_results:
pieces = "".join(strings).split("|")
decoded = map(lambda x: x.strip().decode("utf-8", "replace"), pieces)
item_list = list()
for key, value in zip(keys, decoded):
if key is None:
continue
if value in ("", "-"):
continue
item_list.append((key, value))
if not item_list:
continue
results.add(frozenset(item_list))
return tuple(tuple(x) for x in results)
class ASNameLookup(object):
_keys = (None, None, None, "as allocated", "as name")
def __init__(self, resolver=None, cache_time=4 * 60 * 60, catch_error=True):
self._resolver = resolver
self._cache = utils.TimedCache(cache_time)
self._catch_error = catch_error
@idiokit.stream
def lookup(self, asn):
try:
asn = int(asn)
except ValueError:
idiokit.stop(())
results = self._cache.get(asn, None)
if results is not None:
idiokit.stop(results)
try:
txt_results = yield dns.txt(
"AS{0}.asn.cymru.com".format(asn),
resolver=self._resolver)
except dns.DNSError:
if self._catch_error:
idiokit.stop(())
else:
raise
results = _split(txt_results, self._keys)
self._cache.set(asn, results)
idiokit.stop(results)
class OriginLookup(object):
_keys = ("asn", "bgp prefix", "cc", "registry", "bgp prefix allocated")
def __init__(self, resolver=None, cache_time=4 * 60 * 60, catch_error=True):
self._resolver = resolver
self._cache = utils.TimedCache(cache_time)
self._catch_error = catch_error
@idiokit.stream
def _lookup(self, cache_key, query):
results = self._cache.get(cache_key, None)
if results is not None:
idiokit.stop(results)
try:
txt_results = yield dns.txt(query, resolver=self._resolver)
except dns.DNSError:
if self._catch_error:
idiokit.stop(())
else:
raise
results = []
for result in _split(txt_results, self._keys):
result_dict = dict(result)
for asn in result_dict.get("asn", "").split():
if not asn:
continue
result_dict["asn"] = asn
results.append(tuple(result_dict.iteritems()))
self._cache.set(cache_key, tuple(results))
idiokit.stop(results)
@idiokit.stream
def lookup(self, ip):
ipv4 = _parse_ip(ip, families=[socket.AF_INET])
if ipv4 is not None:
prefix = ".".join(reversed(ipv4.split(".")))
results = yield self._lookup(ipv4, prefix + ".origin.asn.cymru.com")
idiokit.stop(results)
ipv6 = _parse_ip(ip, families=[socket.AF_INET6])
if ipv6 is not None:
prefix = ".".join(reversed(_nibbles(ipv6)))
results = yield self._lookup(ipv6, prefix + ".origin6.asn.cymru.com")
idiokit.stop(results)
idiokit.stop(())
class CymruWhois(object):
def __init__(self, resolver=None, cache_time=4 * 60 * 60):
self._origin_lookup = OriginLookup(resolver, cache_time)
self._asname_lookup = ASNameLookup(resolver, cache_time)
def _ip_values(self, event, keys):
for key in keys:
for value in event.values(key, parser=_parse_ip):
yield value
@idiokit.stream
def augment(self, *ip_keys):
while True:
event = yield idiokit.next()
if not ip_keys:
values = event.values(parser=_parse_ip)
else:
values = self._ip_values(event, ip_keys)
for ip in values:
items = yield self.lookup(ip)
for key, value in items:
event.add(key, value)
yield idiokit.send(event)
@idiokit.stream
def lookup(self, ip):
results = yield self._origin_lookup.lookup(ip)
for result in results:
result = dict(result)
asn = result.get("asn", None)
if asn is not None:
infos = yield self._asname_lookup.lookup(asn)
for info in infos:
result.update(info)
break
idiokit.stop(tuple(result.items()))
idiokit.stop(())
global_whois = CymruWhois()
augment = global_whois.augment
lookup = global_whois.lookup
class Handler(transformation.Handler):
def __init__(self, ip_keys=[], *args, **keys):
transformation.Handler.__init__(self, *args, **keys)
self.ip_keys = tuple(ip_keys)
def transform(self):
return augment(*self.ip_keys)
| mit | -1,920,989,968,818,849,000 | 28.089005 | 81 | 0.551836 | false |
sigmavirus24/github-cli | gh/commands/repo/fork.py | 1 | 1355 | from gh.base import Command
class ForkRepoCommand(Command):
name = 'fork.repo'
usage = '%prog [options] fork.repo [options] login/repo'
summary = 'Fork a repository'
subcommands = {}
def __init__(self):
super(ForkRepoCommand, self).__init__()
self.parser.add_option('-o', '--organization',
dest='organization',
help='Fork to an organization instead of user',
type='str',
default='',
nargs=1,
)
def run(self, options, args):
opts, args = self.parser.parse_args(args)
self.login()
if opts.help:
self.help()
if not args or '/' not in args[0]:
self.parser.error('You must provide a repository name')
return self.FAILURE
self.repository = args[0].split('/')
self.get_repo(options)
fork = self.repo.create_fork(opts.organization)
if fork.owner.login == self.repo.owner.login:
self.parser.error('An error occurred and the repository was not '
'forked')
return self.FAILURE
print('git clone {0}'.format(fork.ssh_url))
return self.SUCCESS
ForkRepoCommand()
| gpl-3.0 | 235,013,058,375,727,840 | 29.795455 | 78 | 0.509963 | false |
jakevdp/ESAC-stats-2014 | notebooks/fig_code/figures.py | 1 | 6516 | import numpy as np
import matplotlib.pyplot as plt
def plot_venn_diagram():
fig, ax = plt.subplots(subplot_kw=dict(frameon=False, xticks=[], yticks=[]))
ax.add_patch(plt.Circle((0.3, 0.3), 0.3, fc='red', alpha=0.5))
ax.add_patch(plt.Circle((0.6, 0.3), 0.3, fc='blue', alpha=0.5))
ax.add_patch(plt.Rectangle((-0.1, -0.1), 1.1, 0.8, fc='none', ec='black'))
ax.text(0.2, 0.3, '$x$', size=30, ha='center', va='center')
ax.text(0.7, 0.3, '$y$', size=30, ha='center', va='center')
ax.text(0.0, 0.6, '$I$', size=30)
ax.axis('equal')
def plot_example_decision_tree():
fig = plt.figure(figsize=(10, 4))
ax = fig.add_axes([0, 0, 0.8, 1], frameon=False, xticks=[], yticks=[])
ax.set_title('Example Decision Tree: Animal Classification', size=24)
def text(ax, x, y, t, size=20, **kwargs):
ax.text(x, y, t,
ha='center', va='center', size=size,
bbox=dict(boxstyle='round', ec='k', fc='w'), **kwargs)
text(ax, 0.5, 0.9, "How big is\nthe animal?", 20)
text(ax, 0.3, 0.6, "Does the animal\nhave horns?", 18)
text(ax, 0.7, 0.6, "Does the animal\nhave two legs?", 18)
text(ax, 0.12, 0.3, "Are the horns\nlonger than 10cm?", 14)
text(ax, 0.38, 0.3, "Is the animal\nwearing a collar?", 14)
text(ax, 0.62, 0.3, "Does the animal\nhave wings?", 14)
text(ax, 0.88, 0.3, "Does the animal\nhave a tail?", 14)
text(ax, 0.4, 0.75, "> 1m", 12, alpha=0.4)
text(ax, 0.6, 0.75, "< 1m", 12, alpha=0.4)
text(ax, 0.21, 0.45, "yes", 12, alpha=0.4)
text(ax, 0.34, 0.45, "no", 12, alpha=0.4)
text(ax, 0.66, 0.45, "yes", 12, alpha=0.4)
text(ax, 0.79, 0.45, "no", 12, alpha=0.4)
ax.plot([0.3, 0.5, 0.7], [0.6, 0.9, 0.6], '-k')
ax.plot([0.12, 0.3, 0.38], [0.3, 0.6, 0.3], '-k')
ax.plot([0.62, 0.7, 0.88], [0.3, 0.6, 0.3], '-k')
ax.plot([0.0, 0.12, 0.20], [0.0, 0.3, 0.0], '--k')
ax.plot([0.28, 0.38, 0.48], [0.0, 0.3, 0.0], '--k')
ax.plot([0.52, 0.62, 0.72], [0.0, 0.3, 0.0], '--k')
ax.plot([0.8, 0.88, 1.0], [0.0, 0.3, 0.0], '--k')
ax.axis([0, 1, 0, 1])
def visualize_tree(estimator, X, y, boundaries=True,
xlim=None, ylim=None):
estimator.fit(X, y)
if xlim is None:
xlim = (X[:, 0].min() - 0.1, X[:, 0].max() + 0.1)
if ylim is None:
ylim = (X[:, 1].min() - 0.1, X[:, 1].max() + 0.1)
x_min, x_max = xlim
y_min, y_max = ylim
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
np.linspace(y_min, y_max, 100))
Z = estimator.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, alpha=0.2, cmap='rainbow')
plt.clim(y.min(), y.max())
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='rainbow')
plt.axis('off')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.clim(y.min(), y.max())
# Plot the decision boundaries
def plot_boundaries(i, xlim, ylim):
if i < 0:
return
tree = estimator.tree_
if tree.feature[i] == 0:
plt.plot([tree.threshold[i], tree.threshold[i]], ylim, '-k')
plot_boundaries(tree.children_left[i],
[xlim[0], tree.threshold[i]], ylim)
plot_boundaries(tree.children_right[i],
[tree.threshold[i], xlim[1]], ylim)
elif tree.feature[i] == 1:
plt.plot(xlim, [tree.threshold[i], tree.threshold[i]], '-k')
plot_boundaries(tree.children_left[i], xlim,
[ylim[0], tree.threshold[i]])
plot_boundaries(tree.children_right[i], xlim,
[tree.threshold[i], ylim[1]])
if boundaries:
plot_boundaries(0, plt.xlim(), plt.ylim())
def plot_tree_interactive(X, y):
from sklearn.tree import DecisionTreeClassifier
def interactive_tree(depth):
clf = DecisionTreeClassifier(max_depth=depth, random_state=0)
visualize_tree(clf, X, y)
from IPython.html.widgets import interact
return interact(interactive_tree, depth=[1, 5])
def plot_kmeans_interactive():
from IPython.html.widgets import interact
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=300, centers=4,
random_state=0, cluster_std=0.60)
def _kmeans_step(frame, n_clusters):
rng = np.random.RandomState(2)
labels = np.zeros(X.shape[0])
centers = rng.randn(n_clusters, 2)
nsteps = frame // 3
for i in range(nsteps + 1):
old_centers = centers
if i < nsteps or frame % 3 > 0:
dist = euclidean_distances(X, centers)
labels = dist.argmin(1)
if i < nsteps or frame % 3 > 1:
centers = np.array([X[labels == j].mean(0)
for j in range(n_clusters)])
nans = np.isnan(centers)
centers[nans] = old_centers[nans]
# plot the cluster centers
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='rainbow');
plt.scatter(old_centers[:, 0], old_centers[:, 1], marker='o',
c=np.arange(n_clusters),
s=200, cmap='rainbow')
plt.scatter(old_centers[:, 0], old_centers[:, 1], marker='o',
c='black', s=50)
# plot new centers if third frame
if frame % 3 == 2:
for i in range(n_clusters):
plt.annotate('', centers[i], old_centers[i],
arrowprops=dict(arrowstyle='->', linewidth=1))
plt.scatter(centers[:, 0], centers[:, 1], marker='o',
c=np.arange(n_clusters),
s=200, cmap='rainbow')
plt.scatter(centers[:, 0], centers[:, 1], marker='o',
c='black', s=50)
plt.xlim(-4, 4)
plt.ylim(-2, 10)
if frame % 3 == 1:
plt.text(3.8, 9.5, "1. Reassign points to nearest centroid",
ha='right', va='top', size=14)
elif frame % 3 == 2:
plt.text(3.8, 9.5, "2. Update centroids to cluster means",
ha='right', va='top', size=14)
return interact(_kmeans_step, frame=[0, 50], n_clusters=[3, 5])
| bsd-2-clause | -8,262,181,070,894,841,000 | 36.234286 | 80 | 0.518109 | false |
cschenck/blender_sim | fluid_sim_deps/blender-2.69/2.69/python/lib/python3.3/site-packages/numpy/ma/core.py | 1 | 227215 | """
numpy.ma : a package to handle missing or invalid values.
This package was initially written for numarray by Paul F. Dubois
at Lawrence Livermore National Laboratory.
In 2006, the package was completely rewritten by Pierre Gerard-Marchant
(University of Georgia) to make the MaskedArray class a subclass of ndarray,
and to improve support of structured arrays.
Copyright 1999, 2000, 2001 Regents of the University of California.
Released for unlimited redistribution.
* Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois.
* Subclassing of the base `ndarray` 2006 by Pierre Gerard-Marchant
(pgmdevlist_AT_gmail_DOT_com)
* Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com)
.. moduleauthor:: Pierre Gerard-Marchant
"""
# pylint: disable-msg=E1002
__author__ = "Pierre GF Gerard-Marchant"
__docformat__ = "restructuredtext en"
__all__ = ['MAError', 'MaskError', 'MaskType', 'MaskedArray',
'bool_',
'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue',
'amax', 'amin', 'angle', 'anom', 'anomalies', 'any', 'arange',
'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2',
'arctanh', 'argmax', 'argmin', 'argsort', 'around',
'array', 'asarray', 'asanyarray',
'bitwise_and', 'bitwise_or', 'bitwise_xor',
'ceil', 'choose', 'clip', 'common_fill_value', 'compress',
'compressed', 'concatenate', 'conjugate', 'copy', 'cos', 'cosh',
'count', 'cumprod', 'cumsum',
'default_fill_value', 'diag', 'diagonal', 'diff', 'divide', 'dump',
'dumps',
'empty', 'empty_like', 'equal', 'exp', 'expand_dims',
'fabs', 'flatten_mask', 'fmod', 'filled', 'floor', 'floor_divide',
'fix_invalid', 'flatten_structured_array', 'frombuffer', 'fromflex',
'fromfunction',
'getdata', 'getmask', 'getmaskarray', 'greater', 'greater_equal',
'harden_mask', 'hypot',
'identity', 'ids', 'indices', 'inner', 'innerproduct',
'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray',
'left_shift', 'less', 'less_equal', 'load', 'loads', 'log', 'log2',
'log10', 'logical_and', 'logical_not', 'logical_or', 'logical_xor',
'make_mask', 'make_mask_descr', 'make_mask_none', 'mask_or',
'masked', 'masked_array', 'masked_equal', 'masked_greater',
'masked_greater_equal', 'masked_inside', 'masked_invalid',
'masked_less', 'masked_less_equal', 'masked_not_equal',
'masked_object', 'masked_outside', 'masked_print_option',
'masked_singleton', 'masked_values', 'masked_where', 'max', 'maximum',
'maximum_fill_value', 'mean', 'min', 'minimum', 'minimum_fill_value',
'mod', 'multiply', 'mvoid',
'negative', 'nomask', 'nonzero', 'not_equal',
'ones', 'outer', 'outerproduct',
'power', 'prod', 'product', 'ptp', 'put', 'putmask',
'rank', 'ravel', 'remainder', 'repeat', 'reshape', 'resize',
'right_shift', 'round_', 'round',
'set_fill_value', 'shape', 'sin', 'sinh', 'size', 'sometrue',
'sort', 'soften_mask', 'sqrt', 'squeeze', 'std', 'subtract', 'sum',
'swapaxes',
'take', 'tan', 'tanh', 'trace', 'transpose', 'true_divide',
'var', 'where',
'zeros']
import pickle
import numpy as np
from numpy import ndarray, amax, amin, iscomplexobj, bool_
from numpy import array as narray
import numpy.core.umath as umath
from numpy.lib.function_base import angle
import numpy.core.numerictypes as ntypes
from numpy.compat import getargspec, formatargspec
from numpy import expand_dims as n_expand_dims
import warnings
import sys
if sys.version_info[0] >= 3:
from functools import reduce
MaskType = np.bool_
nomask = MaskType(0)
def doc_note(initialdoc, note):
"""
Adds a Notes section to an existing docstring.
"""
if initialdoc is None:
return
if note is None:
return initialdoc
newdoc = """
%s
Notes
-----
%s
"""
return newdoc % (initialdoc, note)
def get_object_signature(obj):
"""
Get the signature from obj
"""
try:
sig = formatargspec(*getargspec(obj))
except TypeError as errmsg:
sig = ''
# msg = "Unable to retrieve the signature of %s '%s'\n"\
# "(Initial error message: %s)"
# warnings.warn(msg % (type(obj),
# getattr(obj, '__name__', '???'),
# errmsg))
return sig
#####--------------------------------------------------------------------------
#---- --- Exceptions ---
#####--------------------------------------------------------------------------
class MAError(Exception):
"""Class for masked array related errors."""
pass
class MaskError(MAError):
"Class for mask related errors."
pass
#####--------------------------------------------------------------------------
#---- --- Filling options ---
#####--------------------------------------------------------------------------
# b: boolean - c: complex - f: floats - i: integer - O: object - S: string
default_filler = {'b': True,
'c' : 1.e20 + 0.0j,
'f' : 1.e20,
'i' : 999999,
'O' : '?',
'S' : 'N/A',
'u' : 999999,
'V' : '???',
'U' : 'N/A',
'M8[D]' : np.datetime64('NaT', 'D'),
'M8[us]' : np.datetime64('NaT', 'us')
}
max_filler = ntypes._minvals
max_filler.update([(k, -np.inf) for k in [np.float32, np.float64]])
min_filler = ntypes._maxvals
min_filler.update([(k, +np.inf) for k in [np.float32, np.float64]])
if 'float128' in ntypes.typeDict:
max_filler.update([(np.float128, -np.inf)])
min_filler.update([(np.float128, +np.inf)])
def default_fill_value(obj):
"""
Return the default fill value for the argument object.
The default filling value depends on the datatype of the input
array or the type of the input scalar:
======== ========
datatype default
======== ========
bool True
int 999999
float 1.e20
complex 1.e20+0j
object '?'
string 'N/A'
======== ========
Parameters
----------
obj : ndarray, dtype or scalar
The array data-type or scalar for which the default fill value
is returned.
Returns
-------
fill_value : scalar
The default fill value.
Examples
--------
>>> np.ma.default_fill_value(1)
999999
>>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
1e+20
>>> np.ma.default_fill_value(np.dtype(complex))
(1e+20+0j)
"""
if hasattr(obj, 'dtype'):
defval = _check_fill_value(None, obj.dtype)
elif isinstance(obj, np.dtype):
if obj.subdtype:
defval = default_filler.get(obj.subdtype[0].kind, '?')
elif obj.kind == 'M':
defval = default_filler.get(obj.str[1:], '?')
else:
defval = default_filler.get(obj.kind, '?')
elif isinstance(obj, float):
defval = default_filler['f']
elif isinstance(obj, int) or isinstance(obj, int):
defval = default_filler['i']
elif isinstance(obj, str):
defval = default_filler['S']
elif isinstance(obj, str):
defval = default_filler['U']
elif isinstance(obj, complex):
defval = default_filler['c']
else:
defval = default_filler['O']
return defval
def _recursive_extremum_fill_value(ndtype, extremum):
names = ndtype.names
if names:
deflist = []
for name in names:
fval = _recursive_extremum_fill_value(ndtype[name], extremum)
deflist.append(fval)
return tuple(deflist)
return extremum[ndtype]
def minimum_fill_value(obj):
"""
Return the maximum value that can be represented by the dtype of an object.
This function is useful for calculating a fill value suitable for
taking the minimum of an array with a given dtype.
Parameters
----------
obj : ndarray or dtype
An object that can be queried for it's numeric type.
Returns
-------
val : scalar
The maximum representable value.
Raises
------
TypeError
If `obj` isn't a suitable numeric type.
See Also
--------
maximum_fill_value : The inverse function.
set_fill_value : Set the filling value of a masked array.
MaskedArray.fill_value : Return current fill value.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.int8()
>>> ma.minimum_fill_value(a)
127
>>> a = np.int32()
>>> ma.minimum_fill_value(a)
2147483647
An array of numeric data can also be passed.
>>> a = np.array([1, 2, 3], dtype=np.int8)
>>> ma.minimum_fill_value(a)
127
>>> a = np.array([1, 2, 3], dtype=np.float32)
>>> ma.minimum_fill_value(a)
inf
"""
errmsg = "Unsuitable type for calculating minimum."
if hasattr(obj, 'dtype'):
return _recursive_extremum_fill_value(obj.dtype, min_filler)
elif isinstance(obj, float):
return min_filler[ntypes.typeDict['float_']]
elif isinstance(obj, int):
return min_filler[ntypes.typeDict['int_']]
elif isinstance(obj, int):
return min_filler[ntypes.typeDict['uint']]
elif isinstance(obj, np.dtype):
return min_filler[obj]
else:
raise TypeError(errmsg)
def maximum_fill_value(obj):
"""
Return the minimum value that can be represented by the dtype of an object.
This function is useful for calculating a fill value suitable for
taking the maximum of an array with a given dtype.
Parameters
----------
obj : {ndarray, dtype}
An object that can be queried for it's numeric type.
Returns
-------
val : scalar
The minimum representable value.
Raises
------
TypeError
If `obj` isn't a suitable numeric type.
See Also
--------
minimum_fill_value : The inverse function.
set_fill_value : Set the filling value of a masked array.
MaskedArray.fill_value : Return current fill value.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.int8()
>>> ma.maximum_fill_value(a)
-128
>>> a = np.int32()
>>> ma.maximum_fill_value(a)
-2147483648
An array of numeric data can also be passed.
>>> a = np.array([1, 2, 3], dtype=np.int8)
>>> ma.maximum_fill_value(a)
-128
>>> a = np.array([1, 2, 3], dtype=np.float32)
>>> ma.maximum_fill_value(a)
-inf
"""
errmsg = "Unsuitable type for calculating maximum."
if hasattr(obj, 'dtype'):
return _recursive_extremum_fill_value(obj.dtype, max_filler)
elif isinstance(obj, float):
return max_filler[ntypes.typeDict['float_']]
elif isinstance(obj, int):
return max_filler[ntypes.typeDict['int_']]
elif isinstance(obj, int):
return max_filler[ntypes.typeDict['uint']]
elif isinstance(obj, np.dtype):
return max_filler[obj]
else:
raise TypeError(errmsg)
def _recursive_set_default_fill_value(dtypedescr):
deflist = []
for currentdescr in dtypedescr:
currenttype = currentdescr[1]
if isinstance(currenttype, list):
deflist.append(tuple(_recursive_set_default_fill_value(currenttype)))
else:
deflist.append(default_fill_value(np.dtype(currenttype)))
return tuple(deflist)
def _recursive_set_fill_value(fillvalue, dtypedescr):
fillvalue = np.resize(fillvalue, len(dtypedescr))
output_value = []
for (fval, descr) in zip(fillvalue, dtypedescr):
cdtype = descr[1]
if isinstance(cdtype, list):
output_value.append(tuple(_recursive_set_fill_value(fval, cdtype)))
else:
output_value.append(np.array(fval, dtype=cdtype).item())
return tuple(output_value)
def _check_fill_value(fill_value, ndtype):
"""
Private function validating the given `fill_value` for the given dtype.
If fill_value is None, it is set to the default corresponding to the dtype
if this latter is standard (no fields). If the datatype is flexible (named
fields), fill_value is set to a tuple whose elements are the default fill
values corresponding to each field.
If fill_value is not None, its value is forced to the given dtype.
"""
ndtype = np.dtype(ndtype)
fields = ndtype.fields
if fill_value is None:
if fields:
descr = ndtype.descr
fill_value = np.array(_recursive_set_default_fill_value(descr),
dtype=ndtype,)
else:
fill_value = default_fill_value(ndtype)
elif fields:
fdtype = [(_[0], _[1]) for _ in ndtype.descr]
if isinstance(fill_value, (ndarray, np.void)):
try:
fill_value = np.array(fill_value, copy=False, dtype=fdtype)
except ValueError:
err_msg = "Unable to transform %s to dtype %s"
raise ValueError(err_msg % (fill_value, fdtype))
else:
descr = ndtype.descr
fill_value = np.asarray(fill_value, dtype=object)
fill_value = np.array(_recursive_set_fill_value(fill_value, descr),
dtype=ndtype)
else:
if isinstance(fill_value, str) and (ndtype.char not in 'SV'):
fill_value = default_fill_value(ndtype)
else:
# In case we want to convert 1e+20 to int...
try:
fill_value = np.array(fill_value, copy=False, dtype=ndtype)#.item()
except OverflowError:
fill_value = default_fill_value(ndtype)
return np.array(fill_value)
def set_fill_value(a, fill_value):
"""
Set the filling value of a, if a is a masked array.
This function changes the fill value of the masked array `a` in place.
If `a` is not a masked array, the function returns silently, without
doing anything.
Parameters
----------
a : array_like
Input array.
fill_value : dtype
Filling value. A consistency test is performed to make sure
the value is compatible with the dtype of `a`.
Returns
-------
None
Nothing returned by this function.
See Also
--------
maximum_fill_value : Return the default fill value for a dtype.
MaskedArray.fill_value : Return current fill value.
MaskedArray.set_fill_value : Equivalent method.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> a = ma.masked_where(a < 3, a)
>>> a
masked_array(data = [-- -- -- 3 4],
mask = [ True True True False False],
fill_value=999999)
>>> ma.set_fill_value(a, -999)
>>> a
masked_array(data = [-- -- -- 3 4],
mask = [ True True True False False],
fill_value=-999)
Nothing happens if `a` is not a masked array.
>>> a = range(5)
>>> a
[0, 1, 2, 3, 4]
>>> ma.set_fill_value(a, 100)
>>> a
[0, 1, 2, 3, 4]
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> ma.set_fill_value(a, 100)
>>> a
array([0, 1, 2, 3, 4])
"""
if isinstance(a, MaskedArray):
a.set_fill_value(fill_value)
return
def get_fill_value(a):
"""
Return the filling value of a, if any. Otherwise, returns the
default filling value for that type.
"""
if isinstance(a, MaskedArray):
result = a.fill_value
else:
result = default_fill_value(a)
return result
def common_fill_value(a, b):
"""
Return the common filling value of two masked arrays, if any.
If ``a.fill_value == b.fill_value``, return the fill value,
otherwise return None.
Parameters
----------
a, b : MaskedArray
The masked arrays for which to compare fill values.
Returns
-------
fill_value : scalar or None
The common fill value, or None.
Examples
--------
>>> x = np.ma.array([0, 1.], fill_value=3)
>>> y = np.ma.array([0, 1.], fill_value=3)
>>> np.ma.common_fill_value(x, y)
3.0
"""
t1 = get_fill_value(a)
t2 = get_fill_value(b)
if t1 == t2:
return t1
return None
#####--------------------------------------------------------------------------
def filled(a, fill_value=None):
"""
Return input as an array with masked data replaced by a fill value.
If `a` is not a `MaskedArray`, `a` itself is returned.
If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to
``a.fill_value``.
Parameters
----------
a : MaskedArray or array_like
An input object.
fill_value : scalar, optional
Filling value. Default is None.
Returns
-------
a : ndarray
The filled array.
See Also
--------
compressed
Examples
--------
>>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> x.filled()
array([[999999, 1, 2],
[999999, 4, 5],
[ 6, 7, 8]])
"""
if hasattr(a, 'filled'):
return a.filled(fill_value)
elif isinstance(a, ndarray):
# Should we check for contiguity ? and a.flags['CONTIGUOUS']:
return a
elif isinstance(a, dict):
return np.array(a, 'O')
else:
return np.array(a)
#####--------------------------------------------------------------------------
def get_masked_subclass(*arrays):
"""
Return the youngest subclass of MaskedArray from a list of (masked) arrays.
In case of siblings, the first listed takes over.
"""
if len(arrays) == 1:
arr = arrays[0]
if isinstance(arr, MaskedArray):
rcls = type(arr)
else:
rcls = MaskedArray
else:
arrcls = [type(a) for a in arrays]
rcls = arrcls[0]
if not issubclass(rcls, MaskedArray):
rcls = MaskedArray
for cls in arrcls[1:]:
if issubclass(cls, rcls):
rcls = cls
# Don't return MaskedConstant as result: revert to MaskedArray
if rcls.__name__ == 'MaskedConstant':
return MaskedArray
return rcls
#####--------------------------------------------------------------------------
def getdata(a, subok=True):
"""
Return the data of a masked array as an ndarray.
Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``,
else return `a` as a ndarray or subclass (depending on `subok`) if not.
Parameters
----------
a : array_like
Input ``MaskedArray``, alternatively a ndarray or a subclass thereof.
subok : bool
Whether to force the output to be a `pure` ndarray (False) or to
return a subclass of ndarray if appropriate (True, default).
See Also
--------
getmask : Return the mask of a masked array, or nomask.
getmaskarray : Return the mask of a masked array, or full array of False.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(data =
[[1 --]
[3 4]],
mask =
[[False True]
[False False]],
fill_value=999999)
>>> ma.getdata(a)
array([[1, 2],
[3, 4]])
Equivalently use the ``MaskedArray`` `data` attribute.
>>> a.data
array([[1, 2],
[3, 4]])
"""
try:
data = a._data
except AttributeError:
data = np.array(a, copy=False, subok=subok)
if not subok:
return data.view(ndarray)
return data
get_data = getdata
def fix_invalid(a, mask=nomask, copy=True, fill_value=None):
"""
Return input with invalid data masked and replaced by a fill value.
Invalid data means values of `nan`, `inf`, etc.
Parameters
----------
a : array_like
Input array, a (subclass of) ndarray.
copy : bool, optional
Whether to use a copy of `a` (True) or to fix `a` in place (False).
Default is True.
fill_value : scalar, optional
Value used for fixing invalid data. Default is None, in which case
the ``a.fill_value`` is used.
Returns
-------
b : MaskedArray
The input array with invalid entries fixed.
Notes
-----
A copy is performed by default.
Examples
--------
>>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3)
>>> x
masked_array(data = [-- -1.0 nan inf],
mask = [ True False False False],
fill_value = 1e+20)
>>> np.ma.fix_invalid(x)
masked_array(data = [-- -1.0 -- --],
mask = [ True False True True],
fill_value = 1e+20)
>>> fixed = np.ma.fix_invalid(x)
>>> fixed.data
array([ 1.00000000e+00, -1.00000000e+00, 1.00000000e+20,
1.00000000e+20])
>>> x.data
array([ 1., -1., NaN, Inf])
"""
a = masked_array(a, copy=copy, mask=mask, subok=True)
#invalid = (numpy.isnan(a._data) | numpy.isinf(a._data))
invalid = np.logical_not(np.isfinite(a._data))
if not invalid.any():
return a
a._mask |= invalid
if fill_value is None:
fill_value = a.fill_value
a._data[invalid] = fill_value
return a
#####--------------------------------------------------------------------------
#---- --- Ufuncs ---
#####--------------------------------------------------------------------------
ufunc_domain = {}
ufunc_fills = {}
class _DomainCheckInterval:
"""
Define a valid interval, so that :
``domain_check_interval(a,b)(x) == True`` where
``x < a`` or ``x > b``.
"""
def __init__(self, a, b):
"domain_check_interval(a,b)(x) = true where x < a or y > b"
if (a > b):
(a, b) = (b, a)
self.a = a
self.b = b
def __call__ (self, x):
"Execute the call behavior."
return umath.logical_or(umath.greater (x, self.b),
umath.less(x, self.a))
class _DomainTan:
"""Define a valid interval for the `tan` function, so that:
``domain_tan(eps) = True`` where ``abs(cos(x)) < eps``
"""
def __init__(self, eps):
"domain_tan(eps) = true where abs(cos(x)) < eps)"
self.eps = eps
def __call__ (self, x):
"Executes the call behavior."
return umath.less(umath.absolute(umath.cos(x)), self.eps)
class _DomainSafeDivide:
"""Define a domain for safe division."""
def __init__ (self, tolerance=None):
self.tolerance = tolerance
def __call__ (self, a, b):
# Delay the selection of the tolerance to here in order to reduce numpy
# import times. The calculation of these parameters is a substantial
# component of numpy's import time.
if self.tolerance is None:
self.tolerance = np.finfo(float).tiny
return umath.absolute(a) * self.tolerance >= umath.absolute(b)
class _DomainGreater:
"""DomainGreater(v)(x) is True where x <= v."""
def __init__(self, critical_value):
"DomainGreater(v)(x) = true where x <= v"
self.critical_value = critical_value
def __call__ (self, x):
"Executes the call behavior."
return umath.less_equal(x, self.critical_value)
class _DomainGreaterEqual:
"""DomainGreaterEqual(v)(x) is True where x < v."""
def __init__(self, critical_value):
"DomainGreaterEqual(v)(x) = true where x < v"
self.critical_value = critical_value
def __call__ (self, x):
"Executes the call behavior."
return umath.less(x, self.critical_value)
#..............................................................................
class _MaskedUnaryOperation:
"""
Defines masked version of unary operations, where invalid values are
pre-masked.
Parameters
----------
mufunc : callable
The function for which to define a masked version. Made available
as ``_MaskedUnaryOperation.f``.
fill : scalar, optional
Filling value, default is 0.
domain : class instance
Domain for the function. Should be one of the ``_Domain*``
classes. Default is None.
"""
def __init__ (self, mufunc, fill=0, domain=None):
""" _MaskedUnaryOperation(aufunc, fill=0, domain=None)
aufunc(fill) must be defined
self(x) returns aufunc(x)
with masked values where domain(x) is true or getmask(x) is true.
"""
self.f = mufunc
self.fill = fill
self.domain = domain
self.__doc__ = getattr(mufunc, "__doc__", str(mufunc))
self.__name__ = getattr(mufunc, "__name__", str(mufunc))
ufunc_domain[mufunc] = domain
ufunc_fills[mufunc] = fill
#
def __call__ (self, a, *args, **kwargs):
"Execute the call behavior."
d = getdata(a)
# Case 1.1. : Domained function
if self.domain is not None:
# Save the error status
err_status_ini = np.geterr()
try:
np.seterr(divide='ignore', invalid='ignore')
result = self.f(d, *args, **kwargs)
finally:
np.seterr(**err_status_ini)
# Make a mask
m = ~umath.isfinite(result)
m |= self.domain(d)
m |= getmask(a)
# Case 1.2. : Function without a domain
else:
# Get the result and the mask
result = self.f(d, *args, **kwargs)
m = getmask(a)
# Case 2.1. : The result is scalarscalar
if not result.ndim:
if m:
return masked
return result
# Case 2.2. The result is an array
# We need to fill the invalid data back w/ the input
# Now, that's plain silly: in C, we would just skip the element and keep
# the original, but we do have to do it that way in Python
if m is not nomask:
# In case result has a lower dtype than the inputs (as in equal)
try:
np.copyto(result, d, where=m)
except TypeError:
pass
# Transform to
if isinstance(a, MaskedArray):
subtype = type(a)
else:
subtype = MaskedArray
result = result.view(subtype)
result._mask = m
result._update_from(a)
return result
#
def __str__ (self):
return "Masked version of %s. [Invalid values are masked]" % str(self.f)
class _MaskedBinaryOperation:
"""
Define masked version of binary operations, where invalid
values are pre-masked.
Parameters
----------
mbfunc : function
The function for which to define a masked version. Made available
as ``_MaskedBinaryOperation.f``.
domain : class instance
Default domain for the function. Should be one of the ``_Domain*``
classes. Default is None.
fillx : scalar, optional
Filling value for the first argument, default is 0.
filly : scalar, optional
Filling value for the second argument, default is 0.
"""
def __init__ (self, mbfunc, fillx=0, filly=0):
"""abfunc(fillx, filly) must be defined.
abfunc(x, filly) = x for all x to enable reduce.
"""
self.f = mbfunc
self.fillx = fillx
self.filly = filly
self.__doc__ = getattr(mbfunc, "__doc__", str(mbfunc))
self.__name__ = getattr(mbfunc, "__name__", str(mbfunc))
ufunc_domain[mbfunc] = None
ufunc_fills[mbfunc] = (fillx, filly)
def __call__ (self, a, b, *args, **kwargs):
"Execute the call behavior."
# Get the data, as ndarray
(da, db) = (getdata(a, subok=False), getdata(b, subok=False))
# Get the mask
(ma, mb) = (getmask(a), getmask(b))
if ma is nomask:
if mb is nomask:
m = nomask
else:
m = umath.logical_or(getmaskarray(a), mb)
elif mb is nomask:
m = umath.logical_or(ma, getmaskarray(b))
else:
m = umath.logical_or(ma, mb)
# Get the result
err_status_ini = np.geterr()
try:
np.seterr(divide='ignore', invalid='ignore')
result = self.f(da, db, *args, **kwargs)
finally:
np.seterr(**err_status_ini)
# Case 1. : scalar
if not result.ndim:
if m:
return masked
return result
# Case 2. : array
# Revert result to da where masked
if m.any():
np.copyto(result, 0, casting='unsafe', where=m)
# This only makes sense if the operation preserved the dtype
if result.dtype == da.dtype:
result += m * da
# Transforms to a (subclass of) MaskedArray
result = result.view(get_masked_subclass(a, b))
result._mask = m
# Update the optional info from the inputs
if isinstance(b, MaskedArray):
if isinstance(a, MaskedArray):
result._update_from(a)
else:
result._update_from(b)
elif isinstance(a, MaskedArray):
result._update_from(a)
return result
def reduce(self, target, axis=0, dtype=None):
"""Reduce `target` along the given `axis`."""
if isinstance(target, MaskedArray):
tclass = type(target)
else:
tclass = MaskedArray
m = getmask(target)
t = filled(target, self.filly)
if t.shape == ():
t = t.reshape(1)
if m is not nomask:
m = make_mask(m, copy=1)
m.shape = (1,)
if m is nomask:
return self.f.reduce(t, axis).view(tclass)
t = t.view(tclass)
t._mask = m
tr = self.f.reduce(getdata(t), axis, dtype=dtype or t.dtype)
mr = umath.logical_and.reduce(m, axis)
tr = tr.view(tclass)
if mr.ndim > 0:
tr._mask = mr
return tr
elif mr:
return masked
return tr
def outer (self, a, b):
"""Return the function applied to the outer product of a and b.
"""
ma = getmask(a)
mb = getmask(b)
if ma is nomask and mb is nomask:
m = nomask
else:
ma = getmaskarray(a)
mb = getmaskarray(b)
m = umath.logical_or.outer(ma, mb)
if (not m.ndim) and m:
return masked
(da, db) = (getdata(a), getdata(b))
d = self.f.outer(da, db)
if m is not nomask:
np.copyto(d, da, where=m)
if d.shape:
d = d.view(get_masked_subclass(a, b))
d._mask = m
return d
def accumulate (self, target, axis=0):
"""Accumulate `target` along `axis` after filling with y fill
value.
"""
if isinstance(target, MaskedArray):
tclass = type(target)
else:
tclass = MaskedArray
t = filled(target, self.filly)
return self.f.accumulate(t, axis).view(tclass)
def __str__ (self):
return "Masked version of " + str(self.f)
class _DomainedBinaryOperation:
"""
Define binary operations that have a domain, like divide.
They have no reduce, outer or accumulate.
Parameters
----------
mbfunc : function
The function for which to define a masked version. Made available
as ``_DomainedBinaryOperation.f``.
domain : class instance
Default domain for the function. Should be one of the ``_Domain*``
classes.
fillx : scalar, optional
Filling value for the first argument, default is 0.
filly : scalar, optional
Filling value for the second argument, default is 0.
"""
def __init__ (self, dbfunc, domain, fillx=0, filly=0):
"""abfunc(fillx, filly) must be defined.
abfunc(x, filly) = x for all x to enable reduce.
"""
self.f = dbfunc
self.domain = domain
self.fillx = fillx
self.filly = filly
self.__doc__ = getattr(dbfunc, "__doc__", str(dbfunc))
self.__name__ = getattr(dbfunc, "__name__", str(dbfunc))
ufunc_domain[dbfunc] = domain
ufunc_fills[dbfunc] = (fillx, filly)
def __call__(self, a, b, *args, **kwargs):
"Execute the call behavior."
# Get the data and the mask
(da, db) = (getdata(a, subok=False), getdata(b, subok=False))
(ma, mb) = (getmask(a), getmask(b))
# Get the result
err_status_ini = np.geterr()
try:
np.seterr(divide='ignore', invalid='ignore')
result = self.f(da, db, *args, **kwargs)
finally:
np.seterr(**err_status_ini)
# Get the mask as a combination of ma, mb and invalid
m = ~umath.isfinite(result)
m |= ma
m |= mb
# Apply the domain
domain = ufunc_domain.get(self.f, None)
if domain is not None:
m |= filled(domain(da, db), True)
# Take care of the scalar case first
if (not m.ndim):
if m:
return masked
else:
return result
# When the mask is True, put back da
np.copyto(result, 0, casting='unsafe', where=m)
result += m * da
result = result.view(get_masked_subclass(a, b))
result._mask = m
if isinstance(b, MaskedArray):
if isinstance(a, MaskedArray):
result._update_from(a)
else:
result._update_from(b)
elif isinstance(a, MaskedArray):
result._update_from(a)
return result
def __str__ (self):
return "Masked version of " + str(self.f)
#..............................................................................
# Unary ufuncs
exp = _MaskedUnaryOperation(umath.exp)
conjugate = _MaskedUnaryOperation(umath.conjugate)
sin = _MaskedUnaryOperation(umath.sin)
cos = _MaskedUnaryOperation(umath.cos)
tan = _MaskedUnaryOperation(umath.tan)
arctan = _MaskedUnaryOperation(umath.arctan)
arcsinh = _MaskedUnaryOperation(umath.arcsinh)
sinh = _MaskedUnaryOperation(umath.sinh)
cosh = _MaskedUnaryOperation(umath.cosh)
tanh = _MaskedUnaryOperation(umath.tanh)
abs = absolute = _MaskedUnaryOperation(umath.absolute)
angle = _MaskedUnaryOperation(angle) # from numpy.lib.function_base
fabs = _MaskedUnaryOperation(umath.fabs)
negative = _MaskedUnaryOperation(umath.negative)
floor = _MaskedUnaryOperation(umath.floor)
ceil = _MaskedUnaryOperation(umath.ceil)
around = _MaskedUnaryOperation(np.round_)
logical_not = _MaskedUnaryOperation(umath.logical_not)
# Domained unary ufuncs .......................................................
sqrt = _MaskedUnaryOperation(umath.sqrt, 0.0,
_DomainGreaterEqual(0.0))
log = _MaskedUnaryOperation(umath.log, 1.0,
_DomainGreater(0.0))
log2 = _MaskedUnaryOperation(umath.log2, 1.0,
_DomainGreater(0.0))
log10 = _MaskedUnaryOperation(umath.log10, 1.0,
_DomainGreater(0.0))
tan = _MaskedUnaryOperation(umath.tan, 0.0,
_DomainTan(1e-35))
arcsin = _MaskedUnaryOperation(umath.arcsin, 0.0,
_DomainCheckInterval(-1.0, 1.0))
arccos = _MaskedUnaryOperation(umath.arccos, 0.0,
_DomainCheckInterval(-1.0, 1.0))
arccosh = _MaskedUnaryOperation(umath.arccosh, 1.0,
_DomainGreaterEqual(1.0))
arctanh = _MaskedUnaryOperation(umath.arctanh, 0.0,
_DomainCheckInterval(-1.0 + 1e-15, 1.0 - 1e-15))
# Binary ufuncs ...............................................................
add = _MaskedBinaryOperation(umath.add)
subtract = _MaskedBinaryOperation(umath.subtract)
multiply = _MaskedBinaryOperation(umath.multiply, 1, 1)
arctan2 = _MaskedBinaryOperation(umath.arctan2, 0.0, 1.0)
equal = _MaskedBinaryOperation(umath.equal)
equal.reduce = None
not_equal = _MaskedBinaryOperation(umath.not_equal)
not_equal.reduce = None
less_equal = _MaskedBinaryOperation(umath.less_equal)
less_equal.reduce = None
greater_equal = _MaskedBinaryOperation(umath.greater_equal)
greater_equal.reduce = None
less = _MaskedBinaryOperation(umath.less)
less.reduce = None
greater = _MaskedBinaryOperation(umath.greater)
greater.reduce = None
logical_and = _MaskedBinaryOperation(umath.logical_and)
alltrue = _MaskedBinaryOperation(umath.logical_and, 1, 1).reduce
logical_or = _MaskedBinaryOperation(umath.logical_or)
sometrue = logical_or.reduce
logical_xor = _MaskedBinaryOperation(umath.logical_xor)
bitwise_and = _MaskedBinaryOperation(umath.bitwise_and)
bitwise_or = _MaskedBinaryOperation(umath.bitwise_or)
bitwise_xor = _MaskedBinaryOperation(umath.bitwise_xor)
hypot = _MaskedBinaryOperation(umath.hypot)
# Domained binary ufuncs ......................................................
divide = _DomainedBinaryOperation(umath.divide, _DomainSafeDivide(), 0, 1)
true_divide = _DomainedBinaryOperation(umath.true_divide,
_DomainSafeDivide(), 0, 1)
floor_divide = _DomainedBinaryOperation(umath.floor_divide,
_DomainSafeDivide(), 0, 1)
remainder = _DomainedBinaryOperation(umath.remainder,
_DomainSafeDivide(), 0, 1)
fmod = _DomainedBinaryOperation(umath.fmod, _DomainSafeDivide(), 0, 1)
mod = _DomainedBinaryOperation(umath.mod, _DomainSafeDivide(), 0, 1)
#####--------------------------------------------------------------------------
#---- --- Mask creation functions ---
#####--------------------------------------------------------------------------
def _recursive_make_descr(datatype, newtype=bool_):
"Private function allowing recursion in make_descr."
# Do we have some name fields ?
if datatype.names:
descr = []
for name in datatype.names:
field = datatype.fields[name]
if len(field) == 3:
# Prepend the title to the name
name = (field[-1], name)
descr.append((name, _recursive_make_descr(field[0], newtype)))
return descr
# Is this some kind of composite a la (np.float,2)
elif datatype.subdtype:
mdescr = list(datatype.subdtype)
mdescr[0] = newtype
return tuple(mdescr)
else:
return newtype
def make_mask_descr(ndtype):
"""
Construct a dtype description list from a given dtype.
Returns a new dtype object, with the type of all fields in `ndtype` to a
boolean type. Field names are not altered.
Parameters
----------
ndtype : dtype
The dtype to convert.
Returns
-------
result : dtype
A dtype that looks like `ndtype`, the type of all fields is boolean.
Examples
--------
>>> import numpy.ma as ma
>>> dtype = np.dtype({'names':['foo', 'bar'],
'formats':[np.float32, np.int]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i4')])
>>> ma.make_mask_descr(dtype)
dtype([('foo', '|b1'), ('bar', '|b1')])
>>> ma.make_mask_descr(np.float32)
<type 'numpy.bool_'>
"""
# Make sure we do have a dtype
if not isinstance(ndtype, np.dtype):
ndtype = np.dtype(ndtype)
return np.dtype(_recursive_make_descr(ndtype, np.bool))
def getmask(a):
"""
Return the mask of a masked array, or nomask.
Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the
mask is not `nomask`, else return `nomask`. To guarantee a full array
of booleans of the same shape as a, use `getmaskarray`.
Parameters
----------
a : array_like
Input `MaskedArray` for which the mask is required.
See Also
--------
getdata : Return the data of a masked array as an ndarray.
getmaskarray : Return the mask of a masked array, or full array of False.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(data =
[[1 --]
[3 4]],
mask =
[[False True]
[False False]],
fill_value=999999)
>>> ma.getmask(a)
array([[False, True],
[False, False]], dtype=bool)
Equivalently use the `MaskedArray` `mask` attribute.
>>> a.mask
array([[False, True],
[False, False]], dtype=bool)
Result when mask == `nomask`
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True
"""
return getattr(a, '_mask', nomask)
get_mask = getmask
def getmaskarray(arr):
"""
Return the mask of a masked array, or full boolean array of False.
Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and
the mask is not `nomask`, else return a full boolean array of False of
the same shape as `arr`.
Parameters
----------
arr : array_like
Input `MaskedArray` for which the mask is required.
See Also
--------
getmask : Return the mask of a masked array, or nomask.
getdata : Return the data of a masked array as an ndarray.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(data =
[[1 --]
[3 4]],
mask =
[[False True]
[False False]],
fill_value=999999)
>>> ma.getmaskarray(a)
array([[False, True],
[False, False]], dtype=bool)
Result when mask == ``nomask``
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> >ma.getmaskarray(b)
array([[False, False],
[False, False]], dtype=bool)
"""
mask = getmask(arr)
if mask is nomask:
mask = make_mask_none(np.shape(arr), getdata(arr).dtype)
return mask
def is_mask(m):
"""
Return True if m is a valid, standard mask.
This function does not check the contents of the input, only that the
type is MaskType. In particular, this function returns False if the
mask has a flexible dtype.
Parameters
----------
m : array_like
Array to test.
Returns
-------
result : bool
True if `m.dtype.type` is MaskType, False otherwise.
See Also
--------
isMaskedArray : Test whether input is an instance of MaskedArray.
Examples
--------
>>> import numpy.ma as ma
>>> m = ma.masked_equal([0, 1, 0, 2, 3], 0)
>>> m
masked_array(data = [-- 1 -- 2 3],
mask = [ True False True False False],
fill_value=999999)
>>> ma.is_mask(m)
False
>>> ma.is_mask(m.mask)
True
Input must be an ndarray (or have similar attributes)
for it to be considered a valid mask.
>>> m = [False, True, False]
>>> ma.is_mask(m)
False
>>> m = np.array([False, True, False])
>>> m
array([False, True, False], dtype=bool)
>>> ma.is_mask(m)
True
Arrays with complex dtypes don't return True.
>>> dtype = np.dtype({'names':['monty', 'pithon'],
'formats':[np.bool, np.bool]})
>>> dtype
dtype([('monty', '|b1'), ('pithon', '|b1')])
>>> m = np.array([(True, False), (False, True), (True, False)],
dtype=dtype)
>>> m
array([(True, False), (False, True), (True, False)],
dtype=[('monty', '|b1'), ('pithon', '|b1')])
>>> ma.is_mask(m)
False
"""
try:
return m.dtype.type is MaskType
except AttributeError:
return False
def make_mask(m, copy=False, shrink=True, dtype=MaskType):
"""
Create a boolean mask from an array.
Return `m` as a boolean mask, creating a copy if necessary or requested.
The function can accept any sequence that is convertible to integers,
or ``nomask``. Does not require that contents must be 0s and 1s, values
of 0 are interepreted as False, everything else as True.
Parameters
----------
m : array_like
Potential mask.
copy : bool, optional
Whether to return a copy of `m` (True) or `m` itself (False).
shrink : bool, optional
Whether to shrink `m` to ``nomask`` if all its values are False.
dtype : dtype, optional
Data-type of the output mask. By default, the output mask has
a dtype of MaskType (bool). If the dtype is flexible, each field
has a boolean dtype.
Returns
-------
result : ndarray
A boolean mask derived from `m`.
Examples
--------
>>> import numpy.ma as ma
>>> m = [True, False, True, True]
>>> ma.make_mask(m)
array([ True, False, True, True], dtype=bool)
>>> m = [1, 0, 1, 1]
>>> ma.make_mask(m)
array([ True, False, True, True], dtype=bool)
>>> m = [1, 0, 2, -3]
>>> ma.make_mask(m)
array([ True, False, True, True], dtype=bool)
Effect of the `shrink` parameter.
>>> m = np.zeros(4)
>>> m
array([ 0., 0., 0., 0.])
>>> ma.make_mask(m)
False
>>> ma.make_mask(m, shrink=False)
array([False, False, False, False], dtype=bool)
Using a flexible `dtype`.
>>> m = [1, 0, 1, 1]
>>> n = [0, 1, 0, 0]
>>> arr = []
>>> for man, mouse in zip(m, n):
... arr.append((man, mouse))
>>> arr
[(1, 0), (0, 1), (1, 0), (1, 0)]
>>> dtype = np.dtype({'names':['man', 'mouse'],
'formats':[np.int, np.int]})
>>> arr = np.array(arr, dtype=dtype)
>>> arr
array([(1, 0), (0, 1), (1, 0), (1, 0)],
dtype=[('man', '<i4'), ('mouse', '<i4')])
>>> ma.make_mask(arr, dtype=dtype)
array([(True, False), (False, True), (True, False), (True, False)],
dtype=[('man', '|b1'), ('mouse', '|b1')])
"""
if m is nomask:
return nomask
elif isinstance(m, ndarray):
# We won't return after this point to make sure we can shrink the mask
# Fill the mask in case there are missing data
m = filled(m, True)
# Make sure the input dtype is valid
dtype = make_mask_descr(dtype)
if m.dtype == dtype:
if copy:
result = m.copy()
else:
result = m
else:
result = np.array(m, dtype=dtype, copy=copy)
else:
result = np.array(filled(m, True), dtype=MaskType)
# Bas les masques !
if shrink and (not result.dtype.names) and (not result.any()):
return nomask
else:
return result
def make_mask_none(newshape, dtype=None):
"""
Return a boolean mask of the given shape, filled with False.
This function returns a boolean ndarray with all entries False, that can
be used in common mask manipulations. If a complex dtype is specified, the
type of each field is converted to a boolean type.
Parameters
----------
newshape : tuple
A tuple indicating the shape of the mask.
dtype: {None, dtype}, optional
If None, use a MaskType instance. Otherwise, use a new datatype with
the same fields as `dtype`, converted to boolean types.
Returns
-------
result : ndarray
An ndarray of appropriate shape and dtype, filled with False.
See Also
--------
make_mask : Create a boolean mask from an array.
make_mask_descr : Construct a dtype description list from a given dtype.
Examples
--------
>>> import numpy.ma as ma
>>> ma.make_mask_none((3,))
array([False, False, False], dtype=bool)
Defining a more complex dtype.
>>> dtype = np.dtype({'names':['foo', 'bar'],
'formats':[np.float32, np.int]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i4')])
>>> ma.make_mask_none((3,), dtype=dtype)
array([(False, False), (False, False), (False, False)],
dtype=[('foo', '|b1'), ('bar', '|b1')])
"""
if dtype is None:
result = np.zeros(newshape, dtype=MaskType)
else:
result = np.zeros(newshape, dtype=make_mask_descr(dtype))
return result
def mask_or (m1, m2, copy=False, shrink=True):
"""
Combine two masks with the ``logical_or`` operator.
The result may be a view on `m1` or `m2` if the other is `nomask`
(i.e. False).
Parameters
----------
m1, m2 : array_like
Input masks.
copy : bool, optional
If copy is False and one of the inputs is `nomask`, return a view
of the other input mask. Defaults to False.
shrink : bool, optional
Whether to shrink the output to `nomask` if all its values are
False. Defaults to True.
Returns
-------
mask : output mask
The result masks values that are masked in either `m1` or `m2`.
Raises
------
ValueError
If `m1` and `m2` have different flexible dtypes.
Examples
--------
>>> m1 = np.ma.make_mask([0, 1, 1, 0])
>>> m2 = np.ma.make_mask([1, 0, 0, 0])
>>> np.ma.mask_or(m1, m2)
array([ True, True, True, False], dtype=bool)
"""
def _recursive_mask_or(m1, m2, newmask):
names = m1.dtype.names
for name in names:
current1 = m1[name]
if current1.dtype.names:
_recursive_mask_or(current1, m2[name], newmask[name])
else:
umath.logical_or(current1, m2[name], newmask[name])
return
#
if (m1 is nomask) or (m1 is False):
dtype = getattr(m2, 'dtype', MaskType)
return make_mask(m2, copy=copy, shrink=shrink, dtype=dtype)
if (m2 is nomask) or (m2 is False):
dtype = getattr(m1, 'dtype', MaskType)
return make_mask(m1, copy=copy, shrink=shrink, dtype=dtype)
if m1 is m2 and is_mask(m1):
return m1
(dtype1, dtype2) = (getattr(m1, 'dtype', None), getattr(m2, 'dtype', None))
if (dtype1 != dtype2):
raise ValueError("Incompatible dtypes '%s'<>'%s'" % (dtype1, dtype2))
if dtype1.names:
newmask = np.empty_like(m1)
_recursive_mask_or(m1, m2, newmask)
return newmask
return make_mask(umath.logical_or(m1, m2), copy=copy, shrink=shrink)
def flatten_mask(mask):
"""
Returns a completely flattened version of the mask, where nested fields
are collapsed.
Parameters
----------
mask : array_like
Input array, which will be interpreted as booleans.
Returns
-------
flattened_mask : ndarray of bools
The flattened input.
Examples
--------
>>> mask = np.array([0, 0, 1], dtype=np.bool)
>>> flatten_mask(mask)
array([False, False, True], dtype=bool)
>>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
>>> flatten_mask(mask)
array([False, False, False, True], dtype=bool)
>>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
>>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype)
>>> flatten_mask(mask)
array([False, False, False, False, False, True], dtype=bool)
"""
#
def _flatmask(mask):
"Flatten the mask and returns a (maybe nested) sequence of booleans."
mnames = mask.dtype.names
if mnames:
return [flatten_mask(mask[name]) for name in mnames]
else:
return mask
#
def _flatsequence(sequence):
"Generates a flattened version of the sequence."
try:
for element in sequence:
if hasattr(element, '__iter__'):
for f in _flatsequence(element):
yield f
else:
yield element
except TypeError:
yield sequence
#
mask = np.asarray(mask)
flattened = _flatsequence(_flatmask(mask))
return np.array([_ for _ in flattened], dtype=bool)
def _check_mask_axis(mask, axis):
"Check whether there are masked values along the given axis"
if mask is not nomask:
return mask.all(axis=axis)
return nomask
#####--------------------------------------------------------------------------
#--- --- Masking functions ---
#####--------------------------------------------------------------------------
def masked_where(condition, a, copy=True):
"""
Mask an array where a condition is met.
Return `a` as an array masked where `condition` is True.
Any masked values of `a` or `condition` are also masked in the output.
Parameters
----------
condition : array_like
Masking condition. When `condition` tests floating point values for
equality, consider using ``masked_values`` instead.
a : array_like
Array to mask.
copy : bool
If True (default) make a copy of `a` in the result. If False modify
`a` in place and return a view.
Returns
-------
result : MaskedArray
The result of masking `a` where `condition` is True.
See Also
--------
masked_values : Mask using floating point equality.
masked_equal : Mask where equal to a given value.
masked_not_equal : Mask where `not` equal to a given value.
masked_less_equal : Mask where less than or equal to a given value.
masked_greater_equal : Mask where greater than or equal to a given value.
masked_less : Mask where less than a given value.
masked_greater : Mask where greater than a given value.
masked_inside : Mask inside a given interval.
masked_outside : Mask outside a given interval.
masked_invalid : Mask invalid values (NaNs or infs).
Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_where(a <= 2, a)
masked_array(data = [-- -- -- 3],
mask = [ True True True False],
fill_value=999999)
Mask array `b` conditional on `a`.
>>> b = ['a', 'b', 'c', 'd']
>>> ma.masked_where(a == 2, b)
masked_array(data = [a b -- d],
mask = [False False True False],
fill_value=N/A)
Effect of the `copy` argument.
>>> c = ma.masked_where(a <= 2, a)
>>> c
masked_array(data = [-- -- -- 3],
mask = [ True True True False],
fill_value=999999)
>>> c[0] = 99
>>> c
masked_array(data = [99 -- -- 3],
mask = [False True True False],
fill_value=999999)
>>> a
array([0, 1, 2, 3])
>>> c = ma.masked_where(a <= 2, a, copy=False)
>>> c[0] = 99
>>> c
masked_array(data = [99 -- -- 3],
mask = [False True True False],
fill_value=999999)
>>> a
array([99, 1, 2, 3])
When `condition` or `a` contain masked values.
>>> a = np.arange(4)
>>> a = ma.masked_where(a == 2, a)
>>> a
masked_array(data = [0 1 -- 3],
mask = [False False True False],
fill_value=999999)
>>> b = np.arange(4)
>>> b = ma.masked_where(b == 0, b)
>>> b
masked_array(data = [-- 1 2 3],
mask = [ True False False False],
fill_value=999999)
>>> ma.masked_where(a == 3, b)
masked_array(data = [-- 1 -- --],
mask = [ True False True True],
fill_value=999999)
"""
# Make sure that condition is a valid standard-type mask.
cond = make_mask(condition)
a = np.array(a, copy=copy, subok=True)
(cshape, ashape) = (cond.shape, a.shape)
if cshape and cshape != ashape:
raise IndexError("Inconsistant shape between the condition and the input"
" (got %s and %s)" % (cshape, ashape))
if hasattr(a, '_mask'):
cond = mask_or(cond, a._mask)
cls = type(a)
else:
cls = MaskedArray
result = a.view(cls)
result._mask = cond
return result
def masked_greater(x, value, copy=True):
"""
Mask an array where greater than a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x > value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_greater(a, 2)
masked_array(data = [0 1 2 --],
mask = [False False False True],
fill_value=999999)
"""
return masked_where(greater(x, value), x, copy=copy)
def masked_greater_equal(x, value, copy=True):
"""
Mask an array where greater than or equal to a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x >= value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_greater_equal(a, 2)
masked_array(data = [0 1 -- --],
mask = [False False True True],
fill_value=999999)
"""
return masked_where(greater_equal(x, value), x, copy=copy)
def masked_less(x, value, copy=True):
"""
Mask an array where less than a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x < value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_less(a, 2)
masked_array(data = [-- -- 2 3],
mask = [ True True False False],
fill_value=999999)
"""
return masked_where(less(x, value), x, copy=copy)
def masked_less_equal(x, value, copy=True):
"""
Mask an array where less than or equal to a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x <= value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_less_equal(a, 2)
masked_array(data = [-- -- -- 3],
mask = [ True True True False],
fill_value=999999)
"""
return masked_where(less_equal(x, value), x, copy=copy)
def masked_not_equal(x, value, copy=True):
"""
Mask an array where `not` equal to a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x != value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_not_equal(a, 2)
masked_array(data = [-- -- 2 --],
mask = [ True True False True],
fill_value=999999)
"""
return masked_where(not_equal(x, value), x, copy=copy)
def masked_equal(x, value, copy=True):
"""
Mask an array where equal to a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x == value). For floating point arrays,
consider using ``masked_values(x, value)``.
See Also
--------
masked_where : Mask where a condition is met.
masked_values : Mask using floating point equality.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_equal(a, 2)
masked_array(data = [0 1 -- 3],
mask = [False False True False],
fill_value=999999)
"""
# An alternative implementation relies on filling first: probably not needed.
# d = filled(x, 0)
# c = umath.equal(d, value)
# m = mask_or(c, getmask(x))
# return array(d, mask=m, copy=copy)
output = masked_where(equal(x, value), x, copy=copy)
output.fill_value = value
return output
def masked_inside(x, v1, v2, copy=True):
"""
Mask an array inside a given interval.
Shortcut to ``masked_where``, where `condition` is True for `x` inside
the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2`
can be given in either order.
See Also
--------
masked_where : Mask where a condition is met.
Notes
-----
The array `x` is prefilled with its filling value.
Examples
--------
>>> import numpy.ma as ma
>>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
>>> ma.masked_inside(x, -0.3, 0.3)
masked_array(data = [0.31 1.2 -- -- -0.4 -1.1],
mask = [False False True True False False],
fill_value=1e+20)
The order of `v1` and `v2` doesn't matter.
>>> ma.masked_inside(x, 0.3, -0.3)
masked_array(data = [0.31 1.2 -- -- -0.4 -1.1],
mask = [False False True True False False],
fill_value=1e+20)
"""
if v2 < v1:
(v1, v2) = (v2, v1)
xf = filled(x)
condition = (xf >= v1) & (xf <= v2)
return masked_where(condition, x, copy=copy)
def masked_outside(x, v1, v2, copy=True):
"""
Mask an array outside a given interval.
Shortcut to ``masked_where``, where `condition` is True for `x` outside
the interval [v1,v2] (x < v1)|(x > v2).
The boundaries `v1` and `v2` can be given in either order.
See Also
--------
masked_where : Mask where a condition is met.
Notes
-----
The array `x` is prefilled with its filling value.
Examples
--------
>>> import numpy.ma as ma
>>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
>>> ma.masked_outside(x, -0.3, 0.3)
masked_array(data = [-- -- 0.01 0.2 -- --],
mask = [ True True False False True True],
fill_value=1e+20)
The order of `v1` and `v2` doesn't matter.
>>> ma.masked_outside(x, 0.3, -0.3)
masked_array(data = [-- -- 0.01 0.2 -- --],
mask = [ True True False False True True],
fill_value=1e+20)
"""
if v2 < v1:
(v1, v2) = (v2, v1)
xf = filled(x)
condition = (xf < v1) | (xf > v2)
return masked_where(condition, x, copy=copy)
def masked_object(x, value, copy=True, shrink=True):
"""
Mask the array `x` where the data are exactly equal to value.
This function is similar to `masked_values`, but only suitable
for object arrays: for floating point, use `masked_values` instead.
Parameters
----------
x : array_like
Array to mask
value : object
Comparison value
copy : {True, False}, optional
Whether to return a copy of `x`.
shrink : {True, False}, optional
Whether to collapse a mask full of False to nomask
Returns
-------
result : MaskedArray
The result of masking `x` where equal to `value`.
See Also
--------
masked_where : Mask where a condition is met.
masked_equal : Mask where equal to a given value (integers).
masked_values : Mask using floating point equality.
Examples
--------
>>> import numpy.ma as ma
>>> food = np.array(['green_eggs', 'ham'], dtype=object)
>>> # don't eat spoiled food
>>> eat = ma.masked_object(food, 'green_eggs')
>>> print eat
[-- ham]
>>> # plain ol` ham is boring
>>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object)
>>> eat = ma.masked_object(fresh_food, 'green_eggs')
>>> print eat
[cheese ham pineapple]
Note that `mask` is set to ``nomask`` if possible.
>>> eat
masked_array(data = [cheese ham pineapple],
mask = False,
fill_value=?)
"""
if isMaskedArray(x):
condition = umath.equal(x._data, value)
mask = x._mask
else:
condition = umath.equal(np.asarray(x), value)
mask = nomask
mask = mask_or(mask, make_mask(condition, shrink=shrink))
return masked_array(x, mask=mask, copy=copy, fill_value=value)
def masked_values(x, value, rtol=1e-5, atol=1e-8, copy=True, shrink=True):
"""
Mask using floating point equality.
Return a MaskedArray, masked where the data in array `x` are approximately
equal to `value`, i.e. where the following condition is True
(abs(x - value) <= atol+rtol*abs(value))
The fill_value is set to `value` and the mask is set to ``nomask`` if
possible. For integers, consider using ``masked_equal``.
Parameters
----------
x : array_like
Array to mask.
value : float
Masking value.
rtol : float, optional
Tolerance parameter.
atol : float, optional
Tolerance parameter (1e-8).
copy : bool, optional
Whether to return a copy of `x`.
shrink : bool, optional
Whether to collapse a mask full of False to ``nomask``.
Returns
-------
result : MaskedArray
The result of masking `x` where approximately equal to `value`.
See Also
--------
masked_where : Mask where a condition is met.
masked_equal : Mask where equal to a given value (integers).
Examples
--------
>>> import numpy.ma as ma
>>> x = np.array([1, 1.1, 2, 1.1, 3])
>>> ma.masked_values(x, 1.1)
masked_array(data = [1.0 -- 2.0 -- 3.0],
mask = [False True False True False],
fill_value=1.1)
Note that `mask` is set to ``nomask`` if possible.
>>> ma.masked_values(x, 1.5)
masked_array(data = [ 1. 1.1 2. 1.1 3. ],
mask = False,
fill_value=1.5)
For integers, the fill value will be different in general to the
result of ``masked_equal``.
>>> x = np.arange(5)
>>> x
array([0, 1, 2, 3, 4])
>>> ma.masked_values(x, 2)
masked_array(data = [0 1 -- 3 4],
mask = [False False True False False],
fill_value=2)
>>> ma.masked_equal(x, 2)
masked_array(data = [0 1 -- 3 4],
mask = [False False True False False],
fill_value=999999)
"""
mabs = umath.absolute
xnew = filled(x, value)
if issubclass(xnew.dtype.type, np.floating):
condition = umath.less_equal(mabs(xnew - value), atol + rtol * mabs(value))
mask = getattr(x, '_mask', nomask)
else:
condition = umath.equal(xnew, value)
mask = nomask
mask = mask_or(mask, make_mask(condition, shrink=shrink))
return masked_array(xnew, mask=mask, copy=copy, fill_value=value)
def masked_invalid(a, copy=True):
"""
Mask an array where invalid values occur (NaNs or infs).
This function is a shortcut to ``masked_where``, with
`condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved.
Only applies to arrays with a dtype where NaNs or infs make sense
(i.e. floating point types), but accepts any array_like object.
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(5, dtype=np.float)
>>> a[2] = np.NaN
>>> a[3] = np.PINF
>>> a
array([ 0., 1., NaN, Inf, 4.])
>>> ma.masked_invalid(a)
masked_array(data = [0.0 1.0 -- -- 4.0],
mask = [False False True True False],
fill_value=1e+20)
"""
a = np.array(a, copy=copy, subok=True)
mask = getattr(a, '_mask', None)
if mask is not None:
condition = ~(np.isfinite(getdata(a)))
if mask is not nomask:
condition |= mask
cls = type(a)
else:
condition = ~(np.isfinite(a))
cls = MaskedArray
result = a.view(cls)
result._mask = condition
return result
#####--------------------------------------------------------------------------
#---- --- Printing options ---
#####--------------------------------------------------------------------------
class _MaskedPrintOption:
"""
Handle the string used to represent missing data in a masked array.
"""
def __init__ (self, display):
"Create the masked_print_option object."
self._display = display
self._enabled = True
def display(self):
"Display the string to print for masked values."
return self._display
def set_display (self, s):
"Set the string to print for masked values."
self._display = s
def enabled(self):
"Is the use of the display value enabled?"
return self._enabled
def enable(self, shrink=1):
"Set the enabling shrink to `shrink`."
self._enabled = shrink
def __str__ (self):
return str(self._display)
__repr__ = __str__
#if you single index into a masked location you get this object.
masked_print_option = _MaskedPrintOption('--')
def _recursive_printoption(result, mask, printopt):
"""
Puts printoptions in result where mask is True.
Private function allowing for recursion
"""
names = result.dtype.names
for name in names:
(curdata, curmask) = (result[name], mask[name])
if curdata.dtype.names:
_recursive_printoption(curdata, curmask, printopt)
else:
np.copyto(curdata, printopt, where=curmask)
return
_print_templates = dict(long_std="""\
masked_%(name)s(data =
%(data)s,
%(nlen)s mask =
%(mask)s,
%(nlen)s fill_value = %(fill)s)
""",
short_std="""\
masked_%(name)s(data = %(data)s,
%(nlen)s mask = %(mask)s,
%(nlen)s fill_value = %(fill)s)
""",
long_flx="""\
masked_%(name)s(data =
%(data)s,
%(nlen)s mask =
%(mask)s,
%(nlen)s fill_value = %(fill)s,
%(nlen)s dtype = %(dtype)s)
""",
short_flx="""\
masked_%(name)s(data = %(data)s,
%(nlen)s mask = %(mask)s,
%(nlen)s fill_value = %(fill)s,
%(nlen)s dtype = %(dtype)s)
""")
#####--------------------------------------------------------------------------
#---- --- MaskedArray class ---
#####--------------------------------------------------------------------------
def _recursive_filled(a, mask, fill_value):
"""
Recursively fill `a` with `fill_value`.
Private function
"""
names = a.dtype.names
for name in names:
current = a[name]
if current.dtype.names:
_recursive_filled(current, mask[name], fill_value[name])
else:
np.copyto(current, fill_value[name], where=mask[name])
def flatten_structured_array(a):
"""
Flatten a structured array.
The data type of the output is chosen such that it can represent all of the
(nested) fields.
Parameters
----------
a : structured array
Returns
-------
output : masked array or ndarray
A flattened masked array if the input is a masked array, otherwise a
standard ndarray.
Examples
--------
>>> ndtype = [('a', int), ('b', float)]
>>> a = np.array([(1, 1), (2, 2)], dtype=ndtype)
>>> flatten_structured_array(a)
array([[1., 1.],
[2., 2.]])
"""
#
def flatten_sequence(iterable):
"""Flattens a compound of nested iterables."""
for elm in iter(iterable):
if hasattr(elm, '__iter__'):
for f in flatten_sequence(elm):
yield f
else:
yield elm
#
a = np.asanyarray(a)
inishape = a.shape
a = a.ravel()
if isinstance(a, MaskedArray):
out = np.array([tuple(flatten_sequence(d.item())) for d in a._data])
out = out.view(MaskedArray)
out._mask = np.array([tuple(flatten_sequence(d.item()))
for d in getmaskarray(a)])
else:
out = np.array([tuple(flatten_sequence(d.item())) for d in a])
if len(inishape) > 1:
newshape = list(out.shape)
newshape[0] = inishape
out.shape = tuple(flatten_sequence(newshape))
return out
class _arraymethod(object):
"""
Define a wrapper for basic array methods.
Upon call, returns a masked array, where the new ``_data`` array is
the output of the corresponding method called on the original
``_data``.
If `onmask` is True, the new mask is the output of the method called
on the initial mask. Otherwise, the new mask is just a reference
to the initial mask.
Attributes
----------
_onmask : bool
Holds the `onmask` parameter.
obj : object
The object calling `_arraymethod`.
Parameters
----------
funcname : str
Name of the function to apply on data.
onmask : bool
Whether the mask must be processed also (True) or left
alone (False). Default is True. Make available as `_onmask`
attribute.
"""
def __init__(self, funcname, onmask=True):
self.__name__ = funcname
self._onmask = onmask
self.obj = None
self.__doc__ = self.getdoc()
#
def getdoc(self):
"Return the doc of the function (from the doc of the method)."
methdoc = getattr(ndarray, self.__name__, None) or \
getattr(np, self.__name__, None)
if methdoc is not None:
return methdoc.__doc__
#
def __get__(self, obj, objtype=None):
self.obj = obj
return self
#
def __call__(self, *args, **params):
methodname = self.__name__
instance = self.obj
# Fallback : if the instance has not been initialized, use the first arg
if instance is None:
args = list(args)
instance = args.pop(0)
data = instance._data
mask = instance._mask
cls = type(instance)
result = getattr(data, methodname)(*args, **params).view(cls)
result._update_from(instance)
if result.ndim:
if not self._onmask:
result.__setmask__(mask)
elif mask is not nomask:
result.__setmask__(getattr(mask, methodname)(*args, **params))
else:
if mask.ndim and (not mask.dtype.names and mask.all()):
return masked
return result
class MaskedIterator(object):
"""
Flat iterator object to iterate over masked arrays.
A `MaskedIterator` iterator is returned by ``x.flat`` for any masked array
`x`. It allows iterating over the array as if it were a 1-D array,
either in a for-loop or by calling its `next` method.
Iteration is done in C-contiguous style, with the last index varying the
fastest. The iterator can also be indexed using basic slicing or
advanced indexing.
See Also
--------
MaskedArray.flat : Return a flat iterator over an array.
MaskedArray.flatten : Returns a flattened copy of an array.
Notes
-----
`MaskedIterator` is not exported by the `ma` module. Instead of
instantiating a `MaskedIterator` directly, use `MaskedArray.flat`.
Examples
--------
>>> x = np.ma.array(arange(6).reshape(2, 3))
>>> fl = x.flat
>>> type(fl)
<class 'numpy.ma.core.MaskedIterator'>
>>> for item in fl:
... print item
...
0
1
2
3
4
5
Extracting more than a single element b indexing the `MaskedIterator`
returns a masked array:
>>> fl[2:4]
masked_array(data = [2 3],
mask = False,
fill_value = 999999)
"""
def __init__(self, ma):
self.ma = ma
self.dataiter = ma._data.flat
#
if ma._mask is nomask:
self.maskiter = None
else:
self.maskiter = ma._mask.flat
def __iter__(self):
return self
def __getitem__(self, indx):
result = self.dataiter.__getitem__(indx).view(type(self.ma))
if self.maskiter is not None:
_mask = self.maskiter.__getitem__(indx)
_mask.shape = result.shape
result._mask = _mask
return result
### This won't work is ravel makes a copy
def __setitem__(self, index, value):
self.dataiter[index] = getdata(value)
if self.maskiter is not None:
self.maskiter[index] = getmaskarray(value)
def __next__(self):
"""
Return the next value, or raise StopIteration.
Examples
--------
>>> x = np.ma.array([3, 2], mask=[0, 1])
>>> fl = x.flat
>>> fl.next()
3
>>> fl.next()
masked_array(data = --,
mask = True,
fill_value = 1e+20)
>>> fl.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ralf/python/numpy/numpy/ma/core.py", line 2243, in next
d = self.dataiter.next()
StopIteration
"""
d = next(self.dataiter)
if self.maskiter is not None and next(self.maskiter):
d = masked
return d
class MaskedArray(ndarray):
"""
An array class with possibly masked values.
Masked values of True exclude the corresponding element from any
computation.
Construction::
x = MaskedArray(data, mask=nomask, dtype=None,
copy=False, subok=True, ndmin=0, fill_value=None,
keep_mask=True, hard_mask=None, shrink=True)
Parameters
----------
data : array_like
Input data.
mask : sequence, optional
Mask. Must be convertible to an array of booleans with the same
shape as `data`. True indicates a masked (i.e. invalid) data.
dtype : dtype, optional
Data type of the output.
If `dtype` is None, the type of the data argument (``data.dtype``)
is used. If `dtype` is not None and different from ``data.dtype``,
a copy is performed.
copy : bool, optional
Whether to copy the input data (True), or to use a reference instead.
Default is False.
subok : bool, optional
Whether to return a subclass of `MaskedArray` if possible (True) or a
plain `MaskedArray`. Default is True.
ndmin : int, optional
Minimum number of dimensions. Default is 0.
fill_value : scalar, optional
Value used to fill in the masked values when necessary.
If None, a default based on the data-type is used.
keep_mask : bool, optional
Whether to combine `mask` with the mask of the input data, if any
(True), or to use only `mask` for the output (False). Default is True.
hard_mask : bool, optional
Whether to use a hard mask or not. With a hard mask, masked values
cannot be unmasked. Default is False.
shrink : bool, optional
Whether to force compression of an empty mask. Default is True.
"""
__array_priority__ = 15
_defaultmask = nomask
_defaulthardmask = False
_baseclass = ndarray
def __new__(cls, data=None, mask=nomask, dtype=None, copy=False,
subok=True, ndmin=0, fill_value=None,
keep_mask=True, hard_mask=None, shrink=True,
**options):
"""
Create a new masked array from scratch.
Notes
-----
A masked array can also be created by taking a .view(MaskedArray).
"""
# Process data............
_data = np.array(data, dtype=dtype, copy=copy, subok=True, ndmin=ndmin)
_baseclass = getattr(data, '_baseclass', type(_data))
# Check that we're not erasing the mask..........
if isinstance(data, MaskedArray) and (data.shape != _data.shape):
copy = True
# Careful, cls might not always be MaskedArray...
if not isinstance(data, cls) or not subok:
_data = ndarray.view(_data, cls)
else:
_data = ndarray.view(_data, type(data))
# Backwards compatibility w/ numpy.core.ma .......
if hasattr(data, '_mask') and not isinstance(data, ndarray):
_data._mask = data._mask
_sharedmask = True
# Process mask ...............................
# Number of named fields (or zero if none)
names_ = _data.dtype.names or ()
# Type of the mask
if names_:
mdtype = make_mask_descr(_data.dtype)
else:
mdtype = MaskType
# Case 1. : no mask in input ............
if mask is nomask:
# Erase the current mask ?
if not keep_mask:
# With a reduced version
if shrink:
_data._mask = nomask
# With full version
else:
_data._mask = np.zeros(_data.shape, dtype=mdtype)
# Check whether we missed something
elif isinstance(data, (tuple, list)):
try:
# If data is a sequence of masked array
mask = np.array([getmaskarray(m) for m in data],
dtype=mdtype)
except ValueError:
# If data is nested
mask = nomask
# Force shrinking of the mask if needed (and possible)
if (mdtype == MaskType) and mask.any():
_data._mask = mask
_data._sharedmask = False
else:
if copy:
_data._mask = _data._mask.copy()
_data._sharedmask = False
# Reset the shape of the original mask
if getmask(data) is not nomask:
data._mask.shape = data.shape
else:
_data._sharedmask = True
# Case 2. : With a mask in input ........
else:
# Read the mask with the current mdtype
try:
mask = np.array(mask, copy=copy, dtype=mdtype)
# Or assume it's a sequence of bool/int
except TypeError:
mask = np.array([tuple([m] * len(mdtype)) for m in mask],
dtype=mdtype)
# Make sure the mask and the data have the same shape
if mask.shape != _data.shape:
(nd, nm) = (_data.size, mask.size)
if nm == 1:
mask = np.resize(mask, _data.shape)
elif nm == nd:
mask = np.reshape(mask, _data.shape)
else:
msg = "Mask and data not compatible: data size is %i, " + \
"mask size is %i."
raise MaskError(msg % (nd, nm))
copy = True
# Set the mask to the new value
if _data._mask is nomask:
_data._mask = mask
_data._sharedmask = not copy
else:
if not keep_mask:
_data._mask = mask
_data._sharedmask = not copy
else:
if names_:
def _recursive_or(a, b):
"do a|=b on each field of a, recursively"
for name in a.dtype.names:
(af, bf) = (a[name], b[name])
if af.dtype.names:
_recursive_or(af, bf)
else:
af |= bf
return
_recursive_or(_data._mask, mask)
else:
_data._mask = np.logical_or(mask, _data._mask)
_data._sharedmask = False
# Update fill_value.......
if fill_value is None:
fill_value = getattr(data, '_fill_value', None)
# But don't run the check unless we have something to check....
if fill_value is not None:
_data._fill_value = _check_fill_value(fill_value, _data.dtype)
# Process extra options ..
if hard_mask is None:
_data._hardmask = getattr(data, '_hardmask', False)
else:
_data._hardmask = hard_mask
_data._baseclass = _baseclass
return _data
#
def _update_from(self, obj):
"""Copies some attributes of obj to self.
"""
if obj is not None and isinstance(obj, ndarray):
_baseclass = type(obj)
else:
_baseclass = ndarray
# We need to copy the _basedict to avoid backward propagation
_optinfo = {}
_optinfo.update(getattr(obj, '_optinfo', {}))
_optinfo.update(getattr(obj, '_basedict', {}))
if not isinstance(obj, MaskedArray):
_optinfo.update(getattr(obj, '__dict__', {}))
_dict = dict(_fill_value=getattr(obj, '_fill_value', None),
_hardmask=getattr(obj, '_hardmask', False),
_sharedmask=getattr(obj, '_sharedmask', False),
_isfield=getattr(obj, '_isfield', False),
_baseclass=getattr(obj, '_baseclass', _baseclass),
_optinfo=_optinfo,
_basedict=_optinfo)
self.__dict__.update(_dict)
self.__dict__.update(_optinfo)
return
def __array_finalize__(self, obj):
"""Finalizes the masked array.
"""
# Get main attributes .........
self._update_from(obj)
if isinstance(obj, ndarray):
odtype = obj.dtype
if odtype.names:
_mask = getattr(obj, '_mask', make_mask_none(obj.shape, odtype))
else:
_mask = getattr(obj, '_mask', nomask)
else:
_mask = nomask
self._mask = _mask
# Finalize the mask ...........
if self._mask is not nomask:
try:
self._mask.shape = self.shape
except ValueError:
self._mask = nomask
except (TypeError, AttributeError):
# When _mask.shape is not writable (because it's a void)
pass
# Finalize the fill_value for structured arrays
if self.dtype.names:
if self._fill_value is None:
self._fill_value = _check_fill_value(None, self.dtype)
return
def __array_wrap__(self, obj, context=None):
"""
Special hook for ufuncs.
Wraps the numpy array and sets the mask according to context.
"""
result = obj.view(type(self))
result._update_from(self)
#..........
if context is not None:
result._mask = result._mask.copy()
(func, args, _) = context
m = reduce(mask_or, [getmaskarray(arg) for arg in args])
# Get the domain mask................
domain = ufunc_domain.get(func, None)
if domain is not None:
# Take the domain, and make sure it's a ndarray
if len(args) > 2:
d = filled(reduce(domain, args), True)
else:
d = filled(domain(*args), True)
# Fill the result where the domain is wrong
try:
# Binary domain: take the last value
fill_value = ufunc_fills[func][-1]
except TypeError:
# Unary domain: just use this one
fill_value = ufunc_fills[func]
except KeyError:
# Domain not recognized, use fill_value instead
fill_value = self.fill_value
result = result.copy()
np.copyto(result, fill_value, where=d)
# Update the mask
if m is nomask:
if d is not nomask:
m = d
else:
# Don't modify inplace, we risk back-propagation
m = (m | d)
# Make sure the mask has the proper size
if result.shape == () and m:
return masked
else:
result._mask = m
result._sharedmask = False
#....
return result
def view(self, dtype=None, type=None):
if dtype is None:
if type is None:
output = ndarray.view(self)
else:
output = ndarray.view(self, type)
elif type is None:
try:
if issubclass(dtype, ndarray):
output = ndarray.view(self, dtype)
dtype = None
else:
output = ndarray.view(self, dtype)
except TypeError:
output = ndarray.view(self, dtype)
else:
output = ndarray.view(self, dtype, type)
# Should we update the mask ?
if (getattr(output, '_mask', nomask) is not nomask):
if dtype is None:
dtype = output.dtype
mdtype = make_mask_descr(dtype)
output._mask = self._mask.view(mdtype, ndarray)
# Try to reset the shape of the mask (if we don't have a void)
try:
output._mask.shape = output.shape
except (AttributeError, TypeError):
pass
# Make sure to reset the _fill_value if needed
if getattr(output, '_fill_value', None) is not None:
output._fill_value = None
return output
view.__doc__ = ndarray.view.__doc__
def astype(self, newtype):
"""
Returns a copy of the MaskedArray cast to given newtype.
Returns
-------
output : MaskedArray
A copy of self cast to input newtype.
The returned record shape matches self.shape.
Examples
--------
>>> x = np.ma.array([[1,2,3.1],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1.0 -- 3.1]
[-- 5.0 --]
[7.0 -- 9.0]]
>>> print x.astype(int32)
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
"""
newtype = np.dtype(newtype)
output = self._data.astype(newtype).view(type(self))
output._update_from(self)
names = output.dtype.names
if names is None:
output._mask = self._mask.astype(bool)
else:
if self._mask is nomask:
output._mask = nomask
else:
output._mask = self._mask.astype([(n, bool) for n in names])
# Don't check _fill_value if it's None, that'll speed things up
if self._fill_value is not None:
output._fill_value = _check_fill_value(self._fill_value, newtype)
return output
def __getitem__(self, indx):
"""x.__getitem__(y) <==> x[y]
Return the item described by i, as a masked array.
"""
# This test is useful, but we should keep things light...
# if getmask(indx) is not nomask:
# msg = "Masked arrays must be filled before they can be used as indices!"
# raise IndexError(msg)
_data = ndarray.view(self, ndarray)
dout = ndarray.__getitem__(_data, indx)
# We could directly use ndarray.__getitem__ on self...
# But then we would have to modify __array_finalize__ to prevent the
# mask of being reshaped if it hasn't been set up properly yet...
# So it's easier to stick to the current version
_mask = self._mask
if not getattr(dout, 'ndim', False):
# A record ................
if isinstance(dout, np.void):
mask = _mask[indx]
# If we can make mvoid a subclass of np.void, that'd be what we'd need
# return mvoid(dout, mask=mask)
if flatten_mask(mask).any():
dout = mvoid(dout, mask=mask)
else:
return dout
# Just a scalar............
elif _mask is not nomask and _mask[indx]:
return masked
else:
# Force dout to MA ........
dout = dout.view(type(self))
# Inherit attributes from self
dout._update_from(self)
# Check the fill_value ....
if isinstance(indx, str):
if self._fill_value is not None:
dout._fill_value = self._fill_value[indx]
dout._isfield = True
# Update the mask if needed
if _mask is not nomask:
dout._mask = _mask[indx]
dout._sharedmask = True
# Note: Don't try to check for m.any(), that'll take too long...
return dout
def __setitem__(self, indx, value):
"""x.__setitem__(i, y) <==> x[i]=y
Set item described by index. If value is masked, masks those
locations.
"""
if self is masked:
raise MaskError('Cannot alter the masked element.')
# This test is useful, but we should keep things light...
# if getmask(indx) is not nomask:
# msg = "Masked arrays must be filled before they can be used as indices!"
# raise IndexError(msg)
_data = ndarray.view(self, ndarray.__getattribute__(self, '_baseclass'))
_mask = ndarray.__getattribute__(self, '_mask')
if isinstance(indx, str):
ndarray.__setitem__(_data, indx, value)
if _mask is nomask:
self._mask = _mask = make_mask_none(self.shape, self.dtype)
_mask[indx] = getmask(value)
return
#........................................
_dtype = ndarray.__getattribute__(_data, 'dtype')
nbfields = len(_dtype.names or ())
#........................................
if value is masked:
# The mask wasn't set: create a full version...
if _mask is nomask:
_mask = self._mask = make_mask_none(self.shape, _dtype)
# Now, set the mask to its value.
if nbfields:
_mask[indx] = tuple([True] * nbfields)
else:
_mask[indx] = True
if not self._isfield:
self._sharedmask = False
return
#........................................
# Get the _data part of the new value
dval = value
# Get the _mask part of the new value
mval = getattr(value, '_mask', nomask)
if nbfields and mval is nomask:
mval = tuple([False] * nbfields)
if _mask is nomask:
# Set the data, then the mask
ndarray.__setitem__(_data, indx, dval)
if mval is not nomask:
_mask = self._mask = make_mask_none(self.shape, _dtype)
ndarray.__setitem__(_mask, indx, mval)
elif not self._hardmask:
# Unshare the mask if necessary to avoid propagation
if not self._isfield:
self.unshare_mask()
_mask = ndarray.__getattribute__(self, '_mask')
# Set the data, then the mask
ndarray.__setitem__(_data, indx, dval)
ndarray.__setitem__(_mask, indx, mval)
elif hasattr(indx, 'dtype') and (indx.dtype == MaskType):
indx = indx * umath.logical_not(_mask)
ndarray.__setitem__(_data, indx, dval)
else:
if nbfields:
err_msg = "Flexible 'hard' masks are not yet supported..."
raise NotImplementedError(err_msg)
mindx = mask_or(_mask[indx], mval, copy=True)
dindx = self._data[indx]
if dindx.size > 1:
np.copyto(dindx, dval, where=~mindx)
elif mindx is nomask:
dindx = dval
ndarray.__setitem__(_data, indx, dindx)
_mask[indx] = mindx
return
def __getslice__(self, i, j):
"""x.__getslice__(i, j) <==> x[i:j]
Return the slice described by (i, j). The use of negative
indices is not supported.
"""
return self.__getitem__(slice(i, j))
def __setslice__(self, i, j, value):
"""x.__setslice__(i, j, value) <==> x[i:j]=value
Set the slice (i,j) of a to value. If value is masked, mask
those locations.
"""
self.__setitem__(slice(i, j), value)
def __setmask__(self, mask, copy=False):
"""Set the mask.
"""
idtype = ndarray.__getattribute__(self, 'dtype')
current_mask = ndarray.__getattribute__(self, '_mask')
if mask is masked:
mask = True
# Make sure the mask is set
if (current_mask is nomask):
# Just don't do anything is there's nothing to do...
if mask is nomask:
return
current_mask = self._mask = make_mask_none(self.shape, idtype)
# No named fields.........
if idtype.names is None:
# Hardmask: don't unmask the data
if self._hardmask:
current_mask |= mask
# Softmask: set everything to False
else:
current_mask.flat = mask
# Named fields w/ ............
else:
mdtype = current_mask.dtype
mask = np.array(mask, copy=False)
# Mask is a singleton
if not mask.ndim:
# It's a boolean : make a record
if mask.dtype.kind == 'b':
mask = np.array(tuple([mask.item()]*len(mdtype)),
dtype=mdtype)
# It's a record: make sure the dtype is correct
else:
mask = mask.astype(mdtype)
# Mask is a sequence
else:
# Make sure the new mask is a ndarray with the proper dtype
try:
mask = np.array(mask, copy=copy, dtype=mdtype)
# Or assume it's a sequence of bool/int
except TypeError:
mask = np.array([tuple([m] * len(mdtype)) for m in mask],
dtype=mdtype)
# Hardmask: don't unmask the data
if self._hardmask:
for n in idtype.names:
current_mask[n] |= mask[n]
# Softmask: set everything to False
else:
current_mask.flat = mask
# Reshape if needed
if current_mask.shape:
current_mask.shape = self.shape
return
_set_mask = __setmask__
#....
def _get_mask(self):
"""Return the current mask.
"""
# We could try to force a reshape, but that wouldn't work in some cases.
# return self._mask.reshape(self.shape)
return self._mask
mask = property(fget=_get_mask, fset=__setmask__, doc="Mask")
def _get_recordmask(self):
"""
Return the mask of the records.
A record is masked when all the fields are masked.
"""
_mask = ndarray.__getattribute__(self, '_mask').view(ndarray)
if _mask.dtype.names is None:
return _mask
return np.all(flatten_structured_array(_mask), axis= -1)
def _set_recordmask(self):
"""Return the mask of the records.
A record is masked when all the fields are masked.
"""
raise NotImplementedError("Coming soon: setting the mask per records!")
recordmask = property(fget=_get_recordmask)
#............................................
def harden_mask(self):
"""
Force the mask to hard.
Whether the mask of a masked array is hard or soft is determined by
its `hardmask` property. `harden_mask` sets `hardmask` to True.
See Also
--------
hardmask
"""
self._hardmask = True
return self
def soften_mask(self):
"""
Force the mask to soft.
Whether the mask of a masked array is hard or soft is determined by
its `hardmask` property. `soften_mask` sets `hardmask` to False.
See Also
--------
hardmask
"""
self._hardmask = False
return self
hardmask = property(fget=lambda self: self._hardmask,
doc="Hardness of the mask")
def unshare_mask(self):
"""
Copy the mask and set the sharedmask flag to False.
Whether the mask is shared between masked arrays can be seen from
the `sharedmask` property. `unshare_mask` ensures the mask is not shared.
A copy of the mask is only made if it was shared.
See Also
--------
sharedmask
"""
if self._sharedmask:
self._mask = self._mask.copy()
self._sharedmask = False
return self
sharedmask = property(fget=lambda self: self._sharedmask,
doc="Share status of the mask (read-only).")
def shrink_mask(self):
"""
Reduce a mask to nomask when possible.
Parameters
----------
None
Returns
-------
None
Examples
--------
>>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4)
>>> x.mask
array([[False, False],
[False, False]], dtype=bool)
>>> x.shrink_mask()
>>> x.mask
False
"""
m = self._mask
if m.ndim and not m.any():
self._mask = nomask
return self
#............................................
baseclass = property(fget=lambda self:self._baseclass,
doc="Class of the underlying data (read-only).")
def _get_data(self):
"""Return the current data, as a view of the original
underlying data.
"""
return ndarray.view(self, self._baseclass)
_data = property(fget=_get_data)
data = property(fget=_get_data)
def _get_flat(self):
"Return a flat iterator."
return MaskedIterator(self)
#
def _set_flat (self, value):
"Set a flattened version of self to value."
y = self.ravel()
y[:] = value
#
flat = property(fget=_get_flat, fset=_set_flat,
doc="Flat version of the array.")
def get_fill_value(self):
"""
Return the filling value of the masked array.
Returns
-------
fill_value : scalar
The filling value.
Examples
--------
>>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
... np.ma.array([0, 1], dtype=dt).get_fill_value()
...
999999
999999
1e+20
(1e+20+0j)
>>> x = np.ma.array([0, 1.], fill_value=-np.inf)
>>> x.get_fill_value()
-inf
"""
if self._fill_value is None:
self._fill_value = _check_fill_value(None, self.dtype)
return self._fill_value[()]
def set_fill_value(self, value=None):
"""
Set the filling value of the masked array.
Parameters
----------
value : scalar, optional
The new filling value. Default is None, in which case a default
based on the data type is used.
See Also
--------
ma.set_fill_value : Equivalent function.
Examples
--------
>>> x = np.ma.array([0, 1.], fill_value=-np.inf)
>>> x.fill_value
-inf
>>> x.set_fill_value(np.pi)
>>> x.fill_value
3.1415926535897931
Reset to default:
>>> x.set_fill_value()
>>> x.fill_value
1e+20
"""
target = _check_fill_value(value, self.dtype)
_fill_value = self._fill_value
if _fill_value is None:
# Create the attribute if it was undefined
self._fill_value = target
else:
# Don't overwrite the attribute, just fill it (for propagation)
_fill_value[()] = target
fill_value = property(fget=get_fill_value, fset=set_fill_value,
doc="Filling value.")
def filled(self, fill_value=None):
"""
Return a copy of self, with masked values filled with a given value.
Parameters
----------
fill_value : scalar, optional
The value to use for invalid entries (None by default).
If None, the `fill_value` attribute of the array is used instead.
Returns
-------
filled_array : ndarray
A copy of ``self`` with invalid entries replaced by *fill_value*
(be it the function argument or the attribute of ``self``.
Notes
-----
The result is **not** a MaskedArray!
Examples
--------
>>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
>>> x.filled()
array([1, 2, -999, 4, -999])
>>> type(x.filled())
<type 'numpy.ndarray'>
Subclassing is preserved. This means that if the data part of the masked
array is a matrix, `filled` returns a matrix:
>>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
>>> x.filled()
matrix([[ 1, 999999],
[999999, 4]])
"""
m = self._mask
if m is nomask:
return self._data
#
if fill_value is None:
fill_value = self.fill_value
else:
fill_value = _check_fill_value(fill_value, self.dtype)
#
if self is masked_singleton:
return np.asanyarray(fill_value)
#
if m.dtype.names:
result = self._data.copy()
_recursive_filled(result, self._mask, fill_value)
elif not m.any():
return self._data
else:
result = self._data.copy()
try:
np.copyto(result, fill_value, where=m)
except (TypeError, AttributeError):
fill_value = narray(fill_value, dtype=object)
d = result.astype(object)
result = np.choose(m, (d, fill_value))
except IndexError:
#ok, if scalar
if self._data.shape:
raise
elif m:
result = np.array(fill_value, dtype=self.dtype)
else:
result = self._data
return result
def compressed(self):
"""
Return all the non-masked data as a 1-D array.
Returns
-------
data : ndarray
A new `ndarray` holding the non-masked data is returned.
Notes
-----
The result is **not** a MaskedArray!
Examples
--------
>>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3)
>>> x.compressed()
array([0, 1])
>>> type(x.compressed())
<type 'numpy.ndarray'>
"""
data = ndarray.ravel(self._data)
if self._mask is not nomask:
data = data.compress(np.logical_not(ndarray.ravel(self._mask)))
return data
def compress(self, condition, axis=None, out=None):
"""
Return `a` where condition is ``True``.
If condition is a `MaskedArray`, missing values are considered
as ``False``.
Parameters
----------
condition : var
Boolean 1-d array selecting which entries to return. If len(condition)
is less than the size of a along the axis, then output is truncated
to length of condition array.
axis : {None, int}, optional
Axis along which the operation must be performed.
out : {None, ndarray}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
result : MaskedArray
A :class:`MaskedArray` object.
Notes
-----
Please note the difference with :meth:`compressed` !
The output of :meth:`compress` has a mask, the output of
:meth:`compressed` does not.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> x.compress([1, 0, 1])
masked_array(data = [1 3],
mask = [False False],
fill_value=999999)
>>> x.compress([1, 0, 1], axis=1)
masked_array(data =
[[1 3]
[-- --]
[7 9]],
mask =
[[False False]
[ True True]
[False False]],
fill_value=999999)
"""
# Get the basic components
(_data, _mask) = (self._data, self._mask)
# Force the condition to a regular ndarray (forget the missing values...)
condition = np.array(condition, copy=False, subok=False)
#
_new = _data.compress(condition, axis=axis, out=out).view(type(self))
_new._update_from(self)
if _mask is not nomask:
_new._mask = _mask.compress(condition, axis=axis)
return _new
#............................................
def __str__(self):
"""String representation.
"""
if masked_print_option.enabled():
f = masked_print_option
if self is masked:
return str(f)
m = self._mask
if m is nomask:
res = self._data
else:
if m.shape == ():
if m.dtype.names:
m = m.view((bool, len(m.dtype)))
if m.any():
r = np.array(self._data.tolist(), dtype=object)
np.copyto(r, f, where=m)
return str(tuple(r))
else:
return str(self._data)
elif m:
return str(f)
else:
return str(self._data)
# convert to object array to make filled work
names = self.dtype.names
if names is None:
res = self._data.astype("O")
res[m] = f
else:
rdtype = _recursive_make_descr(self.dtype, "O")
res = self._data.astype(rdtype)
_recursive_printoption(res, m, f)
else:
res = self.filled(self.fill_value)
return str(res)
def __repr__(self):
"""Literal string representation.
"""
n = len(self.shape)
name = repr(self._data).split('(')[0]
parameters = dict(name=name, nlen=" " * len(name),
data=str(self), mask=str(self._mask),
fill=str(self.fill_value), dtype=str(self.dtype))
if self.dtype.names:
if n <= 1:
return _print_templates['short_flx'] % parameters
return _print_templates['long_flx'] % parameters
elif n <= 1:
return _print_templates['short_std'] % parameters
return _print_templates['long_std'] % parameters
def __eq__(self, other):
"Check whether other equals self elementwise"
if self is masked:
return masked
omask = getattr(other, '_mask', nomask)
if omask is nomask:
check = ndarray.__eq__(self.filled(0), other)
try:
check = check.view(type(self))
check._mask = self._mask
except AttributeError:
# Dang, we have a bool instead of an array: return the bool
return check
else:
odata = filled(other, 0)
check = ndarray.__eq__(self.filled(0), odata).view(type(self))
if self._mask is nomask:
check._mask = omask
else:
mask = mask_or(self._mask, omask)
if mask.dtype.names:
if mask.size > 1:
axis = 1
else:
axis = None
try:
mask = mask.view((bool_, len(self.dtype))).all(axis)
except ValueError:
mask = np.all([[f[n].all() for n in mask.dtype.names]
for f in mask], axis=axis)
check._mask = mask
return check
#
def __ne__(self, other):
"Check whether other doesn't equal self elementwise"
if self is masked:
return masked
omask = getattr(other, '_mask', nomask)
if omask is nomask:
check = ndarray.__ne__(self.filled(0), other)
try:
check = check.view(type(self))
check._mask = self._mask
except AttributeError:
# In case check is a boolean (or a numpy.bool)
return check
else:
odata = filled(other, 0)
check = ndarray.__ne__(self.filled(0), odata).view(type(self))
if self._mask is nomask:
check._mask = omask
else:
mask = mask_or(self._mask, omask)
if mask.dtype.names:
if mask.size > 1:
axis = 1
else:
axis = None
try:
mask = mask.view((bool_, len(self.dtype))).all(axis)
except ValueError:
mask = np.all([[f[n].all() for n in mask.dtype.names]
for f in mask], axis=axis)
check._mask = mask
return check
#
def __add__(self, other):
"Add other to self, and return a new masked array."
return add(self, other)
#
def __radd__(self, other):
"Add other to self, and return a new masked array."
return add(self, other)
#
def __sub__(self, other):
"Subtract other to self, and return a new masked array."
return subtract(self, other)
#
def __rsub__(self, other):
"Subtract other to self, and return a new masked array."
return subtract(other, self)
#
def __mul__(self, other):
"Multiply other by self, and return a new masked array."
return multiply(self, other)
#
def __rmul__(self, other):
"Multiply other by self, and return a new masked array."
return multiply(self, other)
#
def __div__(self, other):
"Divide other into self, and return a new masked array."
return divide(self, other)
#
def __truediv__(self, other):
"Divide other into self, and return a new masked array."
return true_divide(self, other)
#
def __rtruediv__(self, other):
"Divide other into self, and return a new masked array."
return true_divide(other, self)
#
def __floordiv__(self, other):
"Divide other into self, and return a new masked array."
return floor_divide(self, other)
#
def __rfloordiv__(self, other):
"Divide other into self, and return a new masked array."
return floor_divide(other, self)
#
def __pow__(self, other):
"Raise self to the power other, masking the potential NaNs/Infs"
return power(self, other)
#
def __rpow__(self, other):
"Raise self to the power other, masking the potential NaNs/Infs"
return power(other, self)
#............................................
def __iadd__(self, other):
"Add other to self in-place."
m = getmask(other)
if self._mask is nomask:
if m is not nomask and m.any():
self._mask = make_mask_none(self.shape, self.dtype)
self._mask += m
else:
if m is not nomask:
self._mask += m
ndarray.__iadd__(self._data, np.where(self._mask, 0, getdata(other)))
return self
#....
def __isub__(self, other):
"Subtract other from self in-place."
m = getmask(other)
if self._mask is nomask:
if m is not nomask and m.any():
self._mask = make_mask_none(self.shape, self.dtype)
self._mask += m
elif m is not nomask:
self._mask += m
ndarray.__isub__(self._data, np.where(self._mask, 0, getdata(other)))
return self
#....
def __imul__(self, other):
"Multiply self by other in-place."
m = getmask(other)
if self._mask is nomask:
if m is not nomask and m.any():
self._mask = make_mask_none(self.shape, self.dtype)
self._mask += m
elif m is not nomask:
self._mask += m
ndarray.__imul__(self._data, np.where(self._mask, 1, getdata(other)))
return self
#....
def __idiv__(self, other):
"Divide self by other in-place."
other_data = getdata(other)
dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
other_mask = getmask(other)
new_mask = mask_or(other_mask, dom_mask)
# The following 3 lines control the domain filling
if dom_mask.any():
(_, fval) = ufunc_fills[np.divide]
other_data = np.where(dom_mask, fval, other_data)
# self._mask = mask_or(self._mask, new_mask)
self._mask |= new_mask
ndarray.__idiv__(self._data, np.where(self._mask, 1, other_data))
return self
#....
def __ifloordiv__(self, other):
"Floor divide self by other in-place."
other_data = getdata(other)
dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
other_mask = getmask(other)
new_mask = mask_or(other_mask, dom_mask)
# The following 3 lines control the domain filling
if dom_mask.any():
(_, fval) = ufunc_fills[np.floor_divide]
other_data = np.where(dom_mask, fval, other_data)
# self._mask = mask_or(self._mask, new_mask)
self._mask |= new_mask
ndarray.__ifloordiv__(self._data, np.where(self._mask, 1, other_data))
return self
#....
def __itruediv__(self, other):
"True divide self by other in-place."
other_data = getdata(other)
dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
other_mask = getmask(other)
new_mask = mask_or(other_mask, dom_mask)
# The following 3 lines control the domain filling
if dom_mask.any():
(_, fval) = ufunc_fills[np.true_divide]
other_data = np.where(dom_mask, fval, other_data)
# self._mask = mask_or(self._mask, new_mask)
self._mask |= new_mask
ndarray.__itruediv__(self._data, np.where(self._mask, 1, other_data))
return self
#...
def __ipow__(self, other):
"Raise self to the power other, in place."
other_data = getdata(other)
other_mask = getmask(other)
err_status = np.geterr()
try:
np.seterr(divide='ignore', invalid='ignore')
ndarray.__ipow__(self._data, np.where(self._mask, 1, other_data))
finally:
np.seterr(**err_status)
invalid = np.logical_not(np.isfinite(self._data))
if invalid.any():
if self._mask is not nomask:
self._mask |= invalid
else:
self._mask = invalid
np.copyto(self._data, self.fill_value, where=invalid)
new_mask = mask_or(other_mask, invalid)
self._mask = mask_or(self._mask, new_mask)
return self
#............................................
def __float__(self):
"Convert to float."
if self.size > 1:
raise TypeError("Only length-1 arrays can be converted "
"to Python scalars")
elif self._mask:
warnings.warn("Warning: converting a masked element to nan.")
return np.nan
return float(self.item())
def __int__(self):
"Convert to int."
if self.size > 1:
raise TypeError("Only length-1 arrays can be converted "
"to Python scalars")
elif self._mask:
raise MaskError('Cannot convert masked element to a Python int.')
return int(self.item())
def get_imag(self):
"""
Return the imaginary part of the masked array.
The returned array is a view on the imaginary part of the `MaskedArray`
whose `get_imag` method is called.
Parameters
----------
None
Returns
-------
result : MaskedArray
The imaginary part of the masked array.
See Also
--------
get_real, real, imag
Examples
--------
>>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
>>> x.get_imag()
masked_array(data = [1.0 -- 1.6],
mask = [False True False],
fill_value = 1e+20)
"""
result = self._data.imag.view(type(self))
result.__setmask__(self._mask)
return result
imag = property(fget=get_imag, doc="Imaginary part.")
def get_real(self):
"""
Return the real part of the masked array.
The returned array is a view on the real part of the `MaskedArray`
whose `get_real` method is called.
Parameters
----------
None
Returns
-------
result : MaskedArray
The real part of the masked array.
See Also
--------
get_imag, real, imag
Examples
--------
>>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
>>> x.get_real()
masked_array(data = [1.0 -- 3.45],
mask = [False True False],
fill_value = 1e+20)
"""
result = self._data.real.view(type(self))
result.__setmask__(self._mask)
return result
real = property(fget=get_real, doc="Real part")
#............................................
def count(self, axis=None):
"""
Count the non-masked elements of the array along the given axis.
Parameters
----------
axis : int, optional
Axis along which to count the non-masked elements. If `axis` is
`None`, all non-masked elements are counted.
Returns
-------
result : int or ndarray
If `axis` is `None`, an integer count is returned. When `axis` is
not `None`, an array with shape determined by the lengths of the
remaining axes, is returned.
See Also
--------
count_masked : Count masked elements in array or along a given axis.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.arange(6).reshape((2, 3))
>>> a[1, :] = ma.masked
>>> a
masked_array(data =
[[0 1 2]
[-- -- --]],
mask =
[[False False False]
[ True True True]],
fill_value = 999999)
>>> a.count()
3
When the `axis` keyword is specified an array of appropriate size is
returned.
>>> a.count(axis=0)
array([1, 1, 1])
>>> a.count(axis=1)
array([3, 0])
"""
m = self._mask
s = self.shape
ls = len(s)
if m is nomask:
if ls == 0:
return 1
if ls == 1:
return s[0]
if axis is None:
return self.size
else:
n = s[axis]
t = list(s)
del t[axis]
return np.ones(t) * n
n1 = np.size(m, axis)
n2 = m.astype(int).sum(axis)
if axis is None:
return (n1 - n2)
else:
return narray(n1 - n2)
#............................................
flatten = _arraymethod('flatten')
#
def ravel(self):
"""
Returns a 1D version of self, as a view.
Returns
-------
MaskedArray
Output view is of shape ``(self.size,)`` (or
``(np.ma.product(self.shape),)``).
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.ravel()
[1 -- 3 -- 5 -- 7 -- 9]
"""
r = ndarray.ravel(self._data).view(type(self))
r._update_from(self)
if self._mask is not nomask:
r._mask = ndarray.ravel(self._mask).reshape(r.shape)
else:
r._mask = nomask
return r
#
repeat = _arraymethod('repeat')
#
def reshape (self, *s, **kwargs):
"""
Give a new shape to the array without changing its data.
Returns a masked array containing the same data, but with a new shape.
The result is a view on the original array; if this is not possible, a
ValueError is raised.
Parameters
----------
shape : int or tuple of ints
The new shape should be compatible with the original shape. If an
integer is supplied, then the result will be a 1-D array of that
length.
order : {'C', 'F'}, optional
Determines whether the array data should be viewed as in C
(row-major) or FORTRAN (column-major) order.
Returns
-------
reshaped_array : array
A new view on the array.
See Also
--------
reshape : Equivalent function in the masked array module.
numpy.ndarray.reshape : Equivalent method on ndarray object.
numpy.reshape : Equivalent function in the NumPy module.
Notes
-----
The reshaping operation cannot guarantee that a copy will not be made,
to modify the shape in place, use ``a.shape = s``
Examples
--------
>>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1])
>>> print x
[[-- 2]
[3 --]]
>>> x = x.reshape((4,1))
>>> print x
[[--]
[2]
[3]
[--]]
"""
kwargs.update(order=kwargs.get('order', 'C'))
result = self._data.reshape(*s, **kwargs).view(type(self))
result._update_from(self)
mask = self._mask
if mask is not nomask:
result._mask = mask.reshape(*s, **kwargs)
return result
#
def resize(self, newshape, refcheck=True, order=False):
"""
.. warning::
This method does nothing, except raise a ValueError exception. A
masked array does not own its data and therefore cannot safely be
resized in place. Use the `numpy.ma.resize` function instead.
This method is difficult to implement safely and may be deprecated in
future releases of NumPy.
"""
# Note : the 'order' keyword looks broken, let's just drop it
# try:
# ndarray.resize(self, newshape, refcheck=refcheck)
# if self.mask is not nomask:
# self._mask.resize(newshape, refcheck=refcheck)
# except ValueError:
# raise ValueError("Cannot resize an array that has been referenced "
# "or is referencing another array in this way.\n"
# "Use the numpy.ma.resize function.")
# return None
errmsg = "A masked array does not own its data "\
"and therefore cannot be resized.\n" \
"Use the numpy.ma.resize function instead."
raise ValueError(errmsg)
#
def put(self, indices, values, mode='raise'):
"""
Set storage-indexed locations to corresponding values.
Sets self._data.flat[n] = values[n] for each n in indices.
If `values` is shorter than `indices` then it will repeat.
If `values` has some masked values, the initial mask is updated
in consequence, else the corresponding values are unmasked.
Parameters
----------
indices : 1-D array_like
Target indices, interpreted as integers.
values : array_like
Values to place in self._data copy at target indices.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
'raise' : raise an error.
'wrap' : wrap around.
'clip' : clip to the range.
Notes
-----
`values` can be a scalar or length 1 array.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> x.put([0,4,8],[10,20,30])
>>> print x
[[10 -- 3]
[-- 20 --]
[7 -- 30]]
>>> x.put(4,999)
>>> print x
[[10 -- 3]
[-- 999 --]
[7 -- 30]]
"""
m = self._mask
# Hard mask: Get rid of the values/indices that fall on masked data
if self._hardmask and self._mask is not nomask:
mask = self._mask[indices]
indices = narray(indices, copy=False)
values = narray(values, copy=False, subok=True)
values.resize(indices.shape)
indices = indices[~mask]
values = values[~mask]
#....
self._data.put(indices, values, mode=mode)
#....
if m is nomask:
m = getmask(values)
else:
m = m.copy()
if getmask(values) is nomask:
m.put(indices, False, mode=mode)
else:
m.put(indices, values._mask, mode=mode)
m = make_mask(m, copy=False, shrink=True)
self._mask = m
#............................................
def ids (self):
"""
Return the addresses of the data and mask areas.
Parameters
----------
None
Examples
--------
>>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1])
>>> x.ids()
(166670640, 166659832)
If the array has no mask, the address of `nomask` is returned. This address
is typically not close to the data in memory:
>>> x = np.ma.array([1, 2, 3])
>>> x.ids()
(166691080, 3083169284L)
"""
if self._mask is nomask:
return (self.ctypes.data, id(nomask))
return (self.ctypes.data, self._mask.ctypes.data)
def iscontiguous(self):
"""
Return a boolean indicating whether the data is contiguous.
Parameters
----------
None
Examples
--------
>>> x = np.ma.array([1, 2, 3])
>>> x.iscontiguous()
True
`iscontiguous` returns one of the flags of the masked array:
>>> x.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
"""
return self.flags['CONTIGUOUS']
#............................................
def all(self, axis=None, out=None):
"""
Check if all of the elements of `a` are true.
Performs a :func:`logical_and` over the given axis and returns the result.
Masked values are considered as True during computation.
For convenience, the output array is masked where ALL the values along the
current axis are masked: if the output would have been a scalar and that
all the values are masked, then the output is `masked`.
Parameters
----------
axis : {None, integer}
Axis to perform the operation over.
If None, perform over flattened array.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
See Also
--------
all : equivalent function
Examples
--------
>>> np.ma.array([1,2,3]).all()
True
>>> a = np.ma.array([1,2,3], mask=True)
>>> (a.all() is np.ma.masked)
True
"""
mask = _check_mask_axis(self._mask, axis)
if out is None:
d = self.filled(True).all(axis=axis).view(type(self))
if d.ndim:
d.__setmask__(mask)
elif mask:
return masked
return d
self.filled(True).all(axis=axis, out=out)
if isinstance(out, MaskedArray):
if out.ndim or mask:
out.__setmask__(mask)
return out
def any(self, axis=None, out=None):
"""
Check if any of the elements of `a` are true.
Performs a logical_or over the given axis and returns the result.
Masked values are considered as False during computation.
Parameters
----------
axis : {None, integer}
Axis to perform the operation over.
If None, perform over flattened array and return a scalar.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
See Also
--------
any : equivalent function
"""
mask = _check_mask_axis(self._mask, axis)
if out is None:
d = self.filled(False).any(axis=axis).view(type(self))
if d.ndim:
d.__setmask__(mask)
elif mask:
d = masked
return d
self.filled(False).any(axis=axis, out=out)
if isinstance(out, MaskedArray):
if out.ndim or mask:
out.__setmask__(mask)
return out
def nonzero(self):
"""
Return the indices of unmasked elements that are not zero.
Returns a tuple of arrays, one for each dimension, containing the
indices of the non-zero elements in that dimension. The corresponding
non-zero values can be obtained with::
a[a.nonzero()]
To group the indices by element, rather than dimension, use
instead::
np.transpose(a.nonzero())
The result of this is always a 2d array, with a row for each non-zero
element.
Parameters
----------
None
Returns
-------
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also
--------
numpy.nonzero :
Function operating on ndarrays.
flatnonzero :
Return indices that are non-zero in the flattened version of the input
array.
ndarray.nonzero :
Equivalent ndarray method.
count_nonzero :
Counts the number of non-zero elements in the input array.
Examples
--------
>>> import numpy.ma as ma
>>> x = ma.array(np.eye(3))
>>> x
masked_array(data =
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]],
mask =
False,
fill_value=1e+20)
>>> x.nonzero()
(array([0, 1, 2]), array([0, 1, 2]))
Masked elements are ignored.
>>> x[1, 1] = ma.masked
>>> x
masked_array(data =
[[1.0 0.0 0.0]
[0.0 -- 0.0]
[0.0 0.0 1.0]],
mask =
[[False False False]
[False True False]
[False False False]],
fill_value=1e+20)
>>> x.nonzero()
(array([0, 2]), array([0, 2]))
Indices can also be grouped by element.
>>> np.transpose(x.nonzero())
array([[0, 0],
[2, 2]])
A common use for ``nonzero`` is to find the indices of an array, where
a condition is True. Given an array `a`, the condition `a` > 3 is a
boolean array and since False is interpreted as 0, ma.nonzero(a > 3)
yields the indices of the `a` where the condition is true.
>>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
masked_array(data =
[[False False False]
[ True True True]
[ True True True]],
mask =
False,
fill_value=999999)
>>> ma.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
The ``nonzero`` method of the condition array can also be called.
>>> (a > 3).nonzero()
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
"""
return narray(self.filled(0), copy=False).nonzero()
def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None):
"""
(this docstring should be overwritten)
"""
#!!!: implement out + test!
m = self._mask
if m is nomask:
result = super(MaskedArray, self).trace(offset=offset, axis1=axis1,
axis2=axis2, out=out)
return result.astype(dtype)
else:
D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2)
return D.astype(dtype).filled(0).sum(axis=None, out=out)
trace.__doc__ = ndarray.trace.__doc__
def sum(self, axis=None, dtype=None, out=None):
"""
Return the sum of the array elements over the given axis.
Masked elements are set to 0 internally.
Parameters
----------
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default
(`axis` = None) is to compute over the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are summed. If dtype has the value None and
the type of a is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of a.
out : {None, ndarray}, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
Returns
-------
sum_along_axis : MaskedArray or scalar
An array with the same shape as self, with the specified
axis removed. If self is a 0-d array, or if `axis` is None, a scalar
is returned. If an output array is specified, a reference to
`out` is returned.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.sum()
25
>>> print x.sum(axis=1)
[4 5 16]
>>> print x.sum(axis=0)
[8 5 12]
>>> print type(x.sum(axis=0, dtype=np.int64)[0])
<type 'numpy.int64'>
"""
_mask = ndarray.__getattribute__(self, '_mask')
newmask = _check_mask_axis(_mask, axis)
# No explicit output
if out is None:
result = self.filled(0).sum(axis, dtype=dtype)
rndim = getattr(result, 'ndim', 0)
if rndim:
result = result.view(type(self))
result.__setmask__(newmask)
elif newmask:
result = masked
return result
# Explicit output
result = self.filled(0).sum(axis, dtype=dtype, out=out)
if isinstance(out, MaskedArray):
outmask = getattr(out, '_mask', nomask)
if (outmask is nomask):
outmask = out._mask = make_mask_none(out.shape)
outmask.flat = newmask
return out
def cumsum(self, axis=None, dtype=None, out=None):
"""
Return the cumulative sum of the elements along the given axis.
The cumulative sum is calculated over the flattened array by
default, otherwise over the specified axis.
Masked values are set to 0 internally during the computation.
However, their position is saved, and the result will be masked at
the same locations.
Parameters
----------
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (`axis` = None) is to
compute over the flattened array. `axis` may be negative, in which case
it counts from the last to the first axis.
dtype : {None, dtype}, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults
to the dtype of `a`, unless `a` has an integer dtype with a
precision less than that of the default platform integer. In
that case, the default platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
Returns
-------
cumsum : ndarray.
A new array holding the result is returned unless ``out`` is
specified, in which case a reference to ``out`` is returned.
Notes
-----
The mask is lost if `out` is not a valid :class:`MaskedArray` !
Arithmetic is modular when using integer types, and no error is
raised on overflow.
Examples
--------
>>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
>>> print marr.cumsum()
[0 1 3 -- -- -- 9 16 24 33]
"""
result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out)
if out is not None:
if isinstance(out, MaskedArray):
out.__setmask__(self.mask)
return out
result = result.view(type(self))
result.__setmask__(self._mask)
return result
def prod(self, axis=None, dtype=None, out=None):
"""
Return the product of the array elements over the given axis.
Masked elements are set to 1 internally for computation.
Parameters
----------
axis : {None, int}, optional
Axis over which the product is taken. If None is used, then the
product is over all the array elements.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are multiplied. If ``dtype`` has the value ``None``
and the type of a is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of a.
out : {None, array}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
product_along_axis : {array, scalar}, see dtype parameter above.
Returns an array whose shape is the same as a with the specified
axis removed. Returns a 0d array when a is 1d or axis=None.
Returns a reference to the specified output array if specified.
See Also
--------
prod : equivalent function
Notes
-----
Arithmetic is modular when using integer types, and no error is raised
on overflow.
Examples
--------
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
"""
_mask = ndarray.__getattribute__(self, '_mask')
newmask = _check_mask_axis(_mask, axis)
# No explicit output
if out is None:
result = self.filled(1).prod(axis, dtype=dtype)
rndim = getattr(result, 'ndim', 0)
if rndim:
result = result.view(type(self))
result.__setmask__(newmask)
elif newmask:
result = masked
return result
# Explicit output
result = self.filled(1).prod(axis, dtype=dtype, out=out)
if isinstance(out, MaskedArray):
outmask = getattr(out, '_mask', nomask)
if (outmask is nomask):
outmask = out._mask = make_mask_none(out.shape)
outmask.flat = newmask
return out
product = prod
def cumprod(self, axis=None, dtype=None, out=None):
"""
Return the cumulative product of the elements along the given axis.
The cumulative product is taken over the flattened array by
default, otherwise over the specified axis.
Masked values are set to 1 internally during the computation.
However, their position is saved, and the result will be masked at
the same locations.
Parameters
----------
axis : {None, -1, int}, optional
Axis along which the product is computed. The default
(`axis` = None) is to compute over the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are multiplied. If ``dtype`` has the value ``None``
and the type of ``a`` is an integer type of precision less than the
default platform integer, then the default platform integer precision
is used. Otherwise, the dtype is the same as that of ``a``.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
Returns
-------
cumprod : ndarray
A new array holding the result is returned unless out is specified,
in which case a reference to out is returned.
Notes
-----
The mask is lost if `out` is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is
raised on overflow.
"""
result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out)
if out is not None:
if isinstance(out, MaskedArray):
out.__setmask__(self._mask)
return out
result = result.view(type(self))
result.__setmask__(self._mask)
return result
def mean(self, axis=None, dtype=None, out=None):
"""
Returns the average of the array elements.
Masked entries are ignored.
The average is taken over the flattened array by default, otherwise over
the specified axis. Refer to `numpy.mean` for the full documentation.
Parameters
----------
a : array_like
Array containing numbers whose mean is desired. If `a` is not an
array, a conversion is attempted.
axis : int, optional
Axis along which the means are computed. The default is to compute
the mean of the flattened array.
dtype : dtype, optional
Type to use in computing the mean. For integer inputs, the default
is float64; for floating point, inputs it is the same as the input
dtype.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
mean : ndarray, see dtype parameter above
If `out=None`, returns a new array containing the mean values,
otherwise a reference to the output array is returned.
See Also
--------
numpy.ma.mean : Equivalent function.
numpy.mean : Equivalent function on non-masked arrays.
numpy.ma.average: Weighted average.
Examples
--------
>>> a = np.ma.array([1,2,3], mask=[False, False, True])
>>> a
masked_array(data = [1 2 --],
mask = [False False True],
fill_value = 999999)
>>> a.mean()
1.5
"""
if self._mask is nomask:
result = super(MaskedArray, self).mean(axis=axis, dtype=dtype)
else:
dsum = self.sum(axis=axis, dtype=dtype)
cnt = self.count(axis=axis)
if cnt.shape == () and (cnt == 0):
result = masked
else:
result = dsum * 1. / cnt
if out is not None:
out.flat = result
if isinstance(out, MaskedArray):
outmask = getattr(out, '_mask', nomask)
if (outmask is nomask):
outmask = out._mask = make_mask_none(out.shape)
outmask.flat = getattr(result, '_mask', nomask)
return out
return result
def anom(self, axis=None, dtype=None):
"""
Compute the anomalies (deviations from the arithmetic mean)
along the given axis.
Returns an array of anomalies, with the same shape as the input and
where the arithmetic mean is computed along the given axis.
Parameters
----------
axis : int, optional
Axis over which the anomalies are taken.
The default is to use the mean of the flattened array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as
the array type.
See Also
--------
mean : Compute the mean of the array.
Examples
--------
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data = [-1. 0. 1.],
mask = False,
fill_value = 1e+20)
"""
m = self.mean(axis, dtype)
if not axis:
return (self - m)
else:
return (self - expand_dims(m, axis))
def var(self, axis=None, dtype=None, out=None, ddof=0):
""
# Easy case: nomask, business as usual
if self._mask is nomask:
return self._data.var(axis=axis, dtype=dtype, out=out, ddof=ddof)
# Some data are masked, yay!
cnt = self.count(axis=axis) - ddof
danom = self.anom(axis=axis, dtype=dtype)
if iscomplexobj(self):
danom = umath.absolute(danom) ** 2
else:
danom *= danom
dvar = divide(danom.sum(axis), cnt).view(type(self))
# Apply the mask if it's not a scalar
if dvar.ndim:
dvar._mask = mask_or(self._mask.all(axis), (cnt <= 0))
dvar._update_from(self)
elif getattr(dvar, '_mask', False):
# Make sure that masked is returned when the scalar is masked.
dvar = masked
if out is not None:
if isinstance(out, MaskedArray):
out.__setmask__(True)
elif out.dtype.kind in 'biu':
errmsg = "Masked data information would be lost in one or "\
"more location."
raise MaskError(errmsg)
else:
out.flat = np.nan
return out
# In case with have an explicit output
if out is not None:
# Set the data
out.flat = dvar
# Set the mask if needed
if isinstance(out, MaskedArray):
out.__setmask__(dvar.mask)
return out
return dvar
var.__doc__ = np.var.__doc__
def std(self, axis=None, dtype=None, out=None, ddof=0):
""
dvar = self.var(axis=axis, dtype=dtype, out=out, ddof=ddof)
if dvar is not masked:
dvar = sqrt(dvar)
if out is not None:
np.power(out, 0.5, out=out, casting='unsafe')
return out
return dvar
std.__doc__ = np.std.__doc__
#............................................
def round(self, decimals=0, out=None):
"""
Return an array rounded a to the given number of decimals.
Refer to `numpy.around` for full documentation.
See Also
--------
numpy.around : equivalent function
"""
result = self._data.round(decimals=decimals, out=out).view(type(self))
result._mask = self._mask
result._update_from(self)
# No explicit output: we're done
if out is None:
return result
if isinstance(out, MaskedArray):
out.__setmask__(self._mask)
return out
round.__doc__ = ndarray.round.__doc__
#............................................
def argsort(self, axis=None, kind='quicksort', order=None, fill_value=None):
"""
Return an ndarray of indices that sort the array along the
specified axis. Masked values are filled beforehand to
`fill_value`.
Parameters
----------
axis : int, optional
Axis along which to sort. The default is -1 (last axis).
If None, the flattened array is used.
fill_value : var, optional
Value used to fill the array before sorting.
The default is the `fill_value` attribute of the input array.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
Returns
-------
index_array : ndarray, int
Array of indices that sort `a` along the specified axis.
In other words, ``a[index_array]`` yields a sorted `a`.
See Also
--------
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
Notes
-----
See `sort` for notes on the different sorting algorithms.
Examples
--------
>>> a = np.ma.array([3,2,1], mask=[False, False, True])
>>> a
masked_array(data = [3 2 --],
mask = [False False True],
fill_value = 999999)
>>> a.argsort()
array([1, 0, 2])
"""
if fill_value is None:
fill_value = default_fill_value(self)
d = self.filled(fill_value).view(ndarray)
return d.argsort(axis=axis, kind=kind, order=order)
def argmin(self, axis=None, fill_value=None, out=None):
"""
Return array of indices to the minimum values along the given axis.
Parameters
----------
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of
minimum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
{ndarray, scalar}
If multi-dimension input, returns a new ndarray of indices to the
minimum values along the given axis. Otherwise, returns a scalar
of index to the minimum values along the given axis.
Examples
--------
>>> x = np.ma.array(arange(4), mask=[1,1,0,0])
>>> x.shape = (2,2)
>>> print x
[[-- --]
[2 3]]
>>> print x.argmin(axis=0, fill_value=-1)
[0 0]
>>> print x.argmin(axis=0, fill_value=9)
[1 1]
"""
if fill_value is None:
fill_value = minimum_fill_value(self)
d = self.filled(fill_value).view(ndarray)
return d.argmin(axis, out=out)
def argmax(self, axis=None, fill_value=None, out=None):
"""
Returns array of indices of the maximum values along the given axis.
Masked values are treated as if they had the value fill_value.
Parameters
----------
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of
maximum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
index_array : {integer_array}
Examples
--------
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
"""
if fill_value is None:
fill_value = maximum_fill_value(self._data)
d = self.filled(fill_value).view(ndarray)
return d.argmax(axis, out=out)
def sort(self, axis= -1, kind='quicksort', order=None,
endwith=True, fill_value=None):
"""
Sort the array, in-place
Parameters
----------
a : array_like
Array to be sorted.
axis : int, optional
Axis along which to sort. If None, the array is flattened before
sorting. The default is -1, which sorts along the last axis.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm. Default is 'quicksort'.
order : list, optional
When `a` is a structured array, this argument specifies which fields
to compare first, second, and so on. This list does not need to
include all of the fields.
endwith : {True, False}, optional
Whether missing values (if any) should be forced in the upper indices
(at the end of the array) (True) or lower indices (at the beginning).
fill_value : {var}, optional
Value used internally for the masked values.
If ``fill_value`` is not None, it supersedes ``endwith``.
Returns
-------
sorted_array : ndarray
Array of the same type and shape as `a`.
See Also
--------
ndarray.sort : Method to sort an array in-place.
argsort : Indirect sort.
lexsort : Indirect stable sort on multiple keys.
searchsorted : Find elements in a sorted array.
Notes
-----
See ``sort`` for notes on the different sorting algorithms.
Examples
--------
>>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
>>> # Default
>>> a.sort()
>>> print a
[1 3 5 -- --]
>>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
>>> # Put missing values in the front
>>> a.sort(endwith=False)
>>> print a
[-- -- 1 3 5]
>>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
>>> # fill_value takes over endwith
>>> a.sort(endwith=False, fill_value=3)
>>> print a
[1 -- -- 3 5]
"""
if self._mask is nomask:
ndarray.sort(self, axis=axis, kind=kind, order=order)
else:
if self is masked:
return self
if fill_value is None:
if endwith:
filler = minimum_fill_value(self)
else:
filler = maximum_fill_value(self)
else:
filler = fill_value
idx = np.indices(self.shape)
idx[axis] = self.filled(filler).argsort(axis=axis, kind=kind,
order=order)
idx_l = idx.tolist()
tmp_mask = self._mask[idx_l].flat
tmp_data = self._data[idx_l].flat
self._data.flat = tmp_data
self._mask.flat = tmp_mask
return
#............................................
def min(self, axis=None, out=None, fill_value=None):
"""
Return the minimum along a given axis.
Parameters
----------
axis : {None, int}, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must be of
the same shape and buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values.
If None, use the output of `minimum_fill_value`.
Returns
-------
amin : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
minimum_fill_value
Returns the minimum filling value for a given datatype.
"""
_mask = ndarray.__getattribute__(self, '_mask')
newmask = _check_mask_axis(_mask, axis)
if fill_value is None:
fill_value = minimum_fill_value(self)
# No explicit output
if out is None:
result = self.filled(fill_value).min(axis=axis, out=out).view(type(self))
if result.ndim:
# Set the mask
result.__setmask__(newmask)
# Get rid of Infs
if newmask.ndim:
np.copyto(result, result.fill_value, where=newmask)
elif newmask:
result = masked
return result
# Explicit output
result = self.filled(fill_value).min(axis=axis, out=out)
if isinstance(out, MaskedArray):
outmask = getattr(out, '_mask', nomask)
if (outmask is nomask):
outmask = out._mask = make_mask_none(out.shape)
outmask.flat = newmask
else:
if out.dtype.kind in 'biu':
errmsg = "Masked data information would be lost in one or more"\
" location."
raise MaskError(errmsg)
np.copyto(out, np.nan, where=newmask)
return out
def mini(self, axis=None):
"""
Return the array minimum along the specified axis.
Parameters
----------
axis : int, optional
The axis along which to find the minima. Default is None, in which case
the minimum value in the whole array is returned.
Returns
-------
min : scalar or MaskedArray
If `axis` is None, the result is a scalar. Otherwise, if `axis` is
given and the array is at least 2-D, the result is a masked array with
dimension one smaller than the array on which `mini` is called.
Examples
--------
>>> x = np.ma.array(np.arange(6), mask=[0 ,1, 0, 0, 0 ,1]).reshape(3, 2)
>>> print x
[[0 --]
[2 3]
[4 --]]
>>> x.mini()
0
>>> x.mini(axis=0)
masked_array(data = [0 3],
mask = [False False],
fill_value = 999999)
>>> print x.mini(axis=1)
[0 2 4]
"""
if axis is None:
return minimum(self)
else:
return minimum.reduce(self, axis)
#........................
def max(self, axis=None, out=None, fill_value=None):
"""
Return the maximum along a given axis.
Parameters
----------
axis : {None, int}, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values.
If None, use the output of maximum_fill_value().
Returns
-------
amax : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
maximum_fill_value
Returns the maximum filling value for a given datatype.
"""
_mask = ndarray.__getattribute__(self, '_mask')
newmask = _check_mask_axis(_mask, axis)
if fill_value is None:
fill_value = maximum_fill_value(self)
# No explicit output
if out is None:
result = self.filled(fill_value).max(axis=axis, out=out).view(type(self))
if result.ndim:
# Set the mask
result.__setmask__(newmask)
# Get rid of Infs
if newmask.ndim:
np.copyto(result, result.fill_value, where=newmask)
elif newmask:
result = masked
return result
# Explicit output
result = self.filled(fill_value).max(axis=axis, out=out)
if isinstance(out, MaskedArray):
outmask = getattr(out, '_mask', nomask)
if (outmask is nomask):
outmask = out._mask = make_mask_none(out.shape)
outmask.flat = newmask
else:
if out.dtype.kind in 'biu':
errmsg = "Masked data information would be lost in one or more"\
" location."
raise MaskError(errmsg)
np.copyto(out, np.nan, where=newmask)
return out
def ptp(self, axis=None, out=None, fill_value=None):
"""
Return (maximum - minimum) along the the given dimension
(i.e. peak-to-peak value).
Parameters
----------
axis : {None, int}, optional
Axis along which to find the peaks. If None (default) the
flattened array is used.
out : {None, array_like}, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
fill_value : {var}, optional
Value used to fill in the masked values.
Returns
-------
ptp : ndarray.
A new array holding the result, unless ``out`` was
specified, in which case a reference to ``out`` is returned.
"""
if out is None:
result = self.max(axis=axis, fill_value=fill_value)
result -= self.min(axis=axis, fill_value=fill_value)
return result
out.flat = self.max(axis=axis, out=out, fill_value=fill_value)
min_value = self.min(axis=axis, fill_value=fill_value)
np.subtract(out, min_value, out=out, casting='unsafe')
return out
def take(self, indices, axis=None, out=None, mode='raise'):
"""
"""
(_data, _mask) = (self._data, self._mask)
cls = type(self)
# Make sure the indices are not masked
maskindices = getattr(indices, '_mask', nomask)
if maskindices is not nomask:
indices = indices.filled(0)
# Get the data
if out is None:
out = _data.take(indices, axis=axis, mode=mode).view(cls)
else:
np.take(_data, indices, axis=axis, mode=mode, out=out)
# Get the mask
if isinstance(out, MaskedArray):
if _mask is nomask:
outmask = maskindices
else:
outmask = _mask.take(indices, axis=axis, mode=mode)
outmask |= maskindices
out.__setmask__(outmask)
return out
# Array methods ---------------------------------------
copy = _arraymethod('copy')
diagonal = _arraymethod('diagonal')
transpose = _arraymethod('transpose')
T = property(fget=lambda self:self.transpose())
swapaxes = _arraymethod('swapaxes')
clip = _arraymethod('clip', onmask=False)
copy = _arraymethod('copy')
squeeze = _arraymethod('squeeze')
#--------------------------------------------
def tolist(self, fill_value=None):
"""
Return the data portion of the masked array as a hierarchical Python list.
Data items are converted to the nearest compatible Python type.
Masked values are converted to `fill_value`. If `fill_value` is None,
the corresponding entries in the output list will be ``None``.
Parameters
----------
fill_value : scalar, optional
The value to use for invalid entries. Default is None.
Returns
-------
result : list
The Python list representation of the masked array.
Examples
--------
>>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4)
>>> x.tolist()
[[1, None, 3], [None, 5, None], [7, None, 9]]
>>> x.tolist(-999)
[[1, -999, 3], [-999, 5, -999], [7, -999, 9]]
"""
_mask = self._mask
# No mask ? Just return .data.tolist ?
if _mask is nomask:
return self._data.tolist()
# Explicit fill_value: fill the array and get the list
if fill_value is not None:
return self.filled(fill_value).tolist()
# Structured array .............
names = self.dtype.names
if names:
result = self._data.astype([(_, object) for _ in names])
for n in names:
result[n][_mask[n]] = None
return result.tolist()
# Standard arrays ...............
if _mask is nomask:
return [None]
# Set temps to save time when dealing w/ marrays...
inishape = self.shape
result = np.array(self._data.ravel(), dtype=object)
result[_mask.ravel()] = None
result.shape = inishape
return result.tolist()
# if fill_value is not None:
# return self.filled(fill_value).tolist()
# result = self.filled().tolist()
# # Set temps to save time when dealing w/ mrecarrays...
# _mask = self._mask
# if _mask is nomask:
# return result
# nbdims = self.ndim
# dtypesize = len(self.dtype)
# if nbdims == 0:
# return tuple([None] * dtypesize)
# elif nbdims == 1:
# maskedidx = _mask.nonzero()[0].tolist()
# if dtypesize:
# nodata = tuple([None] * dtypesize)
# else:
# nodata = None
# [operator.setitem(result, i, nodata) for i in maskedidx]
# else:
# for idx in zip(*[i.tolist() for i in _mask.nonzero()]):
# tmp = result
# for i in idx[:-1]:
# tmp = tmp[i]
# tmp[idx[-1]] = None
# return result
#........................
def tostring(self, fill_value=None, order='C'):
"""
Return the array data as a string containing the raw bytes in the array.
The array is filled with a fill value before the string conversion.
Parameters
----------
fill_value : scalar, optional
Value used to fill in the masked values. Deafult is None, in which
case `MaskedArray.fill_value` is used.
order : {'C','F','A'}, optional
Order of the data item in the copy. Default is 'C'.
- 'C' -- C order (row major).
- 'F' -- Fortran order (column major).
- 'A' -- Any, current order of array.
- None -- Same as 'A'.
See Also
--------
ndarray.tostring
tolist, tofile
Notes
-----
As for `ndarray.tostring`, information about the shape, dtype, etc.,
but also about `fill_value`, will be lost.
Examples
--------
>>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
>>> x.tostring()
'\\x01\\x00\\x00\\x00?B\\x0f\\x00?B\\x0f\\x00\\x04\\x00\\x00\\x00'
"""
return self.filled(fill_value).tostring(order=order)
#........................
def tofile(self, fid, sep="", format="%s"):
"""
Save a masked array to a file in binary format.
.. warning::
This function is not implemented yet.
Raises
------
NotImplementedError
When `tofile` is called.
"""
raise NotImplementedError("Not implemented yet, sorry...")
def toflex(self):
"""
Transforms a masked array into a flexible-type array.
The flexible type array that is returned will have two fields:
* the ``_data`` field stores the ``_data`` part of the array.
* the ``_mask`` field stores the ``_mask`` part of the array.
Parameters
----------
None
Returns
-------
record : ndarray
A new flexible-type `ndarray` with two fields: the first element
containing a value, the second element containing the corresponding
mask boolean. The returned record shape matches self.shape.
Notes
-----
A side-effect of transforming a masked array into a flexible `ndarray` is
that meta information (``fill_value``, ...) will be lost.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.toflex()
[[(1, False) (2, True) (3, False)]
[(4, True) (5, False) (6, True)]
[(7, False) (8, True) (9, False)]]
"""
# Get the basic dtype ....
ddtype = self.dtype
# Make sure we have a mask
_mask = self._mask
if _mask is None:
_mask = make_mask_none(self.shape, ddtype)
# And get its dtype
mdtype = self._mask.dtype
#
record = np.ndarray(shape=self.shape,
dtype=[('_data', ddtype), ('_mask', mdtype)])
record['_data'] = self._data
record['_mask'] = self._mask
return record
torecords = toflex
#--------------------------------------------
# Pickling
def __getstate__(self):
"""Return the internal state of the masked array, for pickling
purposes.
"""
cf = 'CF'[self.flags.fnc]
state = (1,
self.shape,
self.dtype,
self.flags.fnc,
self._data.tostring(cf),
#self._data.tolist(),
getmaskarray(self).tostring(cf),
#getmaskarray(self).tolist(),
self._fill_value,
)
return state
#
def __setstate__(self, state):
"""Restore the internal state of the masked array, for
pickling purposes. ``state`` is typically the output of the
``__getstate__`` output, and is a 5-tuple:
- class name
- a tuple giving the shape of the data
- a typecode for the data
- a binary string for the data
- a binary string for the mask.
"""
(_, shp, typ, isf, raw, msk, flv) = state
ndarray.__setstate__(self, (shp, typ, isf, raw))
self._mask.__setstate__((shp, make_mask_descr(typ), isf, msk))
self.fill_value = flv
#
def __reduce__(self):
"""Return a 3-tuple for pickling a MaskedArray.
"""
return (_mareconstruct,
(self.__class__, self._baseclass, (0,), 'b',),
self.__getstate__())
#
def __deepcopy__(self, memo=None):
from copy import deepcopy
copied = MaskedArray.__new__(type(self), self, copy=True)
if memo is None:
memo = {}
memo[id(self)] = copied
for (k, v) in self.__dict__.items():
copied.__dict__[k] = deepcopy(v, memo)
return copied
def _mareconstruct(subtype, baseclass, baseshape, basetype,):
"""Internal function that builds a new MaskedArray from the
information stored in a pickle.
"""
_data = ndarray.__new__(baseclass, baseshape, basetype)
_mask = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,)
class mvoid(MaskedArray):
"""
Fake a 'void' object to use for masked array with structured dtypes.
"""
#
def __new__(self, data, mask=nomask, dtype=None, fill_value=None):
dtype = dtype or data.dtype
_data = ndarray((), dtype=dtype)
_data[()] = data
_data = _data.view(self)
if mask is not nomask:
if isinstance(mask, np.void):
_data._mask = mask
else:
try:
# Mask is already a 0D array
_data._mask = np.void(mask)
except TypeError:
# Transform the mask to a void
mdtype = make_mask_descr(dtype)
_data._mask = np.array(mask, dtype=mdtype)[()]
if fill_value is not None:
_data.fill_value = fill_value
return _data
def _get_data(self):
# Make sure that the _data part is a np.void
return self.view(ndarray)[()]
_data = property(fget=_get_data)
def __getitem__(self, indx):
"Get the index..."
m = self._mask
if m is not nomask and m[indx]:
return masked
return self._data[indx]
def __setitem__(self, indx, value):
self._data[indx] = value
self._mask[indx] |= getattr(value, "_mask", False)
def __str__(self):
m = self._mask
if (m is nomask):
return self._data.__str__()
m = tuple(m)
if (not any(m)):
return self._data.__str__()
r = self._data.tolist()
p = masked_print_option
if not p.enabled():
p = 'N/A'
else:
p = str(p)
r = [(str(_), p)[int(_m)] for (_, _m) in zip(r, m)]
return "(%s)" % ", ".join(r)
def __repr__(self):
m = self._mask
if (m is nomask):
return self._data.__repr__()
m = tuple(m)
if not any(m):
return self._data.__repr__()
p = masked_print_option
if not p.enabled():
return self.filled(self.fill_value).__repr__()
p = str(p)
r = [(str(_), p)[int(_m)] for (_, _m) in zip(self._data.tolist(), m)]
return "(%s)" % ", ".join(r)
def __iter__(self):
"Defines an iterator for mvoid"
(_data, _mask) = (self._data, self._mask)
if _mask is nomask:
for d in _data:
yield d
else:
for (d, m) in zip(_data, _mask):
if m:
yield masked
else:
yield d
def filled(self, fill_value=None):
"""
Return a copy with masked fields filled with a given value.
Parameters
----------
fill_value : scalar, optional
The value to use for invalid entries (None by default).
If None, the `fill_value` attribute is used instead.
Returns
-------
filled_void:
A `np.void` object
See Also
--------
MaskedArray.filled
"""
return asarray(self).filled(fill_value)[()]
def tolist(self):
"""
Transforms the mvoid object into a tuple.
Masked fields are replaced by None.
Returns
-------
returned_tuple
Tuple of fields
"""
_mask = self._mask
if _mask is nomask:
return self._data.tolist()
result = []
for (d, m) in zip(self._data, self._mask):
if m:
result.append(None)
else:
# .item() makes sure we return a standard Python object
result.append(d.item())
return tuple(result)
#####--------------------------------------------------------------------------
#---- --- Shortcuts ---
#####---------------------------------------------------------------------------
def isMaskedArray(x):
"""
Test whether input is an instance of MaskedArray.
This function returns True if `x` is an instance of MaskedArray
and returns False otherwise. Any object is accepted as input.
Parameters
----------
x : object
Object to test.
Returns
-------
result : bool
True if `x` is a MaskedArray.
See Also
--------
isMA : Alias to isMaskedArray.
isarray : Alias to isMaskedArray.
Examples
--------
>>> import numpy.ma as ma
>>> a = np.eye(3, 3)
>>> a
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> m = ma.masked_values(a, 0)
>>> m
masked_array(data =
[[1.0 -- --]
[-- 1.0 --]
[-- -- 1.0]],
mask =
[[False True True]
[ True False True]
[ True True False]],
fill_value=0.0)
>>> ma.isMaskedArray(a)
False
>>> ma.isMaskedArray(m)
True
>>> ma.isMaskedArray([0, 1, 2])
False
"""
return isinstance(x, MaskedArray)
isarray = isMaskedArray
isMA = isMaskedArray #backward compatibility
# We define the masked singleton as a float for higher precedence...
# Note that it can be tricky sometimes w/ type comparison
class MaskedConstant(MaskedArray):
#
_data = data = np.array(0.)
_mask = mask = np.array(True)
_baseclass = ndarray
#
def __new__(self):
return self._data.view(self)
#
def __array_finalize__(self, obj):
return
#
def __array_wrap__(self, obj):
return self
#
def __str__(self):
return str(masked_print_option._display)
#
def __repr__(self):
return 'masked'
#
def flatten(self):
return masked_array([self._data], dtype=float, mask=[True])
def __reduce__(self):
"""Override of MaskedArray's __reduce__.
"""
return (self.__class__, ())
masked = masked_singleton = MaskedConstant()
masked_array = MaskedArray
def array(data, dtype=None, copy=False, order=False,
mask=nomask, fill_value=None,
keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0,
):
"""array(data, dtype=None, copy=False, order=False, mask=nomask,
fill_value=None, keep_mask=True, hard_mask=False, shrink=True,
subok=True, ndmin=0)
Acts as shortcut to MaskedArray, with options in a different order
for convenience. And backwards compatibility...
"""
#!!!: we should try to put 'order' somwehere
return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok,
keep_mask=keep_mask, hard_mask=hard_mask,
fill_value=fill_value, ndmin=ndmin, shrink=shrink)
array.__doc__ = masked_array.__doc__
def is_masked(x):
"""
Determine whether input has masked values.
Accepts any object as input, but always returns False unless the
input is a MaskedArray containing masked values.
Parameters
----------
x : array_like
Array to check for masked values.
Returns
-------
result : bool
True if `x` is a MaskedArray with masked values, False otherwise.
Examples
--------
>>> import numpy.ma as ma
>>> x = ma.masked_equal([0, 1, 0, 2, 3], 0)
>>> x
masked_array(data = [-- 1 -- 2 3],
mask = [ True False True False False],
fill_value=999999)
>>> ma.is_masked(x)
True
>>> x = ma.masked_equal([0, 1, 0, 2, 3], 42)
>>> x
masked_array(data = [0 1 0 2 3],
mask = False,
fill_value=999999)
>>> ma.is_masked(x)
False
Always returns False if `x` isn't a MaskedArray.
>>> x = [False, True, False]
>>> ma.is_masked(x)
False
>>> x = 'a string'
>>> ma.is_masked(x)
False
"""
m = getmask(x)
if m is nomask:
return False
elif m.any():
return True
return False
#####---------------------------------------------------------------------------
#---- --- Extrema functions ---
#####---------------------------------------------------------------------------
class _extrema_operation(object):
"""
Generic class for maximum/minimum functions.
.. note::
This is the base class for `_maximum_operation` and
`_minimum_operation`.
"""
def __call__(self, a, b=None):
"Executes the call behavior."
if b is None:
return self.reduce(a)
return where(self.compare(a, b), a, b)
#.........
def reduce(self, target, axis=None):
"Reduce target along the given axis."
target = narray(target, copy=False, subok=True)
m = getmask(target)
if axis is not None:
kargs = { 'axis' : axis }
else:
kargs = {}
target = target.ravel()
if not (m is nomask):
m = m.ravel()
if m is nomask:
t = self.ufunc.reduce(target, **kargs)
else:
target = target.filled(self.fill_value_func(target)).view(type(target))
t = self.ufunc.reduce(target, **kargs)
m = umath.logical_and.reduce(m, **kargs)
if hasattr(t, '_mask'):
t._mask = m
elif m:
t = masked
return t
#.........
def outer (self, a, b):
"Return the function applied to the outer product of a and b."
ma = getmask(a)
mb = getmask(b)
if ma is nomask and mb is nomask:
m = nomask
else:
ma = getmaskarray(a)
mb = getmaskarray(b)
m = logical_or.outer(ma, mb)
result = self.ufunc.outer(filled(a), filled(b))
if not isinstance(result, MaskedArray):
result = result.view(MaskedArray)
result._mask = m
return result
#............................
class _minimum_operation(_extrema_operation):
"Object to calculate minima"
def __init__ (self):
"""minimum(a, b) or minimum(a)
In one argument case, returns the scalar minimum.
"""
self.ufunc = umath.minimum
self.afunc = amin
self.compare = less
self.fill_value_func = minimum_fill_value
#............................
class _maximum_operation(_extrema_operation):
"Object to calculate maxima"
def __init__ (self):
"""maximum(a, b) or maximum(a)
In one argument case returns the scalar maximum.
"""
self.ufunc = umath.maximum
self.afunc = amax
self.compare = greater
self.fill_value_func = maximum_fill_value
#..........................................................
def min(obj, axis=None, out=None, fill_value=None):
try:
return obj.min(axis=axis, fill_value=fill_value, out=out)
except (AttributeError, TypeError):
# If obj doesn't have a max method,
# ...or if the method doesn't accept a fill_value argument
return asanyarray(obj).min(axis=axis, fill_value=fill_value, out=out)
min.__doc__ = MaskedArray.min.__doc__
def max(obj, axis=None, out=None, fill_value=None):
try:
return obj.max(axis=axis, fill_value=fill_value, out=out)
except (AttributeError, TypeError):
# If obj doesn't have a max method,
# ...or if the method doesn't accept a fill_value argument
return asanyarray(obj).max(axis=axis, fill_value=fill_value, out=out)
max.__doc__ = MaskedArray.max.__doc__
def ptp(obj, axis=None, out=None, fill_value=None):
"""a.ptp(axis=None) = a.max(axis)-a.min(axis)"""
try:
return obj.ptp(axis, out=out, fill_value=fill_value)
except (AttributeError, TypeError):
# If obj doesn't have a max method,
# ...or if the method doesn't accept a fill_value argument
return asanyarray(obj).ptp(axis=axis, fill_value=fill_value, out=out)
ptp.__doc__ = MaskedArray.ptp.__doc__
#####---------------------------------------------------------------------------
#---- --- Definition of functions from the corresponding methods ---
#####---------------------------------------------------------------------------
class _frommethod:
"""
Define functions from existing MaskedArray methods.
Parameters
----------
methodname : str
Name of the method to transform.
"""
def __init__(self, methodname):
self.__name__ = methodname
self.__doc__ = self.getdoc()
#
def getdoc(self):
"Return the doc of the function (from the doc of the method)."
meth = getattr(MaskedArray, self.__name__, None) or\
getattr(np, self.__name__, None)
signature = self.__name__ + get_object_signature(meth)
if meth is not None:
doc = """ %s\n%s""" % (signature, getattr(meth, '__doc__', None))
return doc
#
def __call__(self, a, *args, **params):
# Get the method from the array (if possible)
method_name = self.__name__
method = getattr(a, method_name, None)
if method is not None:
return method(*args, **params)
# Still here ? Then a is not a MaskedArray
method = getattr(MaskedArray, method_name, None)
if method is not None:
return method(MaskedArray(a), *args, **params)
# Still here ? OK, let's call the corresponding np function
method = getattr(np, method_name)
return method(a, *args, **params)
all = _frommethod('all')
anomalies = anom = _frommethod('anom')
any = _frommethod('any')
compress = _frommethod('compress')
cumprod = _frommethod('cumprod')
cumsum = _frommethod('cumsum')
copy = _frommethod('copy')
diagonal = _frommethod('diagonal')
harden_mask = _frommethod('harden_mask')
ids = _frommethod('ids')
maximum = _maximum_operation()
mean = _frommethod('mean')
minimum = _minimum_operation()
nonzero = _frommethod('nonzero')
prod = _frommethod('prod')
product = _frommethod('prod')
ravel = _frommethod('ravel')
repeat = _frommethod('repeat')
shrink_mask = _frommethod('shrink_mask')
soften_mask = _frommethod('soften_mask')
std = _frommethod('std')
sum = _frommethod('sum')
swapaxes = _frommethod('swapaxes')
#take = _frommethod('take')
trace = _frommethod('trace')
var = _frommethod('var')
def take(a, indices, axis=None, out=None, mode='raise'):
"""
"""
a = masked_array(a)
return a.take(indices, axis=axis, out=out, mode=mode)
#..............................................................................
def power(a, b, third=None):
"""
Returns element-wise base array raised to power from second array.
This is the masked array version of `numpy.power`. For details see
`numpy.power`.
See Also
--------
numpy.power
Notes
-----
The *out* argument to `numpy.power` is not supported, `third` has to be
None.
"""
if third is not None:
raise MaskError("3-argument power not supported.")
# Get the masks
ma = getmask(a)
mb = getmask(b)
m = mask_or(ma, mb)
# Get the rawdata
fa = getdata(a)
fb = getdata(b)
# Get the type of the result (so that we preserve subclasses)
if isinstance(a, MaskedArray):
basetype = type(a)
else:
basetype = MaskedArray
# Get the result and view it as a (subclass of) MaskedArray
err_status = np.geterr()
try:
np.seterr(divide='ignore', invalid='ignore')
result = np.where(m, fa, umath.power(fa, fb)).view(basetype)
finally:
np.seterr(**err_status)
result._update_from(a)
# Find where we're in trouble w/ NaNs and Infs
invalid = np.logical_not(np.isfinite(result.view(ndarray)))
# Add the initial mask
if m is not nomask:
if not (result.ndim):
return masked
result._mask = np.logical_or(m, invalid)
# Fix the invalid parts
if invalid.any():
if not result.ndim:
return masked
elif result._mask is nomask:
result._mask = invalid
result._data[invalid] = result.fill_value
return result
# if fb.dtype.char in typecodes["Integer"]:
# return masked_array(umath.power(fa, fb), m)
# m = mask_or(m, (fa < 0) & (fb != fb.astype(int)))
# if m is nomask:
# return masked_array(umath.power(fa, fb))
# else:
# fa = fa.copy()
# if m.all():
# fa.flat = 1
# else:
# np.copyto(fa, 1, where=m)
# return masked_array(umath.power(fa, fb), m)
#..............................................................................
def argsort(a, axis=None, kind='quicksort', order=None, fill_value=None):
"Function version of the eponymous method."
if fill_value is None:
fill_value = default_fill_value(a)
d = filled(a, fill_value)
if axis is None:
return d.argsort(kind=kind, order=order)
return d.argsort(axis, kind=kind, order=order)
argsort.__doc__ = MaskedArray.argsort.__doc__
def argmin(a, axis=None, fill_value=None):
"Function version of the eponymous method."
if fill_value is None:
fill_value = default_fill_value(a)
d = filled(a, fill_value)
return d.argmin(axis=axis)
argmin.__doc__ = MaskedArray.argmin.__doc__
def argmax(a, axis=None, fill_value=None):
"Function version of the eponymous method."
if fill_value is None:
fill_value = default_fill_value(a)
try:
fill_value = -fill_value
except:
pass
d = filled(a, fill_value)
return d.argmax(axis=axis)
argmin.__doc__ = MaskedArray.argmax.__doc__
def sort(a, axis= -1, kind='quicksort', order=None, endwith=True, fill_value=None):
"Function version of the eponymous method."
a = narray(a, copy=True, subok=True)
if axis is None:
a = a.flatten()
axis = 0
if fill_value is None:
if endwith:
filler = minimum_fill_value(a)
else:
filler = maximum_fill_value(a)
else:
filler = fill_value
# return
indx = np.indices(a.shape).tolist()
indx[axis] = filled(a, filler).argsort(axis=axis, kind=kind, order=order)
return a[indx]
sort.__doc__ = MaskedArray.sort.__doc__
def compressed(x):
"""
Return all the non-masked data as a 1-D array.
This function is equivalent to calling the "compressed" method of a
`MaskedArray`, see `MaskedArray.compressed` for details.
See Also
--------
MaskedArray.compressed
Equivalent method.
"""
if getmask(x) is nomask:
return np.asanyarray(x)
else:
return x.compressed()
def concatenate(arrays, axis=0):
"""
Concatenate a sequence of arrays along the given axis.
Parameters
----------
arrays : sequence of array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. Default is 0.
Returns
-------
result : MaskedArray
The concatenated array with any masked entries preserved.
See Also
--------
numpy.concatenate : Equivalent function in the top-level NumPy module.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.arange(3)
>>> a[1] = ma.masked
>>> b = ma.arange(2, 5)
>>> a
masked_array(data = [0 -- 2],
mask = [False True False],
fill_value = 999999)
>>> b
masked_array(data = [2 3 4],
mask = False,
fill_value = 999999)
>>> ma.concatenate([a, b])
masked_array(data = [0 -- 2 2 3 4],
mask = [False True False False False False],
fill_value = 999999)
"""
d = np.concatenate([getdata(a) for a in arrays], axis)
rcls = get_masked_subclass(*arrays)
data = d.view(rcls)
# Check whether one of the arrays has a non-empty mask...
for x in arrays:
if getmask(x) is not nomask:
break
else:
return data
# OK, so we have to concatenate the masks
dm = np.concatenate([getmaskarray(a) for a in arrays], axis)
# If we decide to keep a '_shrinkmask' option, we want to check that ...
# ... all of them are True, and then check for dm.any()
# shrink = numpy.logical_or.reduce([getattr(a,'_shrinkmask',True) for a in arrays])
# if shrink and not dm.any():
if not dm.dtype.fields and not dm.any():
data._mask = nomask
else:
data._mask = dm.reshape(d.shape)
return data
def count(a, axis=None):
if isinstance(a, MaskedArray):
return a.count(axis)
return masked_array(a, copy=False).count(axis)
count.__doc__ = MaskedArray.count.__doc__
def diag(v, k=0):
"""
Extract a diagonal or construct a diagonal array.
This function is the equivalent of `numpy.diag` that takes masked
values into account, see `numpy.diag` for details.
See Also
--------
numpy.diag : Equivalent function for ndarrays.
"""
output = np.diag(v, k).view(MaskedArray)
if getmask(v) is not nomask:
output._mask = np.diag(v._mask, k)
return output
def expand_dims(x, axis):
"""
Expand the shape of an array.
Expands the shape of the array by including a new axis before the one
specified by the `axis` parameter. This function behaves the same as
`numpy.expand_dims` but preserves masked elements.
See Also
--------
numpy.expand_dims : Equivalent function in top-level NumPy module.
Examples
--------
>>> import numpy.ma as ma
>>> x = ma.array([1, 2, 4])
>>> x[1] = ma.masked
>>> x
masked_array(data = [1 -- 4],
mask = [False True False],
fill_value = 999999)
>>> np.expand_dims(x, axis=0)
array([[1, 2, 4]])
>>> ma.expand_dims(x, axis=0)
masked_array(data =
[[1 -- 4]],
mask =
[[False True False]],
fill_value = 999999)
The same result can be achieved using slicing syntax with `np.newaxis`.
>>> x[np.newaxis, :]
masked_array(data =
[[1 -- 4]],
mask =
[[False True False]],
fill_value = 999999)
"""
result = n_expand_dims(x, axis)
if isinstance(x, MaskedArray):
new_shape = result.shape
result = x.view()
result.shape = new_shape
if result._mask is not nomask:
result._mask.shape = new_shape
return result
#......................................
def left_shift (a, n):
"""
Shift the bits of an integer to the left.
This is the masked array version of `numpy.left_shift`, for details
see that function.
See Also
--------
numpy.left_shift
"""
m = getmask(a)
if m is nomask:
d = umath.left_shift(filled(a), n)
return masked_array(d)
else:
d = umath.left_shift(filled(a, 0), n)
return masked_array(d, mask=m)
def right_shift (a, n):
"""
Shift the bits of an integer to the right.
This is the masked array version of `numpy.right_shift`, for details
see that function.
See Also
--------
numpy.right_shift
"""
m = getmask(a)
if m is nomask:
d = umath.right_shift(filled(a), n)
return masked_array(d)
else:
d = umath.right_shift(filled(a, 0), n)
return masked_array(d, mask=m)
#......................................
def put(a, indices, values, mode='raise'):
"""
Set storage-indexed locations to corresponding values.
This function is equivalent to `MaskedArray.put`, see that method
for details.
See Also
--------
MaskedArray.put
"""
# We can't use 'frommethod', the order of arguments is different
try:
return a.put(indices, values, mode=mode)
except AttributeError:
return narray(a, copy=False).put(indices, values, mode=mode)
def putmask(a, mask, values): #, mode='raise'):
"""
Changes elements of an array based on conditional and input values.
This is the masked array version of `numpy.putmask`, for details see
`numpy.putmask`.
See Also
--------
numpy.putmask
Notes
-----
Using a masked array as `values` will **not** transform a `ndarray` into
a `MaskedArray`.
"""
# We can't use 'frommethod', the order of arguments is different
if not isinstance(a, MaskedArray):
a = a.view(MaskedArray)
(valdata, valmask) = (getdata(values), getmask(values))
if getmask(a) is nomask:
if valmask is not nomask:
a._sharedmask = True
a._mask = make_mask_none(a.shape, a.dtype)
np.copyto(a._mask, valmask, where=mask)
elif a._hardmask:
if valmask is not nomask:
m = a._mask.copy()
np.copyto(m, valmask, where=mask)
a.mask |= m
else:
if valmask is nomask:
valmask = getmaskarray(values)
np.copyto(a._mask, valmask, where=mask)
np.copyto(a._data, valdata, where=mask)
return
def transpose(a, axes=None):
"""
Permute the dimensions of an array.
This function is exactly equivalent to `numpy.transpose`.
See Also
--------
numpy.transpose : Equivalent function in top-level NumPy module.
Examples
--------
>>> import numpy.ma as ma
>>> x = ma.arange(4).reshape((2,2))
>>> x[1, 1] = ma.masked
>>>> x
masked_array(data =
[[0 1]
[2 --]],
mask =
[[False False]
[False True]],
fill_value = 999999)
>>> ma.transpose(x)
masked_array(data =
[[0 2]
[1 --]],
mask =
[[False False]
[False True]],
fill_value = 999999)
"""
#We can't use 'frommethod', as 'transpose' doesn't take keywords
try:
return a.transpose(axes)
except AttributeError:
return narray(a, copy=False).transpose(axes).view(MaskedArray)
def reshape(a, new_shape, order='C'):
"""
Returns an array containing the same data with a new shape.
Refer to `MaskedArray.reshape` for full documentation.
See Also
--------
MaskedArray.reshape : equivalent function
"""
#We can't use 'frommethod', it whine about some parameters. Dmmit.
try:
return a.reshape(new_shape, order=order)
except AttributeError:
_tmp = narray(a, copy=False).reshape(new_shape, order=order)
return _tmp.view(MaskedArray)
def resize(x, new_shape):
"""
Return a new masked array with the specified size and shape.
This is the masked equivalent of the `numpy.resize` function. The new
array is filled with repeated copies of `x` (in the order that the
data are stored in memory). If `x` is masked, the new array will be
masked, and the new mask will be a repetition of the old one.
See Also
--------
numpy.resize : Equivalent function in the top level NumPy module.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.array([[1, 2] ,[3, 4]])
>>> a[0, 1] = ma.masked
>>> a
masked_array(data =
[[1 --]
[3 4]],
mask =
[[False True]
[False False]],
fill_value = 999999)
>>> np.resize(a, (3, 3))
array([[1, 2, 3],
[4, 1, 2],
[3, 4, 1]])
>>> ma.resize(a, (3, 3))
masked_array(data =
[[1 -- 3]
[4 1 --]
[3 4 1]],
mask =
[[False True False]
[False False True]
[False False False]],
fill_value = 999999)
A MaskedArray is always returned, regardless of the input type.
>>> a = np.array([[1, 2] ,[3, 4]])
>>> ma.resize(a, (3, 3))
masked_array(data =
[[1 2 3]
[4 1 2]
[3 4 1]],
mask =
False,
fill_value = 999999)
"""
# We can't use _frommethods here, as N.resize is notoriously whiny.
m = getmask(x)
if m is not nomask:
m = np.resize(m, new_shape)
result = np.resize(x, new_shape).view(get_masked_subclass(x))
if result.ndim:
result._mask = m
return result
#................................................
def rank(obj):
"maskedarray version of the numpy function."
return np.rank(getdata(obj))
rank.__doc__ = np.rank.__doc__
#
def shape(obj):
"maskedarray version of the numpy function."
return np.shape(getdata(obj))
shape.__doc__ = np.shape.__doc__
#
def size(obj, axis=None):
"maskedarray version of the numpy function."
return np.size(getdata(obj), axis)
size.__doc__ = np.size.__doc__
#................................................
#####--------------------------------------------------------------------------
#---- --- Extra functions ---
#####--------------------------------------------------------------------------
def where (condition, x=None, y=None):
"""
Return a masked array with elements from x or y, depending on condition.
Returns a masked array, shaped like condition, where the elements
are from `x` when `condition` is True, and from `y` otherwise.
If neither `x` nor `y` are given, the function returns a tuple of
indices where `condition` is True (the result of
``condition.nonzero()``).
Parameters
----------
condition : array_like, bool
The condition to meet. For each True element, yield the corresponding
element from `x`, otherwise from `y`.
x, y : array_like, optional
Values from which to choose. `x` and `y` need to have the same shape
as condition, or be broadcast-able to that shape.
Returns
-------
out : MaskedArray or tuple of ndarrays
The resulting masked array if `x` and `y` were given, otherwise
the result of ``condition.nonzero()``.
See Also
--------
numpy.where : Equivalent function in the top-level NumPy module.
Examples
--------
>>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0],
... [1, 0, 1],
... [0, 1, 0]])
>>> print x
[[0.0 -- 2.0]
[-- 4.0 --]
[6.0 -- 8.0]]
>>> np.ma.where(x > 5) # return the indices where x > 5
(array([2, 2]), array([0, 2]))
>>> print np.ma.where(x > 5, x, -3.1416)
[[-3.1416 -- -3.1416]
[-- -3.1416 --]
[6.0 -- 8.0]]
"""
if x is None and y is None:
return filled(condition, 0).nonzero()
elif x is None or y is None:
raise ValueError("Either both or neither x and y should be given.")
# Get the condition ...............
fc = filled(condition, 0).astype(MaskType)
notfc = np.logical_not(fc)
# Get the data ......................................
xv = getdata(x)
yv = getdata(y)
if x is masked:
ndtype = yv.dtype
elif y is masked:
ndtype = xv.dtype
else:
ndtype = np.find_common_type([xv.dtype, yv.dtype], [])
# Construct an empty array and fill it
d = np.empty(fc.shape, dtype=ndtype).view(MaskedArray)
_data = d._data
np.copyto(_data, xv.astype(ndtype), where=fc)
np.copyto(_data, yv.astype(ndtype), where=notfc)
# Create an empty mask and fill it
_mask = d._mask = np.zeros(fc.shape, dtype=MaskType)
np.copyto(_mask, getmask(x), where=fc)
np.copyto(_mask, getmask(y), where=notfc)
_mask |= getmaskarray(condition)
if not _mask.any():
d._mask = nomask
return d
def choose (indices, choices, out=None, mode='raise'):
"""
Use an index array to construct a new array from a set of choices.
Given an array of integers and a set of n choice arrays, this method
will create a new array that merges each of the choice arrays. Where a
value in `a` is i, the new array will have the value that choices[i]
contains in the same place.
Parameters
----------
a : ndarray of ints
This array must contain integers in ``[0, n-1]``, where n is the
number of choices.
choices : sequence of arrays
Choice arrays. The index array and all of the choices should be
broadcastable to the same shape.
out : array, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and `dtype`.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
* 'raise' : raise an error
* 'wrap' : wrap around
* 'clip' : clip to the range
Returns
-------
merged_array : array
See Also
--------
choose : equivalent function
Examples
--------
>>> choice = np.array([[1,1,1], [2,2,2], [3,3,3]])
>>> a = np.array([2, 1, 0])
>>> np.ma.choose(a, choice)
masked_array(data = [3 2 1],
mask = False,
fill_value=999999)
"""
def fmask (x):
"Returns the filled array, or True if masked."
if x is masked:
return True
return filled(x)
def nmask (x):
"Returns the mask, True if ``masked``, False if ``nomask``."
if x is masked:
return True
return getmask(x)
# Get the indices......
c = filled(indices, 0)
# Get the masks........
masks = [nmask(x) for x in choices]
data = [fmask(x) for x in choices]
# Construct the mask
outputmask = np.choose(c, masks, mode=mode)
outputmask = make_mask(mask_or(outputmask, getmask(indices)),
copy=0, shrink=True)
# Get the choices......
d = np.choose(c, data, mode=mode, out=out).view(MaskedArray)
if out is not None:
if isinstance(out, MaskedArray):
out.__setmask__(outputmask)
return out
d.__setmask__(outputmask)
return d
def round_(a, decimals=0, out=None):
"""
Return a copy of a, rounded to 'decimals' places.
When 'decimals' is negative, it specifies the number of positions
to the left of the decimal point. The real and imaginary parts of
complex numbers are rounded separately. Nothing is done if the
array is not of float type and 'decimals' is greater than or equal
to 0.
Parameters
----------
decimals : int
Number of decimals to round to. May be negative.
out : array_like
Existing array to use for output.
If not given, returns a default copy of a.
Notes
-----
If out is given and does not have a mask attribute, the mask of a
is lost!
"""
if out is None:
return np.round_(a, decimals, out)
else:
np.round_(getdata(a), decimals, out)
if hasattr(out, '_mask'):
out._mask = getmask(a)
return out
round = round_
def inner(a, b):
"""
Returns the inner product of a and b for arrays of floating point types.
Like the generic NumPy equivalent the product sum is over the last dimension
of a and b.
Notes
-----
The first argument is not conjugated.
"""
fa = filled(a, 0)
fb = filled(b, 0)
if len(fa.shape) == 0:
fa.shape = (1,)
if len(fb.shape) == 0:
fb.shape = (1,)
return np.inner(fa, fb).view(MaskedArray)
inner.__doc__ = doc_note(np.inner.__doc__,
"Masked values are replaced by 0.")
innerproduct = inner
def outer(a, b):
"maskedarray version of the numpy function."
fa = filled(a, 0).ravel()
fb = filled(b, 0).ravel()
d = np.outer(fa, fb)
ma = getmask(a)
mb = getmask(b)
if ma is nomask and mb is nomask:
return masked_array(d)
ma = getmaskarray(a)
mb = getmaskarray(b)
m = make_mask(1 - np.outer(1 - ma, 1 - mb), copy=0)
return masked_array(d, mask=m)
outer.__doc__ = doc_note(np.outer.__doc__,
"Masked values are replaced by 0.")
outerproduct = outer
def allequal (a, b, fill_value=True):
"""
Return True if all entries of a and b are equal, using
fill_value as a truth value where either or both are masked.
Parameters
----------
a, b : array_like
Input arrays to compare.
fill_value : bool, optional
Whether masked values in a or b are considered equal (True) or not
(False).
Returns
-------
y : bool
Returns True if the two arrays are equal within the given
tolerance, False otherwise. If either array contains NaN,
then False is returned.
See Also
--------
all, any
numpy.ma.allclose
Examples
--------
>>> a = ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
>>> a
masked_array(data = [10000000000.0 1e-07 --],
mask = [False False True],
fill_value=1e+20)
>>> b = array([1e10, 1e-7, -42.0])
>>> b
array([ 1.00000000e+10, 1.00000000e-07, -4.20000000e+01])
>>> ma.allequal(a, b, fill_value=False)
False
>>> ma.allequal(a, b)
True
"""
m = mask_or(getmask(a), getmask(b))
if m is nomask:
x = getdata(a)
y = getdata(b)
d = umath.equal(x, y)
return d.all()
elif fill_value:
x = getdata(a)
y = getdata(b)
d = umath.equal(x, y)
dm = array(d, mask=m, copy=False)
return dm.filled(True).all(None)
else:
return False
def allclose (a, b, masked_equal=True, rtol=1e-5, atol=1e-8):
"""
Returns True if two arrays are element-wise equal within a tolerance.
This function is equivalent to `allclose` except that masked values
are treated as equal (default) or unequal, depending on the `masked_equal`
argument.
Parameters
----------
a, b : array_like
Input arrays to compare.
masked_equal : bool, optional
Whether masked values in `a` and `b` are considered equal (True) or not
(False). They are considered equal by default.
rtol : float, optional
Relative tolerance. The relative difference is equal to ``rtol * b``.
Default is 1e-5.
atol : float, optional
Absolute tolerance. The absolute difference is equal to `atol`.
Default is 1e-8.
Returns
-------
y : bool
Returns True if the two arrays are equal within the given
tolerance, False otherwise. If either array contains NaN, then
False is returned.
See Also
--------
all, any
numpy.allclose : the non-masked `allclose`.
Notes
-----
If the following equation is element-wise True, then `allclose` returns
True::
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
Return True if all elements of `a` and `b` are equal subject to
given tolerances.
Examples
--------
>>> a = ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
>>> a
masked_array(data = [10000000000.0 1e-07 --],
mask = [False False True],
fill_value = 1e+20)
>>> b = ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1])
>>> ma.allclose(a, b)
False
>>> a = ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
>>> b = ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1])
>>> ma.allclose(a, b)
True
>>> ma.allclose(a, b, masked_equal=False)
False
Masked values are not compared directly.
>>> a = ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
>>> b = ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1])
>>> ma.allclose(a, b)
True
>>> ma.allclose(a, b, masked_equal=False)
False
"""
x = masked_array(a, copy=False)
y = masked_array(b, copy=False)
m = mask_or(getmask(x), getmask(y))
xinf = np.isinf(masked_array(x, copy=False, mask=m)).filled(False)
# If we have some infs, they should fall at the same place.
if not np.all(xinf == filled(np.isinf(y), False)):
return False
# No infs at all
if not np.any(xinf):
d = filled(umath.less_equal(umath.absolute(x - y),
atol + rtol * umath.absolute(y)),
masked_equal)
return np.all(d)
if not np.all(filled(x[xinf] == y[xinf], masked_equal)):
return False
x = x[~xinf]
y = y[~xinf]
d = filled(umath.less_equal(umath.absolute(x - y),
atol + rtol * umath.absolute(y)),
masked_equal)
return np.all(d)
#..............................................................................
def asarray(a, dtype=None, order=None):
"""
Convert the input to a masked array of the given data-type.
No copy is performed if the input is already an `ndarray`. If `a` is
a subclass of `MaskedArray`, a base class `MaskedArray` is returned.
Parameters
----------
a : array_like
Input data, in any form that can be converted to a masked array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists, ndarrays and masked arrays.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major ('C') or column-major ('FORTRAN') memory
representation. Default is 'C'.
Returns
-------
out : MaskedArray
Masked array interpretation of `a`.
See Also
--------
asanyarray : Similar to `asarray`, but conserves subclasses.
Examples
--------
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
>>> np.ma.asarray(x)
masked_array(data =
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]],
mask =
False,
fill_value = 1e+20)
>>> type(np.ma.asarray(x))
<class 'numpy.ma.core.MaskedArray'>
"""
return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=False)
def asanyarray(a, dtype=None):
"""
Convert the input to a masked array, conserving subclasses.
If `a` is a subclass of `MaskedArray`, its class is conserved.
No copy is performed if the input is already an `ndarray`.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major ('C') or column-major ('FORTRAN') memory
representation. Default is 'C'.
Returns
-------
out : MaskedArray
MaskedArray interpretation of `a`.
See Also
--------
asarray : Similar to `asanyarray`, but does not conserve subclass.
Examples
--------
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
>>> np.ma.asanyarray(x)
masked_array(data =
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]],
mask =
False,
fill_value = 1e+20)
>>> type(np.ma.asanyarray(x))
<class 'numpy.ma.core.MaskedArray'>
"""
return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True)
#####--------------------------------------------------------------------------
#---- --- Pickling ---
#####--------------------------------------------------------------------------
def dump(a, F):
"""
Pickle a masked array to a file.
This is a wrapper around ``cPickle.dump``.
Parameters
----------
a : MaskedArray
The array to be pickled.
F : str or file-like object
The file to pickle `a` to. If a string, the full path to the file.
"""
if not hasattr(F, 'readline'):
F = open(F, 'w')
return pickle.dump(a, F)
def dumps(a):
"""
Return a string corresponding to the pickling of a masked array.
This is a wrapper around ``cPickle.dumps``.
Parameters
----------
a : MaskedArray
The array for which the string representation of the pickle is
returned.
"""
return pickle.dumps(a)
def load(F):
"""
Wrapper around ``cPickle.load`` which accepts either a file-like object
or a filename.
Parameters
----------
F : str or file
The file or file name to load.
See Also
--------
dump : Pickle an array
Notes
-----
This is different from `numpy.load`, which does not use cPickle but loads
the NumPy binary .npy format.
"""
if not hasattr(F, 'readline'):
F = open(F, 'r')
return pickle.load(F)
def loads(strg):
"""
Load a pickle from the current string.
The result of ``cPickle.loads(strg)`` is returned.
Parameters
----------
strg : str
The string to load.
See Also
--------
dumps : Return a string corresponding to the pickling of a masked array.
"""
return pickle.loads(strg)
################################################################################
def fromfile(file, dtype=float, count= -1, sep=''):
raise NotImplementedError("Not yet implemented. Sorry")
def fromflex(fxarray):
"""
Build a masked array from a suitable flexible-type array.
The input array has to have a data-type with ``_data`` and ``_mask``
fields. This type of array is output by `MaskedArray.toflex`.
Parameters
----------
fxarray : ndarray
The structured input array, containing ``_data`` and ``_mask``
fields. If present, other fields are discarded.
Returns
-------
result : MaskedArray
The constructed masked array.
See Also
--------
MaskedArray.toflex : Build a flexible-type array from a masked array.
Examples
--------
>>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[0] + [1, 0] * 4)
>>> rec = x.toflex()
>>> rec
array([[(0, False), (1, True), (2, False)],
[(3, True), (4, False), (5, True)],
[(6, False), (7, True), (8, False)]],
dtype=[('_data', '<i4'), ('_mask', '|b1')])
>>> x2 = np.ma.fromflex(rec)
>>> x2
masked_array(data =
[[0 -- 2]
[-- 4 --]
[6 -- 8]],
mask =
[[False True False]
[ True False True]
[False True False]],
fill_value = 999999)
Extra fields can be present in the structured array but are discarded:
>>> dt = [('_data', '<i4'), ('_mask', '|b1'), ('field3', '<f4')]
>>> rec2 = np.zeros((2, 2), dtype=dt)
>>> rec2
array([[(0, False, 0.0), (0, False, 0.0)],
[(0, False, 0.0), (0, False, 0.0)]],
dtype=[('_data', '<i4'), ('_mask', '|b1'), ('field3', '<f4')])
>>> y = np.ma.fromflex(rec2)
>>> y
masked_array(data =
[[0 0]
[0 0]],
mask =
[[False False]
[False False]],
fill_value = 999999)
"""
return masked_array(fxarray['_data'], mask=fxarray['_mask'])
class _convert2ma:
"""
Convert functions from numpy to numpy.ma.
Parameters
----------
_methodname : string
Name of the method to transform.
"""
__doc__ = None
#
def __init__(self, funcname, params=None):
self._func = getattr(np, funcname)
self.__doc__ = self.getdoc()
self._extras = params or {}
#
def getdoc(self):
"Return the doc of the function (from the doc of the method)."
doc = getattr(self._func, '__doc__', None)
sig = get_object_signature(self._func)
if doc:
# Add the signature of the function at the beginning of the doc
if sig:
sig = "%s%s\n" % (self._func.__name__, sig)
doc = sig + doc
return doc
#
def __call__(self, a, *args, **params):
# Find the common parameters to the call and the definition
_extras = self._extras
common_params = set(params).intersection(_extras)
# Drop the common parameters from the call
for p in common_params:
_extras[p] = params.pop(p)
# Get the result
result = self._func.__call__(a, *args, **params).view(MaskedArray)
if "fill_value" in common_params:
result.fill_value = _extras.get("fill_value", None)
if "hardmask" in common_params:
result._hardmask = bool(_extras.get("hard_mask", False))
return result
arange = _convert2ma('arange', params=dict(fill_value=None, hardmask=False))
clip = np.clip
diff = np.diff
empty = _convert2ma('empty', params=dict(fill_value=None, hardmask=False))
empty_like = _convert2ma('empty_like')
frombuffer = _convert2ma('frombuffer')
fromfunction = _convert2ma('fromfunction')
identity = _convert2ma('identity', params=dict(fill_value=None, hardmask=False))
indices = np.indices
ones = _convert2ma('ones', params=dict(fill_value=None, hardmask=False))
ones_like = np.ones_like
squeeze = np.squeeze
zeros = _convert2ma('zeros', params=dict(fill_value=None, hardmask=False))
zeros_like = np.zeros_like
###############################################################################
| gpl-3.0 | -5,252,491,265,932,812,000 | 30.654361 | 86 | 0.530678 | false |
pekrau/Publications | publications/pubmed.py | 1 | 12887 | "PubMed interface."
import json
import os
import os.path
import sys
import time
import unicodedata
import xml.etree.ElementTree
import requests
PUBMED_FETCH_URL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&rettype=abstract&id=%s"
PUBMED_SEARCH_URL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmax=%s&term=%s"
DEFAULT_TIMEOUT = 5.0
DEFAULT_DELAY = 1.0
MONTHS = dict(jan=1, feb=2, mar=3, apr=4, may=5, jun=6,
jul=7, aug=8, sep=9, oct=10, nov=11, dec=12)
def search(author=None, published=None, journal=None, doi=None,
affiliation=None, title=None, exclude_title=None,
retmax=20, timeout=DEFAULT_TIMEOUT, delay=DEFAULT_DELAY,
api_key=None, debug=False):
"""Get list of PMIDs for PubMed hits given the data.
Delay the HTTP request if positive value (seconds).
The API key is the one set for your NCBI account, if any.
"""
parts = []
if author:
parts.append("%s[AU]" % to_ascii(str(author)))
if published:
parts.append("%s[DP]" % published)
if journal:
parts.append("%s[TA]" % journal)
if doi:
parts.append("%s[LID]" % doi)
if affiliation:
parts.append("%s[AD]" % to_ascii(str(affiliation)))
if title:
parts.append("%s[TI]" % to_ascii(str(title)))
query = " AND ".join(parts)
if exclude_title:
query += " NOT %s[TI]" % to_ascii(str(exclude_title))
url = PUBMED_SEARCH_URL % (retmax, query)
if api_key:
url += f"&api_key={api_key}"
if delay > 0.0:
time.sleep(delay)
try:
if debug:
print("url>", url)
response = requests.get(url, timeout=timeout)
except (requests.exceptions.ReadTimeout,
requests.exceptions.ConnectionError):
raise IOError("timeout")
if response.status_code != 200:
raise IOError(f"HTTP status {response.status_code} {url}")
root = xml.etree.ElementTree.fromstring(response.content)
return [e.text for e in root.findall("IdList/Id")]
def fetch(pmid, dirname=None, timeout=DEFAULT_TIMEOUT, delay=DEFAULT_DELAY,
api_key=None, debug=False):
"""Fetch publication XML from PubMed and parse into a dictionary.
Return None if no article data in XML.
Use the file cache directory if given.
Delay the HTTP request if positive value (seconds).
The API key is the one set for your NCBI account, if any.
"""
filename = pmid + ".xml"
content = None
# Get the locally stored XML file if it exists.
if dirname:
try:
with open(os.path.join(dirname, filename)) as infile:
content = infile.read()
except IOError:
pass
if not content:
url = PUBMED_FETCH_URL % pmid
if api_key:
url += f"&api_key={api_key}"
if delay > 0.0:
time.sleep(delay)
if debug:
print("url>", url)
try:
response = requests.get(url, timeout=timeout)
except (requests.exceptions.ReadTimeout,
requests.exceptions.ConnectionError):
raise IOError("timeout")
if response.status_code != 200:
raise IOError(f"HTTP status {response.status_code} {url}")
content = response.content
# Store the XML file locally.
if dirname:
with open(os.path.join(dirname, filename), "wb") as outfile:
outfile.write(content)
return parse(content)
def parse(data):
"Parse XML text data for a publication into a dictionary."
tree = xml.etree.ElementTree.fromstring(data)
try:
article = get_element(tree, "PubmedArticle")
except ValueError:
raise ValueError("no article with the given PMID")
result = dict()
result["title"] = squish(get_title(article))
result["pmid"] = get_pmid(article)
result["doi"] = None
result["authors"] = get_authors(article)
result["journal"] = get_journal(article)
result["type"] = get_type(article)
result["published"] = get_published(article)
result["epublished"] = get_epublished(article)
result["abstract"] = get_abstract(article)
result["xrefs"] = []
# Remove PMID from xrefs; get and remove DOI
for xref in get_xrefs(article):
if xref["db"] == "doi":
result["doi"] = xref["key"]
elif xref["db"] == "pubmed":
pass
else:
result["xrefs"].append(xref)
return result
def get_title(article):
"Get the title from the article XML tree."
element = get_element(article, "MedlineCitation/Article/ArticleTitle")
return get_text(element)
def get_pmid(article):
"Get the PMID from the article XML tree."
return article.findtext("MedlineCitation/PMID")
def get_authors(article):
"Get the list of authors from the article XML tree."
element = get_element(article, "MedlineCitation/Article")
authorlist = element.find("AuthorList")
if not authorlist: return []
result = []
existing = set() # Handle pathological multi-mention.
for element in authorlist.findall("Author"):
author = dict()
# Name of author
for jkey, xkey in [("family", "LastName"),
("given", "ForeName"),
("initials", "Initials")]:
value = element.findtext(xkey)
if not value: continue
value = str(value)
author[jkey] = value
author[jkey + "_normalized"] = to_ascii(value).lower()
# For consortia and such, names are a mess. Try to sort out.
if not author.get("family"):
try:
author["family"] = author.pop("given")
except KeyError:
value = element.findtext("CollectiveName")
if not value: continue # Give up.
value = str(value)
author["family"] = value
author["given"] = ""
author["initials"] = ""
author["family_normalized"] = to_ascii(author["family"]).lower()
author["given_normalized"] = ""
author["initials_normalized"] = ""
for elem in element.findall("Identifier"):
if elem.attrib.get("Source") == "ORCID":
# ORCID may be given as an URL; split away all except id proper.
author["orcid"] = get_text(elem).split("/")[-1]
for elem in element.findall(".//Affiliation"):
author.setdefault("affiliations", []).append(get_text(elem))
if author:
try: # Don't add author if this doesn't work.
key = f"{author['family']} {author['given']}"
if key not in existing:
result.append(author)
existing.add(key)
except KeyError:
pass
return result
def get_journal(article):
"Get the journal data from the article XML tree."
element = get_element(article, "MedlineCitation/Article/Journal")
result = dict()
if element is not None:
result["title"] = element.findtext("ISOAbbreviation")
if not result["title"]:
result["title"] = element.findtext("Title")
result["issn"] = element.findtext("ISSN")
issue = element.find("JournalIssue")
if issue is not None:
result["volume"] = issue.findtext("Volume")
result["issue"] = issue.findtext("Issue")
element = article.find("MedlineCitation/Article/Pagination/MedlinePgn")
if element is not None:
pages = element.text
if pages:
pages = pages.split("-")
if len(pages) == 2: # Complete page numbers!
diff = len(pages[0]) - len(pages[1])
if diff > 0:
pages[1] = pages[0][0:diff] + pages[1]
pages = "-".join(pages)
result["pages"] = pages
return result
def get_type(article):
"Get the type from the article XML tree."
element = get_element(article, "MedlineCitation/Article/PublicationTypeList/PublicationType")
if element is not None:
return element.text.lower()
else:
return None
def get_published(article):
"Get the publication date from the article XML tree."
elem = article.find("MedlineCitation/Article/Journal/JournalIssue/PubDate")
date = []
if elem is not None:
date = get_date(elem)
if len(date) < 2: # Fallback 1: ArticleDate
elem = article.find("MedlineCitation/Article/ArticleDate")
if elem is not None:
date = get_date(elem)
if len(date) < 2: # Fallback 2: PubMedPubDate
dates = article.findall("PubmedData/History/PubMedPubDate")
for status in ["epublish", "aheadofprint", "pubmed"]:
for elem in dates:
if elem.get("PubStatus") == status:
date = get_date(elem)
break
if len(date) >= 2: break
if len(date) == 0: # Fallback 3: today's year
d = time.localtime()
date = [d.tm_year, 0, 0]
# Add dummy values, if missing
if len(date) == 1: date.append(0)
if len(date) == 2: date.append(0)
return "%s-%02i-%02i" % tuple(date)
def get_epublished(article):
"Get the online publication date from the article XML tree, or None."
date = []
elem = article.find("MedlineCitation/Article/ArticleDate")
if elem is not None and elem.get("DateType") == "Electronic":
date = get_date(elem)
if len(date) < 2:
dates = article.findall("PubmedData/History/PubMedPubDate")
for status in ["epublish", "aheadofprint", "pubmed"]:
for elem in dates:
if elem.get("PubStatus") == status:
date = get_date(elem)
break
if len(date) >= 2: break
if len(date) == 0: # No date found
return None
# Add dummy values, if missing
if len(date) == 1: date.append(0)
if len(date) == 2: date.append(0)
return "%s-%02i-%02i" % tuple(date)
def get_abstract(article):
"Get the abstract from the article XML tree."
try:
element = get_element(article, "MedlineCitation/Article/Abstract")
except ValueError:
return None
else:
text = []
for elem in element.findall("AbstractText"):
text.append(get_text(elem))
return "\n\n".join([t for t in text if t]).strip()
def get_xrefs(article):
"Get the list of cross-references from the article XML tree."
result = []
for elem in article.findall("PubmedData/ArticleIdList/ArticleId"):
result.append(dict(db=elem.get("IdType"), key=elem.text))
for elem in article.findall("MedlineCitation/Article/DataBankList/DataBank"):
db = elem.findtext("DataBankName")
if not db: continue
for elem2 in elem.findall("AccessionNumberList/AccessionNumber"):
result.append(dict(db=db, key=elem2.text))
return result
def get_element(tree, key):
element = tree.find(key)
if element is None: raise ValueError(f"Could not find '{key}' element.")
return element
def get_date(element):
"Get the [year, month, day] from the element."
year = element.findtext("Year")
if not year:
return []
result = [int(year)]
month = element.findtext("Month")
if not month:
return result
try:
month = int(MONTHS.get(month.lower()[:3], month))
except (TypeError, ValueError):
return result
else:
result.append(month)
day = element.findtext("Day")
try:
day = int(day)
except (TypeError, ValueError):
day = 0
result.append(day)
return result
def get_text(element):
"Get all text from element and its children. Normalize blanks."
text = []
for elem in element.iter():
text.append(elem.text)
text.append(elem.tail)
text = "".join([t for t in text if t])
text = "".join([t for t in text.split("\n")])
text = " ".join([t for t in text.split()])
return text
def to_ascii(value):
"Convert any non-ASCII character to its closest ASCII equivalent."
if value is None: return ""
value = unicodedata.normalize("NFKD", str(value))
return u"".join([c for c in value if not unicodedata.combining(c)])
def squish(value):
"Remove all unnecessary white spaces."
return " ".join([p for p in value.split() if p])
if __name__ == "__main__":
dirname = os.getcwd()
pmids = sys.argv[1:]
if not pmids:
pmids = ["32283633", "8142349", "7525970"]
for pmid in pmids:
data = fetch(pmid, dirname=dirname, debug=True)
print(json.dumps(data, indent=2, ensure_ascii=False))
| mit | 2,347,821,381,237,688,300 | 35.7151 | 111 | 0.589897 | false |
i2y/mochi | mochi/core/global_env.py | 1 | 4977 | from collections import (
Iterable,
Mapping,
MutableMapping,
Sequence,
MutableSequence
)
import sys
import imp
import functools
import itertools
from numbers import Number
import operator
import re
from pyrsistent import (
v, pvector, m, pmap, s, pset, b, pbag, dq, pdeque, l,
plist, immutable, freeze, thaw, CheckedPVector, PVector,
PMap, PSet, PList, PBag
)
from mochi import IS_PYPY, GE_PYTHON_33
from mochi.actor import actor
from mochi.parser import Symbol, Keyword, get_temp_name
if not IS_PYPY:
from annotation.typed import union, options, optional, only, predicate
class AttrDict(dict):
def __getattr__(self, attr):
if attr in self.keys():
return self[attr]
else:
return self['__builtins__'][attr]
def __setattr__(self, attr, value):
self[attr] = value
def make_default_env():
env = AttrDict()
if isinstance(__builtins__, dict):
env.update(__builtins__)
else:
env.update(__builtins__.__dict__)
env['Symbol'] = Symbol
env['Keyword'] = Keyword
env.update(__builtins__.__dict__) if hasattr(__builtins__, '__dict__') else env.update(__builtins__)
del env['exec']
# del env['globals']
# del env['locals']
env.update(functools.__dict__)
env.update(itertools.__dict__)
env.update(operator.__dict__)
env['pow'] = pow
if GE_PYTHON_33:
env['__spec__'] = sys.modules[__name__].__spec__
env[Iterable.__name__] = Iterable
env[Sequence.__name__] = Sequence
env[Mapping.__name__] = Mapping
env['v'] = v
env['pvector'] = pvector
env['CheckedPVector'] = CheckedPVector
env['m'] = m
env['pmap'] = pmap
env['s'] = s
env['pset'] = pset
env['l'] = l
env['plist'] = plist
env['b'] = b
env['pbag'] = pbag
env['dq'] = dq
env['pdeque'] = pdeque
env['thaw'] = thaw
env['freeze'] = freeze
env['immutable'] = immutable
env['PVector'] = PVector
env['PMap'] = PMap
env['PSet'] = PSet
env['PList'] = PList
env['PBag'] = PBag
if not IS_PYPY:
env['union'] = union
env['options'] = options
env['optional'] = optional
env['only'] = only
env['predicate'] = predicate
env[Number.__name__] = Number
env['append'] = MutableSequence.append
# env['clear'] = MutableSequence.clear # not supported (pypy)
env['seq_count'] = MutableSequence.count
env['extend'] = MutableSequence.extend
env['insert'] = MutableSequence.insert
env['pop'] = MutableSequence.pop
env['remove'] = MutableSequence.remove
env['reverse'] = MutableSequence.reverse
env['mapping_get'] = MutableMapping.get
env['items'] = MutableMapping.items
env['values'] = MutableMapping.values
env['keys'] = MutableMapping.keys
env['mapping_pop'] = MutableMapping.pop
env['popitem'] = MutableMapping.popitem
env['setdefault'] = MutableMapping.setdefault
env['update'] = MutableMapping.update
env['values'] = MutableMapping.values
env['doall'] = pvector
env['nth'] = operator.getitem
env['+'] = operator.add
env['-'] = operator.sub
env['/'] = operator.truediv
env['*'] = operator.mul
env['%'] = operator.mod
env['**'] = operator.pow
env['<<'] = operator.lshift
env['>>'] = operator.rshift
env['//'] = operator.floordiv
env['=='] = operator.eq
env['!='] = operator.ne
env['>'] = operator.gt
env['>='] = operator.ge
env['<'] = operator.lt
env['<='] = operator.le
env['not'] = operator.not_
env['and'] = operator.and_
env['or'] = operator.or_
env['is'] = operator.is_
env['isnt'] = operator.is_not
env['re'] = re
env['True'] = True
env['False'] = False
env['None'] = None
env['gensym'] = get_temp_name
env['uniq'] = get_temp_name
env['Record'] = immutable((), 'Record')
env['spawn'] = actor.spawn
env['spawn_with_mailbox'] = actor.spawn_with_mailbox
env['send'] = actor.send
env['recv'] = actor.recv
env['ack_last_msg'] = actor.ack_last_msg
env['ack'] = actor.ack
env['link'] = actor.link
env['unlink'] = actor.unlink
env['kill'] = actor.kill
env['cancel'] = actor.cancel
env['self'] = actor.self
env['sleep'] = actor.sleep
env['wait_all'] = actor.wait_all
env['wait'] = actor.wait
try:
env['__loader__'] = __loader__
except:
pass
env['__package__'] = __package__
env['__doc__'] = __doc__
if IS_PYPY:
from _continuation import continulet
env['continulet'] = continulet
return env
global_env = make_default_env()
global_env['__name__'] = '__main__'
global_env['__package__'] = None
global_env['__spec__'] = None
global_env['__loader__'] = None
global_mod = imp.new_module('__main__')
global_mod.__name__ = '__main__'
global_mod.__package__ = None
global_mod.__spec__ = None
global_mod.__loader__ = None
global_mod.__builtins__ = global_env
| mit | -7,836,404,775,858,200,000 | 28.276471 | 104 | 0.587503 | false |
QuLogic/meson | mesonbuild/scripts/uninstall.py | 1 | 1622 | # Copyright 2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import typing as T
logfile = 'meson-logs/install-log.txt'
def do_uninstall(log: str) -> None:
failures = 0
successes = 0
for line in open(log):
if line.startswith('#'):
continue
fname = line.strip()
try:
if os.path.isdir(fname) and not os.path.islink(fname):
os.rmdir(fname)
else:
os.unlink(fname)
print('Deleted:', fname)
successes += 1
except Exception as e:
print(f'Could not delete {fname}: {e}.')
failures += 1
print('\nUninstall finished.\n')
print('Deleted:', successes)
print('Failed:', failures)
print('\nRemember that files created by custom scripts have not been removed.')
def run(args: T.List[str]) -> int:
if args:
print('Weird error.')
return 1
if not os.path.exists(logfile):
print('Log file does not exist, no installation has been done.')
return 0
do_uninstall(logfile)
return 0
| apache-2.0 | 229,427,990,467,042,980 | 31.44 | 83 | 0.638101 | false |
tinkerinestudio/Tinkerine-Suite | TinkerineSuite/Cura/cura_sf/skeinforge_application/skeinforge_plugins/craft_plugins/joris.py | 1 | 7249 | """
This page is in the table of contents.
The Joris plugin makes the perimiter slowly increase in Z over the layer. This will make vases/cups without a z blob.
==Operation==
The default 'Activate Joris' checkbox is off. When it is on, the Joris plugin will do it's work.
==Settings==
===Layers From===
Default: 1
Defines which layer of the print the joris process starts from.
==Tips==
==Examples==
"""
from __future__ import absolute_import
from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret
from fabmetheus_utilities import archive
from fabmetheus_utilities import gcodec
from fabmetheus_utilities import settings
from skeinforge_application.skeinforge_utilities import skeinforge_craft
from skeinforge_application.skeinforge_utilities import skeinforge_polyfile
from skeinforge_application.skeinforge_utilities import skeinforge_profile
__author__ = 'Daid ([email protected]'
__date__ = '$Date: 2012/24/01 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
def getCraftedText(fileName, gcodeText, repository=None):
'Joris a gcode linear move text.'
return getCraftedTextFromText(archive.getTextIfEmpty(fileName, gcodeText), repository)
def getCraftedTextFromText(gcodeText, repository=None):
'Joris a gcode linear move text.'
if gcodec.isProcedureDoneOrFileIsEmpty(gcodeText, 'Joris'):
return gcodeText
if repository == None:
repository = settings.getReadRepository(JorisRepository())
if not repository.activateJoris.value:
return gcodeText
return JorisSkein().getCraftedGcode(gcodeText, repository)
def getIsMinimumSides(loops, sides=3):
'Determine if all the loops have at least the given number of sides.'
for loop in loops:
if len(loop) < sides:
return False
return True
def getNewRepository():
'Get new repository.'
return JorisRepository()
def writeOutput(fileName, shouldAnalyze=True):
'Joris a gcode linear move file. Chain Joris the gcode if it is not already Jorised.'
skeinforge_craft.writeChainTextWithNounMessage(fileName, 'joris', shouldAnalyze)
class JorisRepository(object):
'A class to handle the Joris settings.'
def __init__(self):
'Set the default settings, execute title & settings fileName.'
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.joris.html', self )
self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Joris', self, '')
self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Joris')
self.activateJoris = settings.BooleanSetting().getFromValue('Activate Joris', self, False)
settings.LabelSeparator().getFromRepository(self)
self.layersFrom = settings.IntSpin().getSingleIncrementFromValue(0, 'Layers From (index):', self, 912345678, 1)
self.executeTitle = 'Joris'
def execute(self):
'Joris button has been clicked.'
fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled)
for fileName in fileNames:
writeOutput(fileName)
class JorisSkein(object):
'A class to Joris a skein of extrusions.'
def __init__(self):
'Initialize.'
self.distanceFeedRate = gcodec.DistanceFeedRate()
self.lines = None
self.layerIndex = -1
self.feedRateMinute = 959.0
self.travelFeedRateMinute = 957.0
self.perimeter = None
self.oldLocation = None
self.doJoris = False
self.firstLayer = True
def getCraftedGcode( self, gcodeText, repository ):
'Parse gcode text and store the joris gcode.'
self.lines = archive.getTextLines(gcodeText)
self.repository = repository
self.layersFromBottom = repository.layersFrom.value
self.parseInitialization()
for self.lineIndex in xrange(self.lineIndex, len(self.lines)):
line = self.lines[self.lineIndex]
self.parseLine(line)
return gcodec.getGcodeWithoutDuplication('M108', self.distanceFeedRate.output.getvalue())
def parseInitialization(self):
'Parse gcode initialization and store the parameters.'
for self.lineIndex in xrange(len(self.lines)):
line = self.lines[self.lineIndex]
splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
firstWord = gcodec.getFirstWord(splitLine)
self.distanceFeedRate.parseSplitLine(firstWord, splitLine)
if firstWord == '(<layerThickness>':
self.layerThickness = float(splitLine[1])
elif firstWord == '(</extruderInitialization>)':
self.distanceFeedRate.addTagBracketedProcedure('joris')
return
elif firstWord == '(<travelFeedRatePerSecond>':
self.travelFeedRateMinute = 60.0 * float(splitLine[1])
self.distanceFeedRate.addLine(line)
def parseLine(self, line):
'Parse a gcode line and add it to the joris skein.'
splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
if len(splitLine) < 1:
return
firstWord = splitLine[0]
if firstWord == 'G1' and self.doJoris:
self.feedRateMinute = gcodec.getFeedRateMinute(self.feedRateMinute, splitLine)
location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine)
self.oldLocation = location
if self.perimeter != None:
self.perimeter.append(location.dropAxis())
return
elif firstWord == '(<layer>':
self.layerIndex += 1
settings.printProgress(self.layerIndex, 'joris')
elif firstWord == 'M108':
self.oldFlowRate = gcodec.getDoubleAfterFirstLetter(splitLine[1])
elif firstWord == '(<edge>':
if self.layerIndex >= self.layersFromBottom:
self.doJoris = True
elif firstWord == 'M101' and self.doJoris:
self.perimeter = []
return
elif firstWord == 'M103' and self.doJoris:
self.addJorisedPerimeter()
return
elif firstWord == '(</edge>)':
self.doJoris = False
self.distanceFeedRate.addLine(line)
def addJorisedPerimeter(self):
'Add jorised perimeter.'
if self.perimeter == None:
return
#Calculate the total length of the perimeter.
p = self.oldLocation.dropAxis()
perimeterLength = 0;
for point in self.perimeter:
perimeterLength += abs( point - p );
p = point
#Build the perimeter with an increasing Z over the length.
if self.firstLayer:
#On the first layer, we need to create an extra jorised perimeter, else we create a gap at the end of the perimeter.
p = self.oldLocation.dropAxis()
length = 0;
self.distanceFeedRate.addLine('M101') # Turn extruder on.
for point in self.perimeter:
length += abs( point - p );
p = point
self.distanceFeedRate.addGcodeMovementZWithFeedRate(self.feedRateMinute, point, self.oldLocation.z - self.layerThickness + self.layerThickness * length / perimeterLength)
self.distanceFeedRate.addLine('M103') # Turn extruder off.
self.firstLayer = False
p = self.oldLocation.dropAxis()
length = 0;
self.distanceFeedRate.addLine('M101') # Turn extruder on.
for point in self.perimeter:
length += abs( point - p );
p = point
self.distanceFeedRate.addGcodeMovementZWithFeedRate(self.feedRateMinute, point, self.oldLocation.z + self.layerThickness * length / perimeterLength)
self.distanceFeedRate.addLine('M103') # Turn extruder off.
self.perimeter = None
| agpl-3.0 | -5,983,618,361,555,960,000 | 37.354497 | 180 | 0.756518 | false |
nathanleclaire/WALinuxAgent | setup.py | 1 | 6645 | #!/usr/bin/env python
#
# Microsoft Azure Linux Agent setup.py
#
# Copyright 2013 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
from azurelinuxagent.metadata import AGENT_NAME, AGENT_VERSION, \
AGENT_DESCRIPTION, \
DISTRO_NAME, DISTRO_VERSION, DISTRO_FULL_NAME
from azurelinuxagent.agent import Agent
import setuptools
from setuptools import find_packages
from setuptools.command.install import install as _install
root_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(root_dir)
def set_files(data_files, dest=None, src=None):
data_files.append((dest, src))
def set_bin_files(data_files, dest="/usr/sbin",
src=["bin/waagent", "bin/waagent2.0"]):
data_files.append((dest, src))
def set_conf_files(data_files, dest="/etc", src=["config/waagent.conf"]):
data_files.append((dest, src))
def set_logrotate_files(data_files, dest="/etc/logrotate.d",
src=["config/waagent.logrotate"]):
data_files.append((dest, src))
def set_sysv_files(data_files, dest="/etc/rc.d/init.d", src=["init/waagent"]):
data_files.append((dest, src))
def set_systemd_files(data_files, dest="/lib/systemd/system",
src=["init/waagent.service"]):
data_files.append((dest, src))
def get_data_files(name, version, fullname):
"""
Determine data_files according to distro name, version and init system type
"""
data_files=[]
if name == 'redhat' or name == 'centos':
set_bin_files(data_files)
set_conf_files(data_files)
set_logrotate_files(data_files)
if version.startswith("6"):
set_sysv_files(data_files)
else:
#redhat7.0+ use systemd
set_systemd_files(data_files, dest="/usr/lib/systemd/system")
if version.startswith("7.1"):
#TODO this is a mitigation to systemctl bug on 7.1
set_sysv_files(data_files)
elif name == 'coreos':
set_bin_files(data_files, dest="/usr/share/oem/bin")
set_conf_files(data_files, dest="/usr/share/oem",
src=["config/coreos/waagent.conf"])
set_logrotate_files(data_files)
set_files(data_files, dest="/usr/share/oem",
src="init/coreos/cloud-config.yml")
elif name == 'ubuntu':
set_bin_files(data_files)
set_conf_files(data_files, src=["config/ubuntu/waagent.conf"])
set_logrotate_files(data_files)
if version.startswith("12") or version.startswith("14"):
#Ubuntu12.04/14.04 - uses upstart
set_files(data_files, dest="/etc/init",
src=["init/ubuntu/walinuxagent.conf"])
set_files(data_files, dest='/etc/default',
src=['init/ubuntu/walinuxagent'])
elif fullname == 'Snappy Ubuntu Core':
set_files(data_files, dest="<TODO>",
src=["init/ubuntu/snappy/walinuxagent.yml"])
else:
#Ubuntu15.04+ uses systemd
set_systemd_files(data_files,
src=["init/ubuntu/walinuxagent.service"])
elif name == 'suse':
set_bin_files(data_files)
set_conf_files(data_files, src=["config/suse/waagent.conf"])
set_logrotate_files(data_files)
if fullname == 'SUSE Linux Enterprise Server' and \
version.startswith('11') or \
fullname == 'openSUSE' and version.startswith('13.1'):
set_sysv_files(data_files, dest='/etc/init.d',
src=["init/suse/waagent"])
else:
#sles 12+ and openSUSE 13.2+ use systemd
set_systemd_files(data_files, dest='/usr/lib/systemd/system')
else:
#Use default setting
set_bin_files(data_files)
set_conf_files(data_files)
set_logrotate_files(data_files)
set_sysv_files(data_files)
return data_files
class install(_install):
user_options = _install.user_options + [
# This will magically show up in member variable 'init_system'
('init-system=', None, 'deprecated, use --lnx-distro* instead'),
('lnx-distro=', None, 'target Linux distribution'),
('lnx-distro-version=', None, 'target Linux distribution version'),
('lnx-distro-fullname=', None, 'target Linux distribution full name'),
('register-service', None, 'register as startup service'),
('skip-data-files', None, 'skip data files installation'),
]
def initialize_options(self):
_install.initialize_options(self)
self.init_system=None
self.lnx_distro = DISTRO_NAME
self.lnx_distro_version = DISTRO_VERSION
self.lnx_distro_fullname = DISTRO_FULL_NAME
self.register_service = False
self.skip_data_files = False
def finalize_options(self):
_install.finalize_options(self)
if self.skip_data_files:
return
if self.init_system is not None:
print("WARNING: --init-system is deprecated,"
"use --lnx-distro* instead")
data_files = get_data_files(self.lnx_distro, self.lnx_distro_version,
self.lnx_distro_fullname)
self.distribution.data_files = data_files
self.distribution.reinitialize_command('install_data', True)
def run(self):
_install.run(self)
if self.register_service:
Agent(False).register_service()
setuptools.setup(name=AGENT_NAME,
version=AGENT_VERSION,
long_description=AGENT_DESCRIPTION,
author= 'Yue Zhang, Stephen Zarkos, Eric Gable',
author_email = '[email protected]',
platforms = 'Linux',
url='https://github.com/Azure/WALinuxAgent',
license = 'Apache License Version 2.0',
packages=find_packages(exclude=["tests"]),
cmdclass = {
'install': install
})
| apache-2.0 | -641,448,069,657,263,000 | 39.03012 | 82 | 0.600752 | false |
polarsbear/ThreeDPi | Bipolar_Stepper_Motor_Class_Full_Step.py | 1 | 2366 | import RPi.GPIO as GPIO
import time
#sequence for a1, b2, a2, b1
phase_seq=[[1,1,0,0],[0,1,1,0],[0,0,1,1],[1,0,0,1]];
#full step sequence. maximum torque
#phase_seq=[[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,1,1,0],[0,0,1,0],[0,0,1,1],[0,0,0,1],[1,0,0,1]]
#half-step sequence. double resolution. But the torque of the stepper motor is not constant
num_phase=len(phase_seq);
class Bipolar_Stepper_Motor_Full_Step:
phase=0;
dirction=0;
position=0;
a1=0;#pin numbers
a2=0;
b1=0;
b2=0;
def __init__(self,a1,a2,b1,b2):
#initial a Bipolar_Stepper_Moter objects by assigning the pins
GPIO.setmode(GPIO.BCM);
self.a1=a1;
self.a2=a2;
self.b1=b1;
self.b2=b2;
GPIO.setup(self.a1,GPIO.OUT);
GPIO.setup(self.a2,GPIO.OUT);
GPIO.setup(self.b1,GPIO.OUT);
GPIO.setup(self.b2,GPIO.OUT);
GPIO.output(self.a1,0);
GPIO.output(self.a2,0);
GPIO.output(self.b1,0);
GPIO.output(self.b2,0);
print("Stepper Configured");
self.phase=0;
self.dirction=0;
self.position=0;
def move(self, dirction, steps, delay=0.2):
for _ in range(steps):
next_phase=(self.phase+dirction) % num_phase;
if phase_seq[next_phase][0] ==1:
GPIO.output(self.a1,phase_seq[next_phase][0]);
if phase_seq[next_phase][1] ==1:
GPIO.output(self.b2,phase_seq[next_phase][1]);
if phase_seq[next_phase][2] ==1:
GPIO.output(self.a2,phase_seq[next_phase][2]);
if phase_seq[next_phase][3] ==1:
GPIO.output(self.b1,phase_seq[next_phase][3]);
GPIO.output(self.a1,phase_seq[next_phase][0]);
GPIO.output(self.b2,phase_seq[next_phase][1]);
GPIO.output(self.a2,phase_seq[next_phase][2]);
GPIO.output(self.b1,phase_seq[next_phase][3]);
self.phase=next_phase;
self.dirction=dirction;
self.position+=dirction;
time.sleep(delay);
def unhold(self):
GPIO.output(self.a1,0);
GPIO.output(self.a2,0);
GPIO.output(self.b1,0);
GPIO.output(self.b2,0);
| lgpl-2.1 | -3,164,008,024,690,108,000 | 29.727273 | 92 | 0.522401 | false |
nickkonidaris/kpy | SEDMr/Wavelength.py | 1 | 55908 | import argparse
import pdb
from multiprocessing import Pool
import numpy as np
import os
import pylab as pl
import pyfits as pf
import scipy
import sys
import datetime
import NPK.Fit
import NPK.Bar as Bar
from astropy.table import Table
from scipy.spatial import KDTree
import scipy.signal as SG
from numpy.polynomial.chebyshev import chebfit, chebval
import SEDMr.Extraction as Extraction
from scipy.interpolate import interp1d
reload(NPK.Fit)
reload(Extraction)
from numpy import NaN, Inf, arange, isscalar, asarray, array
def peakdet(v, delta, x = None):
"""
Converted from MATLAB script at http://billauer.co.il/peakdet.html
Returns two arrays
function [maxtab, mintab]=peakdet(v, delta, x)
%PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consists of two columns. Column 1
% contains indices in V, and column 2 the found values.
%
% With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices
% in MAXTAB and MINTAB are replaced with the corresponding
% X-values.
%
% A point is considered a maximum peak if it has the maximal
% value, and was preceded (to the left) by a value lower by
% DELTA.
% Eli Billauer, 3.4.05 (Explicitly not copyrighted).
% This function is released to the public domain; Any use is allowed.
"""
maxtab = []
mintab = []
if x is None:
x = arange(len(v))
v = asarray(v)
if len(v) != len(x):
sys.exit('Input vectors v and x must have same length')
if not isscalar(delta):
sys.exit('Input argument delta must be a scalar')
if delta <= 0:
sys.exit('Input argument delta must be positive')
mn, mx = Inf, -Inf
mnpos, mxpos = NaN, NaN
lookformax = True
for i in arange(len(v)):
this = v[i]
if this > mx:
mx = this
mxpos = x[i]
if this < mn:
mn = this
mnpos = x[i]
if lookformax:
if this < mx-delta:
maxtab.append((mxpos, mx))
mn = this
mnpos = x[i]
lookformax = False
else:
if this > mn+delta:
mintab.append((mnpos, mn))
mx = this
mxpos = x[i]
lookformax = True
return array(maxtab), array(mintab)
def read_catalog(catname):
'''Read a sextractor catalog called catname and return'''
cat = Table.read(catname, format='ascii.sextractor')
return cat
def hg_to_kdtree(assoc_hg_spec):
'''Convert mercury association to a KD Tree'''
xs = []
ys = []
ids = []
for id,f in enumerate(assoc_hg_spec):
if not f.has_key(546.1): continue
xs.append(f[546.1])
ff = np.poly1d(f['coeff_ys'])
ys.append(ff(xs[-1]))
ids.append(f['seg_cnt'])
data = np.array([xs,ys])
return KDTree(data.T), np.array(ids)
def fiducial_spectrum(lamstart=1050.0, lamratio=239./240., len=265):
'''Return a typical SED Machine spectrum, use for interpolating on grid
x
Equation looks like 1000 x (239/240)
Args:
lamstart(float): default is 1050 nm
lamratio(float): default is 239/240, good for SEDM
len(int): default of 265 yields a spectrum that goes to ~ 350 nm'''
xx = np.arange(len)
return lamstart * lamratio**xx
def assoc_hg_with_flats_helper(idx):
global domedat, hgcat, guess_offset, wavetrees
spec_pos = domedat[idx]
if not spec_pos['ok']: return None
tracefun = np.poly1d(spec_pos['coeff_ys'])
minx = spec_pos['xs'][0]
to_return = {}
for wavelen,v in wavetrees.iteritems():
offset = guess_offset[wavelen]
pt = (minx + offset, tracefun(minx+offset))
results = v.query_ball_point(pt, 15)
for res in results:
x_hg,y_hg = v.data[res]
y_trace = tracefun(x_hg)
if np.abs(y_hg - y_trace) < 3:
to_return[wavelen] = x_hg
print "%4.4i : %s" % (idx, to_return)
return to_return
def assoc_hg_with_flats(domedat_par, hgcat_par, guess_offset_par= {365.0: 231,
404.6:214, 435.8:193, 546.1: 133, 578.00: 110}, outname='assoc_Hg'):
'''Given a set of functions defining the ridgeline of dome flats
and a list of positions of mercury lamps, provide a crude wavelength
solution
Args:
guess_offset: Dictionary of {wavelength in nm: x position} indicating
the rough distance from the segment start to the wavelength
'''
global domedat, hgcat, guess_offset, wavetrees
domedat = domedat_par
hgcat = hgcat_par
guess_offset = guess_offset_par
wavetrees = {}
for k,v in hgcat.iteritems():
wavetrees[k] = KDTree(v)
p = Pool(8)
results = p.map(assoc_hg_with_flats_helper, range(len(domedat)))
p.close()
for idx, spec_pos in enumerate(domedat):
if results[idx] is None:
continue
for wave, pos in results[idx].iteritems():
spec_pos[wave] = pos
np.save("%s.npy" % outname, [domedat])
return spec_pos
def find_hg_spectra(lines, dYlimit=2, outname="find_spectra"):
'''Based on line ratios and positions, determine positions of Hg lines
Args:
lines: line list
dYlimit:
Results:
Writes [return value] to outname in npy format
Return:
Returns dictionary of {wavelength nm: [(pixel coords) ...], ...}
Each wavelength has a list of pixel coords of different length.
The coordinates are diassociated from one and other.
'''
data = []
for line in lines:
data.append((line['X_IMAGE'], line['Y_IMAGE']))
data = np.array(data)
kdt = KDTree(data)
reg = ""
ratios = []
hg546 = []
hg578 = []
hg436 = []
hg405 = []
hg365 = []
update_rate = len(lines) / Bar.setup()
for CNT, line in enumerate(lines):
if CNT % update_rate == 0: Bar.update()
point = [line['X_IMAGE'], line['Y_IMAGE']]
results = kdt.query_ball_point(point, 38)
X, Y = point
num = line['NUMBER']
flux = float(line['FLUX_ISO'])
mean_flux = np.median(flux)/2
for resix in results:
resX, resY = data[resix]
resFlux = float(lines[resix]['FLUX_ISO'])
dist = np.abs(resX-X)
dX = resX - X
dY = np.abs(resY - Y)
if dY > dYlimit: continue
if resFlux < 500: continue
ratio = flux/resFlux
bright = (flux > mean_flux)
resbright = (resFlux > mean_flux)
if (2 < ratio < 7) and (-16 < dX < -12) and bright:
reg += 'circle(%s,%s, 3) # color=red\n' % (X, Y)
reg += 'circle(%s,%s, 3) # color=magenta\n' % (resX, resY)
hg546.append((X,Y))
hg578.append((resX,resY))
continue
if (1/6. < ratio < 2) and (-24 < dX < -18) and resbright:
hg405.append((X,Y))
hg436.append((resX,resY))
reg += 'circle(%s,%s, 3) # color=green\n' % (X, Y)
reg += 'circle(%s,%s, 3) # color=yellow\n' % (resX, resY)
continue
if (4 < ratio < 70) and (20 < dX < 38) and bright and (not resbright):
hg365.append((resX,resY))
reg += 'circle(%s,%s, 3) # color=blue\n' % (resX, resY)
continue
f = open(outname + ".reg", "w")
f.write(reg)
f.close()
res = [{365.0: np.array(hg365),
404.6: np.array(hg405),
435.8: np.array(hg436),
546.1: np.array(hg546),
578.00: np.array(hg578)}]
np.save(outname, res)
Bar.done()
return res[0]
def fractional_sum(FS_Y, FS_EW, FS_dat, FS_Yx1):
''' Returns sum of FS_dat via a partial-pixel method.
Args:
FS_Y(float): location of trace in vertical direciton
FS_EW(float): Width of trace around FS_Y
FS_dat(float vector): Data to sum
FS_Yx1(float): Start location of data
Returns:
Float containing the sum of data in FS_Y while taking partial
pixels into account.
Raises:
Nothing.
'''
nn = len(FS_dat)
YB1 = FS_Y - FS_EW
YB2 = FS_Y + FS_EW
FSsum = 0.0
for ii in range(nn):
Yp1 = float(ii+FS_Yx1) - 0.5
Yp2 = float(ii+FS_Yx1) + 0.5
frac= 0.0
# fully contained?
if Yp1 > YB1 and Yp2 < YB2:
frac = 1.0
# pixel surrounds left boundary
elif Yp1 < YB1 and Yp2 > YB1:
frac = (Yp2 - YB1) / (Yp2 - Yp1)
# pixel surrounds right boundary
elif Yp2 > YB2 and Yp1 < YB2:
frac = (YB2 - Yp1) / (Yp2 - Yp1)
FSsum = FSsum + (frac * FS_dat[ii])
return FSsum
def make_profile(slice, sigma2=4):
''' Return a gaussian profile with the same dimensions as the slice '''
profile = np.arange(np.round(slice.stop)-np.round(slice.start))
profile -= (len(profile)-1)/2.0
profile = np.exp(- profile*profile/(2*sigma2))
profile /= np.mean(profile)
return profile
def wavelength_extract_helper(SS):
global dat, exptime, wavecalib, HDUlist, extract_width, flt_corrs
ix, flexure_x_corr_nm, flexure_y_corr_pix = SS
ss = wavecalib[ix]
if not ss.ok:
return Extraction.Extraction(seg_id=ss.seg_id,
ok=False, trace_sigma=ss.trace_sigma, Q_ix=ss.Q_ix,
R_ix=ss.R_ix, X_as=ss.X_as, Y_as=ss.Y_as)
minx = np.max((0,ss.xrange[0]-5))
maxx = np.min((minx + 265,2047))
yfun = np.poly1d(ss.poly)
xpos = xrange(minx, maxx)
res = np.zeros(len(xpos))
res[:] = np.nan
resw = np.zeros(len(xpos))
resw[:] = np.nan
resf = np.zeros(len(xpos))
resf[:] = np.nan
reswf = np.zeros(len(xpos))
reswf[:] = np.nan
sigma2 = ss.trace_sigma * ss.trace_sigma
if np.isnan(sigma2): sigma2 = 4.
for i in xrange(len(xpos)):
X = xpos[i]
Y = yfun(X)
if Y < 0: Y = 0
if Y > 2046: Y=2046
if not np.isfinite(X) or not np.isfinite(Y):
continue
# Extract width requires asymmetry in the slice
# slice[-2:3] will return elements -2 to +2 around 0
# e.g. len(slice[-2:3]) == 5
Ys = slice(
np.max((0,np.round(Y)+flexure_y_corr_pix-extract_width)),
np.min((np.round(Y)+flexure_y_corr_pix+extract_width+1, 2047)))
# Expanded slice for fractional pixels
Yx = slice(
np.max((0,np.round(Y)+flexure_y_corr_pix-extract_width-1)),
np.min((np.round(Y)+flexure_y_corr_pix+extract_width+2, 2047)))
res[i] = np.sum(dat[Ys,X])
profile = make_profile(Ys, sigma2=sigma2)
resw[i]= np.sum(dat[Ys,X]*profile)
resf[i]= fractional_sum(Y, extract_width, dat[Yx,X], Yx.start)
profile = make_profile(Yx, sigma2=sigma2)
reswf[i]= fractional_sum(Y, extract_width, dat[Yx,X]*profile, Yx.start)
try:
ll = chebval(np.arange(minx,maxx),ss.lamcoeff)
fc = flt_corrs[ix].get_correction(ll)
except:
fc = 1.0
ex = Extraction.Extraction(xrange=(minx,maxx), yrange=(yfun(xpos[0]),
yfun(xpos[-1])),
poly=ss.poly, spec=res,
specw=resw/fc,
specf=resf/fc,
specwf=reswf/fc,
seg_id=ss.seg_id, exptime=exptime, ok=True,
trace_sigma=ss.trace_sigma, Q_ix=ss.Q_ix,
R_ix=ss.R_ix, X_as=ss.X_as, Y_as=ss.Y_as)
if ss.__dict__.has_key('lamcoeff') and ss.lamcoeff is not None:
ex.lamcoeff = ss.lamcoeff.copy()
ex.lamcoeff[0] -= flexure_x_corr_nm
ex.lamrms = ss.lamrms
if ss.__dict__.has_key('mdn_coeff') and ss.mdn_coeff is not None:
ex.mdn_coeff = ss.mdn_coeff.copy()
ex.mdn_coeff[0] -= flexure_x_corr_nm
ex.lamrms = ss.lamrms
if ex.lamrms is not None:
print "%4.4i %1.4f (%s)" % (ex.seg_id, ex.lamrms, fc)
return ex
def wavelength_extract(HDUlist_par, wavecalib_par, filename='extracted_spectra.npy',
flexure_x_corr_nm = 0.0, flexure_y_corr_pix = 0.0, extract_width_par=3,
inname='unknown', airmass=None, flat_corrections=None):
global dat, exptime, wavecalib, HDUlist, extract_width, flt_corrs
extract_width = extract_width_par
HDUlist = HDUlist_par
wavecalib = wavecalib_par
flt_corrs = np.copy(flat_corrections)
dat = HDUlist[0].data
exptime = HDUlist[0].header['EXPTIME']
print "Applying %f/%f offset" % (flexure_x_corr_nm, flexure_y_corr_pix)
flexure_y_corr_pix = np.round(flexure_y_corr_pix)
SSs = [ (ix, flexure_x_corr_nm, flexure_y_corr_pix)
for ix in range(len(wavecalib))]
p = Pool(8)
extractions = p.map(wavelength_extract_helper, SSs)
p.close()
meta = {"inname": inname, "extract_width": extract_width_par,
"when": "%s" % datetime.datetime.now(),
"user": os.getlogin(),
"flexure_x_corr_nm": flexure_x_corr_nm,
"flexure_y_corr_pix": flexure_y_corr_pix,
"outname": filename}
return [extractions, meta]
def extract_helper(ss):
''' TODO: MERGE WITH wavelength_extract_helper.
Functionallity is repeated.'''
global dat
if not ss['ok']:
return Extraction.Extraction(seg_id=ss['seg_cnt'],
trace_sigma=ss['trace_sigma'], ok=False)
minx = np.max((0,ss['xs'][0]-5))
maxx = np.min((minx + 265,2047))
yfun = np.poly1d(ss['coeff_ys'])
xpos = xrange(minx, maxx)
res = np.zeros(len(xpos))
res[:] = np.nan
resw = np.zeros(len(xpos))
resw[:] = np.nan
resf = np.zeros(len(xpos))
resf[:] = np.nan
reswf = np.zeros(len(xpos))
reswf[:] = np.nan
sigma2 = ss['trace_sigma']*ss['trace_sigma']
if np.isnan(sigma2): sigma2 = 4.
extract_width = 2
for i in xrange(len(xpos)):
X = xpos[i]
Y = yfun(X)
if Y < 0: Y = 0
if Y > 2046: Y = 2046
if not np.isfinite(X) or not np.isfinite(Y):
continue
Ys = slice(np.max((0,np.int(Y)-3)),np.min((np.int(Y)+3, 2047)))
# Expanded slice for fractional pixels
Yx = slice(
np.max((0,np.round(Y)-extract_width-1)),
np.min((np.round(Y)+extract_width+2, 2047)))
res[i] = np.sum(dat[Ys,X])
# BUG: calling resw what should be resf, this is a cheap workaround
# for now.
resw[i]= fractional_sum(Y, extract_width, dat[Yx,X], Yx.start)
hg_lines = {}
for wave, pix in ss.iteritems():
if type(wave) is float:
hg_lines[wave] = pix-minx-1
return Extraction.Extraction(xrange=(minx,maxx), yrange=(yfun(xpos[0]),
yfun(xpos[-1])),
poly=ss['coeff_ys'], spec=res, specw=resw,
hg_lines=hg_lines, seg_id=ss['seg_cnt'],
ok=True, trace_sigma=ss['trace_sigma'])
def extract(HDUlist, assoc_hg_spec, filename='raw_extractions'):
global dat
dat = HDUlist[0].data
extractions = []
p = Pool(8)
extractions = p.map(extract_helper, assoc_hg_spec)
p.close()
np.save(filename, extractions)
return extractions
def median_fine_grid(fine):
''' Using the 7 nearest neighbors, median the wavelength solution. Refit the wavelength solution to this median wavelength.
Input:
fine: Dictionary that contains the fine wavelength solution
Returns:
fine.mdn_coeff contains updated chebyshev polynomial coefficients '''
xs = []
ys = []
ids = []
for gix, g in enumerate(fine):
# Create X, Y, and ID vector.
if not g.ok:
xs.append(-999)
ys.append(-999)
ids.append(None)
continue
xs.append(np.mean(g.xrange))
ys.append(np.mean(g.yrange))
ids.append(g.seg_id)
xs,ys,ids = map(np.array, [xs,ys,ids])
dat = np.array((xs,ys)).T
dat[dat != dat] = -999 # Correct NaNs
KD = KDTree(dat)
assert(len(ids) == len(fine))
ixs = np.arange(0, 265, 1)
for idx, spec in enumerate(fine):
seg_id = spec.seg_id
loc = dat[seg_id-1]
if ids[idx] is None: continue
dist, nearest_ixs = KD.query(loc, k=20)
lls = []
num_in = 0
shifts = []
for nearest in nearest_ixs[1:]:
if nearest is None: continue
if fine[nearest].hgcoef is None: continue
if fine[nearest].lamcoeff is None: continue
if fine[nearest].lamrms > 0.4: continue
if np.abs(fine[nearest].xrange[1] - fine[nearest].xrange[0]) < 50: continue
xx = np.arange(265)
ll = chebval(xx+fine[nearest].xrange[0], fine[nearest].lamcoeff)
if np.any(np.diff(ll) > 0): continue
lls.append(ll)
num_in += 1
if num_in > 30: break
lls = np.array(lls, dtype=np.float)
if len(lls) == 0:
spec.mdn_coeff = spec.lamcoeff
continue
try: new_lls = scipy.stats.nanmedian(lls, 0)
except:
import pdb
pdb.set_trace()
diff = (lls - new_lls) / new_lls
stds = scipy.stats.nanstd(diff, 0)
bad = np.abs(diff/stds) > 4
if bad.any():
lls[bad] = np.nan
new_lls = scipy.stats.nanmedian(lls, 0)
diff = (lls - new_lls) / new_lls
stds = scipy.stats.nanstd(diff, 0)
bad = np.abs(diff/stds) > 2
if bad.any():
lls[bad] = np.nan
new_lls = scipy.stats.nanmedian(lls, 0)
new_lls = scipy.stats.nanmedian(lls, 0)
spec.mdn_coeff = chebfit(np.arange(len(new_lls))+spec.xrange[0],
new_lls, 3)
pl.figure(3)
pl.clf()
pl.xlim(360, 550)
pl.ioff()
pl.figure(4)
pl.clf()
pl.xlim(360, 550)
pl.ioff()
for g in fine:
if g.mdn_coeff is None: continue
if g.specw is None: continue
if g.hgcoef is None: continue
if len(g.specw) < 30: continue
if g.xrange[0] < 100: continue
if g.xrange[0] > 1900: continue
if g.yrange[0] < 100: continue
if g.yrange[0] > 1900: continue
ix = np.arange(len(g.specw))
pl.figure(3)
ll = chebval(ix+g.xrange[0], g.mdn_coeff)
pl.plot(ll, g.specw, '.')
pl.figure(4)
try:
ll = chebval(ix+g.xrange[0], g.lamcoeff)
pl.plot(ll, g.specw, '.')
except: pass
pl.ion()
pl.show()
return fine
def median_rough_grid(gridded, Hg_E, outname='median_rough_wavelength.npy'):
''' Using the 7 nearest neighbors, median the wavelength solution coefficients '''
this_code_is_of_very_little_use()
'''
median_rough grid was used to test the idea
as of 20 jan 2015, the algorithm tested by this code does not
work.
'''
xs = []
ys = []
ids = []
for gix, g in enumerate(gridded):
if not g.ok: continue
if 546.1 not in g.hg_lines: continue
xs.append(g.hg_lines[546.1] + g.xrange[0])
ys.append(np.mean(g.yrange))
ids.append(g.seg_id)
xs,ys,ids = map(np.array, [xs,ys,ids])
dat = np.array((xs,ys)).T
KD = KDTree(dat)
for ix, id in enumerate(ids):
loc = dat[ix]
dist, nearest_ixs = KD.query(loc, k=14)
#print dist, nearest_ixs
lls = []
num_in = 0
for nix, nearest in enumerate(ids[nearest_ixs]):
#print nearest, dist[nix]
#if dist[nix] > 100: continue
if gridded[nearest-1].hgcoef is None: continue
xx = np.arange(265)
ll = chebval(xx, gridded[nearest-1].hgcoef)
if np.any(np.diff(ll) > 0): continue
lls.append(ll)
num_in += 1
if num_in > 30: break
if len(lls) == 0:
import pdb
pdb.set_trace()
lls = np.array(lls)
if idx > 500:
import pdb
pdb.set_trace()
try:
new_lls = scipy.stats.nanmedian(lls, 0)
new_lls_std = scipy.stats.nanstd(lls, 0)
except:
import pdb
pdb.set_trace()
diff = (lls - new_lls) / new_lls
bad = np.abs(diff) > .05
lls[bad] = np.nan
new_lls = scipy.stats.nanmedian(lls, 0)
diff = (lls - new_lls) / new_lls
bad = np.abs(diff) > .05
lls[bad] = np.nan
new_lls = scipy.stats.nanmedian(lls, 0)
gridded[ix].mdn_hgcoef = chebfit(np.arange(len(new_lls)), new_lls, 4)
import pdb
pdb.set_trace()
pl.figure(3)
pl.clf()
pl.xlim(360, 1100)
pl.ioff()
for g in gridded:
if "mdn_hgcoef" not in g.__dict__: continue
if g.specw is None: continue
if g.hgcoef is None: continue
if len(g.specw) < 30: continue
ix = np.arange(len(g.specw))
ll = chebval(ix, g.mdn_hgcoef)
pl.plot(ll, g.specw, '.')
pl.ion()
pl.show()
import pdb
pdb.set_trace()
def scale_on_547(spec):
if spec is None: return None
if spec.spec is None: return None
if spec.hgcoef is None: return None
ix = np.arange(0, len(spec.specw), .1)
ix_547 = np.argmin(np.abs(chebval(ix, spec.hgcoef) - 547.0))
scale = np.arange(len(spec.specw)) - ix[ix_547]
return scale
def stretch_fit_helper(specno):
''' Helper for Multiprocessing Pool'''
global pix_coeffs, fid_ix, fs1, fs2, slopes, squares, specs, funs
spec = specs[specno]
if spec is None: return None
xcs1 = np.zeros((len(slopes), len(squares)))
xcs2 = np.zeros((len(slopes), len(squares)))
s1f, s2f = funs[specno]
for i, slope in enumerate(slopes):
for j, square in enumerate(squares):
# Step 4
ns1 = s1f(fid_ix * slope + fid_ix**2 * square)
ns2 = s2f(fid_ix * slope + fid_ix**2 * square)
xcs1[i,j] = np.nansum(fs1*fs1*ns1*ns1)
xcs2[i,j] = np.nansum(fs2*fs2*ns2*ns2)
slope1, square1 = np.unravel_index(np.argmax(xcs1), xcs1.shape)
slope2, square2 = np.unravel_index(np.argmax(xcs2), xcs2.shape)
ix1 = fid_ix * slopes[slope1] + fid_ix**2 * squares[square1]
ix2 = fid_ix * slopes[slope2] + fid_ix**2 * squares[square2]
tofit = np.zeros(len(ix1))
tofit[0:150] = ix2[0:150]
tofit[150:] = ix1[150:]
# Step 5
fc = chebfit(fid_ix, tofit, 2)
xc = (xcs1[slope1, square1] + xcs2[slope2, square2] ) / np.nansum(fs1)
print "%4.0i = %1.3e : %1.3f %+1.2e, %1.3f %+1.2e" % (specno, xc,slopes[slope1], squares[square1], slopes[slope2], squares[square2])
if False:
pl.figure(4)
pl.plot(fid_ix, s1f(tofit)+s2f(tofit))
import pdb
pdb.set_trace()
return fc, xc
def get_stretched(fid_ix, coeffs, spec1, spec2=None):
''' Reinterpolate spec1 and spec2 onto the fiducial index set by stretching and scaling the spectra
This is used after a call that looks something like:
ll = np.load("Hg_ext.npy")
lx = np.load("Xe_ext.npy")
gg = rough_grid(ll)
coeffs, fix = stretch_set(gg, lx)
s1, s2 = get_stretched(fix, coeffs[5], ll[5], lx[5])
Returns:
s1, s2 [float(len(fid_ix))]: Spectra'''
newix = chebval(fid_ix, coeffs)
ix = scale_on_547(spec1)
sf1 = interp1d(ix, spec1.specw, bounds_error=False, fill_value=0)
if spec2 is None: sf2 = lambda x: 0.0
else:
sf2 = interp1d(ix, spec2.specw, bounds_error=False, fill_value=0)
s1 = sf1(newix)
s2 = sf2(newix)
return s1/s1.mean()*spec1.specw.mean(), s2/s2.mean()*spec2.specw.mean()
def stretch_set(Hg_set, Xe_set, mscales=None):
''' Shift and stretch spectra so they have the same pixel index
Steps:
1. Shift spectra without interpolation onto a common pixel grid with index 0 being a prominent Hg line.
2. Create a set of interpolating functions for each of the spectra in the set. These functions are called as flux(pixel).
3. Brute force search for the best stretch and 2nd-order polynomial coefficient for each spectrum in the set, compared to the fiducial spectrum.
4. Brute force will measure the above for the xenon and mercury spectra indepdentnly.
5. Then we stitch together a master pixel shift based on a chebyshev fit of the xenon and mercury spectra. The chebyshev fit creates a function such that f(pixel) --> pixel. On this new grid, all spectra are close to the same.
'''
# Global is for interprocess comms
global pix_coeffs, fid_ix, fs1, fs2, slopes, squares, specs, funs
assert(len(Hg_set) == len(Xe_set))
# Step 1
gridded_set = []
for index, hg in enumerate(Hg_set):
gridded_set.append(None)
xe = Xe_set[index]
if hg.spec is None: continue
if xe.spec is None: continue
if hg.hgcoef is None: continue
assert(len(hg.spec) == len(xe.spec))
ix = np.arange(len(hg.specw))
ix_547 = np.argmin(np.abs(chebval(ix, hg.hgcoef) - 547.0))
if ix_547 > 180: continue
if ix_547 < 100: continue
scale = np.arange(len(hg.spec)) - ix_547
gridded_set[-1] = (scale, hg.spec, xe.spec)
fiducial = gridded_set[len(gridded_set)/2]
if fiducial is None or len(fiducial[0]) != 265:
fiducial = gridded_set[len(gridded_set)/2 + 1]
if fiducial is None or len(fiducial[0]) != 265:
fiducial = gridded_set[len(gridded_set)/2 + 2]
if fiducial is None or len(fiducial[0]) != 265:
fiducial = gridded_set[len(gridded_set)/2 + 3]
if fiducial is None or len(fiducial[0]) != 265:
fiducial = gridded_set[len(gridded_set)/2 + 4]
print len(gridded_set)
# Step 2
pl.figure(3)
pl.clf()
def interp_functions():
funs = []
for num, element in enumerate(gridded_set):
funs.append(None)
if element is None: continue
ix, s1, s2 = element
s1f = interp1d(ix, s1, fill_value=np.nan, bounds_error=False)
s2f = interp1d(ix, s2, fill_value=np.nan, bounds_error=False)
funs[-1] = (s1f, s2f)
return funs
funs = interp_functions()
pix_coeffs = []
fid_ix, fs1, fs2 = fiducial
# Note 0.001 over 250 pixels is about a quarter pixel
# max of 0.5e-3 over 150**2 is a handful of pixels.
slopes = np.arange(0.95,1/.95,.001)
squares = np.linspace(-1e-3, 1e-3, 15)
specs = gridded_set
p = Pool(8)
results = p.map(stretch_fit_helper, range(len(specs)))
p.close()
pix_coeffs = []
xcs = []
for res in results:
if res is None:
pix_coeffs.append(None)
xcs.append(None)
else:
pix_coeffs.append(res[0])
xcs.append(res[1])
return pix_coeffs, fiducial, xcs
# TODO -- REFIT Wavelengths given a good guess
linelist = {
"He": [587.5, 667.8, 706.5],
"Cd": [467.8, 479.9, 508.5],
"Hg": [578, 546.1, 435.8, 404.6, 365],
"Xe": [764, 828]
}
def snap_solution_into_place(PARS):
''' Return new Chebyshev coefficients for best fit wavelength solution '''
if PARS is None:
return (None, None)
ixs, coef, lamp_spec = PARS
fitfun = NPK.Fit.gaussian5
resfun = NPK.Fit.mpfit_residuals(fitfun)
def fitlinelist(cc):
lams = chebval(ixs, cc)
#pl.figure(1)
#pl.clf()
results = []
wresults = []
for lampname, lampspec in lamp_spec.iteritems():
#pl.step(ixs, lampspec, where='mid')
for line in linelist[lampname]:
lix = np.argmin(np.abs(line-lams))
if lix < 5 or lix > (len(ixs)-5): continue
cutout = slice(lix-4, lix+4)
xct = ixs[cutout]
sct = lampspec[cutout]
parguess = [
{'value': sct.max()-sct.min()}, # Scale
{'value': xct[sct.argmax()]}, # Centroid!!
{'value': 1.2}, # Sigma
{'value': sct.min()},# offset
{'value': 0}] # slope
pars = NPK.Fit.mpfit_do(resfun, xct, sct, parguess,
error=np.sqrt(np.abs(sct)))
if pars.status != 1: continue
results.append((line, pars.params[1], pars.perror[1]))
results = np.array(results)
if len(results) < 3:
return cc, np.nan
LS = results[:,0]
IXS = results[:,1]
WS = results[:,2]
#for IX in IXS: pl.axvline(IX,color='red')
nc = len(LS)-1
if nc > 5: nc = 4
newcoef = chebfit(IXS, LS, nc, w=WS)
res = np.abs(chebval(IXS, newcoef) - LS)/LS
if res[LS==365] < 200:
sl = np.where(LS==365)[0]
np.delete(IXS, sl)
np.delete(LS, sl)
newcoef = chebfit(IXS, LS, nc, w=WS)
res = np.abs(chebval(IXS, newcoef) - LS)/LS
return newcoef,res
newcoef,res = fitlinelist(coef)
newcoef,newres = fitlinelist(newcoef)
newcoef,newres = fitlinelist(newcoef)
#pl.figure(2)
#pl.clf()
#pl.figure(2)
#pl.plot(chebval(ixs, newcoef), lamp_spec['Hg'])
#for line in linelist["Hg"]: pl.axvline(line, color='red')
return newcoef, np.sqrt(np.mean(res*res))
def snap_solution_into_place_all(fine, Hgs, Xes, Cds=None, Hes=None):
PARS = []
for i in xrange(len(fine)):
PARS.append(None)
if fine[i].xrange is None: continue
if fine[i].mdn_coeff is None: continue
ixs = np.arange(*fine[i].xrange)
coef = fine[i].mdn_coeff
lamp_spec = {"Hg": fine[i].specw,
"Xe": Xes[i].specw}
if Cds is not None: lamp_spec["Cd"] = Cds[i].specw
if Hes is not None: lamp_spec["He"] = Hes[i].specw
PARS[-1] = (ixs, coef, lamp_spec)
p = Pool(8)
results = p.map(snap_solution_into_place, PARS)
p.close()
for i, res in enumerate(results):
fine[i].lamcoeff = res[0]
fine[i].lamrms = res[1]
return fine
def fit_he_lines(SS, guesses = {587.5: -18, 667.8: -48, 706.5: -60}, plot=False,
Ncutout=7):
return fit_known_lines(SS, guesses, plot, Ncutout)
def fit_cd_lines(SS, guesses = {467.8: 41, 479.9: 33, 508.5: 18}, plot=False,
Ncutout=5):
return fit_known_lines(SS, guesses, plot, Ncutout)
def fit_hg_lines(SS, guesses = {578: -14, 546.1: 0, 435.8: 60, 404.6: 81},
plot=False, Ncutout=7):
return fit_known_lines(SS, guesses, plot, Ncutout)
def fit_xe_lines(SS, guesses = {764: -77, 828: -93}, plot=False, Ncutout=5):
return fit_known_lines(SS, guesses, plot, Ncutout)
def fit_known_lines(SS, guesses, plot, Ncutout):
''' Fit lines based on guess pixel positions against a fiducial spectrum
This function is mapable
Args:
SS is a list of two elements containting:
spix(int[Ns]): Index values (pixel) of spec
spec(float[Ns]): Flux from corresponding index values
guesses: Dictionary containing {wavelength in nm: pixel guess position}
Returns:
[ (wavelength in nm, centroid position in pixel) ] with length
len(guesses.keys()).
Intent is for this list to be fit with polynomials to construct the
wavelength solution.
'''
if SS is None: return None
spix, spec = SS
res = []
fitfun = NPK.Fit.gaussian5
resfun = NPK.Fit.mpfit_residuals(fitfun)
for lam, guesspos in guesses.iteritems():
cutout = np.where(np.abs(spix - guesspos) < Ncutout)[0]
xct = spix[cutout]
sct = spec[cutout]
parguess = [
{'value': sct.max()-sct.min()}, # Scale
{'value': xct[sct.argmax()]}, # Centroid!!
{'value': 1.3}, # Sigma
{'value': sct.min()},# offset
{'value': 0}] # slope
pars = NPK.Fit.mpfit_do(resfun, xct, sct, parguess)
if pars.status != 1: continue
res.append([lam, pars.params[1]])
if plot:
pl.plot(xct, sct, 'o')
pl.plot(xct, fitfun(pars.params, xct))
if plot:
import pdb
pdb.set_trace()
pl.clf()
res = np.array(res)
return res
def fit_all_lines(fiducial, hg_spec, xe_spec, xxs, cd_spec=None, he_spec=None):
'''Fit mercury + xenon lines to a set of spectra that are put on a common fiducial grid.
Args:
fiducial(int[Nf]): Fiducial index values range from about -130 to + 130
hg_spec(Extraction[Ne]): Mercury spectra
xe_spec(Extraction[Ne]): Xenon spectra
xxs(Gridded[Ne]): Results from stretch_set() call
'''
assert(len(hg_spec) > 500)
assert(len(hg_spec) == len(xe_spec))
if cd_spec is not None:
assert(len(hg_spec) == len(cd_spec))
if he_spec is not None:
assert(len(hg_spec) == len(he_spec))
assert(len(xxs) == len(hg_spec))
Hgs = []
Xes = []
Cds = []
Hes = []
print "Stretching spectra"
for i in xrange(len(hg_spec)):
if hg_spec[i] is None or xxs[i] is None:
Hgs.append(None)
Xes.append(None)
Cds.append(None)
Hes.append(None)
continue
s1, s2 = get_stretched(fiducial, xxs[i], hg_spec[i],
spec2=xe_spec[i])
if cd_spec is not None:
s1, s3 = get_stretched(fiducial, xxs[i], hg_spec[i],
spec2=cd_spec[i])
Cds.append( (fiducial, s3) )
if he_spec is not None:
s1, s4 = get_stretched(fiducial, xxs[i], hg_spec[i],
spec2=he_spec[i])
Hes.append( (fiducial, s4) )
Hgs.append( (fiducial, s1) )
Xes.append( (fiducial, s2) )
p = Pool(8)
print "Fitting Hg lines"
hg_locs = p.map(fit_hg_lines, Hgs)
p.close()
p = Pool(8)
print "Fitting Xe lines"
xe_locs = p.map(fit_xe_lines, Xes)
p.close()
if cd_spec is not None:
p = Pool(8)
print "Fitting Cd lines"
cd_locs = p.map(fit_cd_lines, Cds)
p.close()
if he_spec is not None:
p = Pool(8)
print "Fitting He lines"
he_locs = p.map(fit_he_lines, Hes)
p.close()
print "Determining best fit to all lines"
fits = []
residuals = []
rss = []
pl.figure(3)
pl.clf()
for i in xrange(len(hg_spec)):
fits.append(None)
rss.append(None)
hg = hg_locs[i]
xe = xe_locs[i]
if cd_spec is not None: cd = cd_locs[i]
if he_spec is not None: he = he_locs[i]
if hg is None: continue
if xe is None: continue
if cd_spec is not None and cd is None: continue
if he_spec is not None and he is None: continue
try:
ll = np.concatenate([hg[:,0], xe[:,0]])
ix = np.concatenate([hg[:,1], xe[:,1]])
if cd_spec is not None:
ll = np.concatenate([ll, cd[:,0]])
ix = np.concatenate([ix, cd[:,1]])
if he_spec is not None:
ll = np.concatenate([ll, he[:,0]])
ix = np.concatenate([ix, he[:,1]])
except:
continue
weights = np.ones(len(ll))
weights[ll<400] = 0.03
weights[ll>860] = 0.1
if i == 50:
print ix
print ll
nc=3
if len(ll) < 5: nc=2
ff = chebfit(ix, ll, nc, w=weights)
fits[-1] = ff
res = {}
for jx, l in enumerate(ll): res[l] = chebval(ix[jx], ff) - l
residuals.append(res)
rss[-1] = np.sqrt(np.sum((chebval(ix, ff) - ll)**2))
if False:
pl.figure(3)
pl.step(chebval(fiducial, ff), Hgs[i][1]+Hes[i][1]+Xes[i][1])
pl.figure(3)
pl.step(chebval(fiducial, ff), Hgs[i][1]+Hes[i][1]+Xes[i][1])
pl.clf()
XS = []
YS = []
CS = []
for i in xrange(len(hg_spec)):
try:
x = np.mean(hg_spec[i].xrange)
y = np.mean(hg_spec[i].yrange)
c = rss[i]
except:
XS.append(None)
YS.append(None)
continue
XS.append(x)
YS.append(y)
CS.append(c)
return np.array(fits), residuals, np.array(rss), (XS, YS)
def coeffs_to_spec(fix, gridded, rgrd_coef, lam_coef):
''' Returns the spectrum given the unadultered spectrum and fits.
Args:
fix(array) -- Fiducial index positions
gridded(Extraction) -- Extracted spectrum to plot
rgrd_coef(list) -- Chebyshev polynomial coefficients that represent
the stretch of the spectrum to put onto the fiducial index
array (fix)
lam_coeff(list) -- Chebyshev polynomial coefficients that convert
fix to wavelength in nm
Returns:
Tuple containing the wavelength and spectrum
(wavelength, spectrum) this is in the units of the fit coefficients.
'''
gix = scale_on_547(gridded)
gsp = gridded.specw
newix = chebval(fix, rgrd_coef)
CC = chebfit(newix, fix, 3)
XX = chebval(gix, CC)
LL = chebval(XX, lam_coef)
return (LL, gsp)
def plot_grid(grid, Xes=None):
pl.figure(2) ; pl.clf()
pl.figure(1) ; pl.clf()
pl.ioff()
ixs = []
for index, g in enumerate(grid):
if index < 800: continue
if index > 900: continue
if g.specw is None: continue
if len(g.specw) == 0: continue
if g.hgcoef is None: continue
ix = np.arange(len(g.specw))
ix_547 = np.argmin(np.abs(chebval(ix, g.hgcoef) - 547))
if ix_547 > 180: continue
if ix_547 < 100: continue
ixs.append(ix_547)
ix = np.arange(len(g.specw)) - ix_547
add = 0
if Xes is not None:
try: add = Xes[index].specw
except: pass
if add is None: add = 0
pl.figure(2)
pl.plot(ix, g.specw+add, 'x')
#if index > 500: break
pl.show()
pl.figure(3)
pl.clf()
pl.ion()
pl.hist(ixs,50)
def rough_grid_helper(ix):
global extractions, lines
ex = extractions[ix]
if not ex.ok: return
xs = []
ys = []
for line in lines:
if line in ex.hg_lines:
X = ex.hg_lines[line]
if X + ex.xrange[0] > 2048:
ex.ok = False
continue
xs.append(ex.hg_lines[line])
ys.append(line)
xs = np.array(xs)
ys = np.array(ys)
if len(xs) == 0:
print ex.xrange, ex.yrange, ex.hg_lines
return
coef = chebfit(xs,ys,2)
vals = chebval(xs, coef)
ex.hgcoef = coef
err = (vals - ys)
ix = np.arange(len(ex.specw))
print "%4.4i: rough RMS: %f nm" % (ex.seg_id, np.mean(err))
def rough_grid(data, the_lines=[365.0, 404.6, 435.8, 546.1, 578],
outname='rough_wavelength.npy'):
'''Shift the extractions onto a coarse common pixel grid'''
global extractions, lines
extractions = data
lines = the_lines
map(rough_grid_helper, range(len(extractions)))
try:np.save(outname, extractions)
except: pass
return extractions
def RMS(vec):
return np.sqrt(np.sum((vec-np.mean(vec))**2))
def fit_spectra_Hg_Xe(Hgs, Xes, kdtree, kdseg_ids, plot=False, outname='fit_spectra'):
assert(len(Hgs) == len(Xes))
if plot:
pl.figure(1)
pl.clf()
pl.figure(2)
pl.clf()
pl.figure(1)
ixs = np.arange(0,260,.01)
hg_segids = [x.seg_id for x in Hgs]
for spec_ix in xrange(len(Hgs)):
hg = Hgs[spec_ix]
xe = Xes[spec_ix]
seg_id = hg.seg_id
coeff = hg.hgcoef
if coeff is None:
print spec_ix
continue
prev_rms = np.inf
rms = np.inf
for i in xrange(25):
offsets = measure_offsets(hg.specw+xe.specw, coeff, plot=False)
keys = np.array(offsets.keys())
vals = np.array(offsets.values())
#print np.sort(keys+vals)
lams = chebval(ixs,coeff)
pixs = []
meas = []
for lam, off in offsets.iteritems():
if (lam+off) > 1000: continue
if (lam+off) < 340: continue
ix = ixs[np.argmin(np.abs(lam-lams))]
pixs.append(ix)
meas.append(lam+off)
if np.any(np.isfinite(meas) == False): break
if np.any(pixs == 0): break
if len(pixs) < 2: break
if i < 2: coeff = chebfit(pixs, meas, 3)
else: coeff = chebfit(pixs, meas, 4)
diff = chebval(pixs, coeff) - meas
rms = RMS(diff)
#print "%4.0i %6.3f" % (spec_ix, rms)
if not np.isfinite(rms): pdb.set_trace()
if (rms < 0.35): break
if np.abs(rms - prev_rms) < 0.02: break
prev_rms = rms
if plot:
pl.figure(2)
lam = chebval(np.arange(len(hg.specw)), coeff)
spec = hg.specw+xe.specw
pl.plot(lam, spec)
pl.figure(1)
Hgs[spec_ix].lamcoeff = coeff
Hgs[spec_ix].lamrms = rms
print "-- %4.0i %6.3f" % (spec_ix, rms)
#if rms > 3: pdb.set_trace()
if plot:
pl.show()
np.save(outname, Hgs)
return Hgs
def measure_offsets(spec, coeff, plot=False):
'''Measure wavelength offsets of Hg and Xe extractions
First uses a crude peak finding code to identify the locations of the
Xe lines.
Then, the two Xe complexes are fit individually
Returns:
A dictionary of {line_wavelength_nm: offset_nm}.
'''
preffun = lambda x: ((x[1])**2 + (x[0]-120)**2)/1e4 + 1.
resfun830 = NPK.Fit.mpfit_residuals(xe_830nm, preffun=preffun)
# Preference function is designed to bias against adjusting the
preffun = lambda x: ( np.abs(x[0]-100)/100 + np.abs(x[1])/30 + np.abs(x[4]-100)/100)/3e4 + 1.0
resfun890 = NPK.Fit.mpfit_residuals(xe_890nm, preffun=preffun)
resfung = NPK.Fit.mpfit_residuals(NPK.Fit.gaussian5)
#pk_pxs = SG.find_peaks_cwt(spec, np.arange(8,25))
pk_pxs = SG.argrelmax(spec, order=10)[0]
pk_lam = chebval(pk_pxs, coeff)
ix = np.arange(len(spec))
ll = chebval(ix, coeff)
if plot:
pl.figure(3)
pl.clf()
pl.plot(ll, spec)
for p in pk_lam:
print "-", p
pl.axvline(p,color='blue')
offsets = {}
# resfung parameters:
for index, lam in enumerate([365.0, 404.6, 435.8, 546.1, 578]):
roi = (ll > (lam-9)) & (ll < (lam+9))
toll = ll[roi]
tofit = spec[roi]
if len(toll) == 0: continue
offset = np.min(tofit)
slope = 0
sigma = 2.5
scale = np.max(tofit)-offset
p = [scale, lam, sigma, offset, slope]
parinfo=[{'value': scale, 'limited':[1,0], 'limits':[0,0]},
{'value': lam, 'limited':[1,1], 'limits':[lam-15,lam+15]},
{'value': sigma, 'limited':[1,1], 'limits': [1.5,3.5]},
{'value': offset, 'limited':[1,0], 'limits': [0,0]},
{'value': slope}]
res = NPK.Fit.mpfit_do(resfung, toll, tofit, parinfo)
if res.status > 0:
offsets[lam] = lam-res.params[1]
# 830
guess_pos = np.argmin(np.abs(pk_lam - 830))
guess_lam = pk_lam[guess_pos]
guess_lam = pk_lam[1]
ok = ((guess_lam-35) < ll) & (ll < (guess_lam+45))
if np.any(ok):
sigma = 80
lamoffset = guess_lam-830
offset = np.min(spec[ok])
peak = np.max(spec[ok]) - offset
p = [sigma,lamoffset,offset,peak]
parinfo = [{'value': sigma, 'limited':[1,1], 'limits':[25,250]},
{'value': lamoffset, 'limited':[1,1],
'limits':[-50,50]},
{'value': offset,'limited':[1,0],'limits':[0,0]},
{'value': peak,'limited':[1,0],'limits':[0,0]}]
res = NPK.Fit.mpfit_do(resfun830, ll[ok], spec[ok], parinfo)
thell = ll[ok]
ps = res.params.copy()
ps[1] = 0
thespec = xe_830nm(ps, thell)
cl = np.sum(thespec*thell)/np.sum(thespec)
offsets[cl] = -res.params[1]
if plot:
pl.plot(ll[ok], xe_830nm(res.params, ll[ok]),'x-')
# Now 920
guess_pos = np.argmin(np.abs(pk_lam - 920))
guess_lam = pk_lam[guess_pos]
guess_lam = pk_lam[0]
ok = ((guess_lam-55) < ll) & (ll < (guess_lam+100))
if np.any(ok):
sigma = 100
lamoffset = guess_lam-890
if lamoffset > 5: lamoffset = 5
if lamoffset < -5: lamoffset = -5
offset = np.min(spec[ok])
peak = np.max(spec[ok]) - offset
p = [sigma,lamoffset,offset,peak, 500]
p930 = 500
parinfo = [ {'value': sigma, 'limited':[1,1], 'limits':[25,260]},
{'value': lamoffset, 'limited':[1,1], 'limits':[-50,50]},
{'value': offset,'limited':[1,0],'limits':[0,0]},
{'value': peak,'limited':[1,0],'limits':[0,0]},
{'value': p930,'limited':[1,0],'limits':[0,0]}]
res = NPK.Fit.mpfit_do(resfun890, ll[ok], spec[ok], parinfo)
thell = ll[ok]
ps = res.params.copy()
#ps[1] = 0
thespec = xe_890nm(ps, thell)
cl = np.sum(thespec*thell)/np.sum(thespec)
offsets[cl] = -res.params[1]
if plot:
print res.status
print res.niter, res.perror
print res.params
print res.debug
print res.errmsg
pl.plot(ll[ok], xe_890nm(res.params, ll[ok]),'x-')
if plot: pdb.set_trace()
return offsets
def read_spec_loc(spec_loc_fname):
'''Returns the structure for the location of each spectrum'''
return np.load(spec_loc_fname)
def xe_830nm(p, lam):
'''Xe comoplex near 830 nm.
See: http://www2.keck.hawaii.edu/inst/lris/arc_calibrations.html'''
sigma,lamoffset,offset,peak = p
sig=(2000*np.exp(-(lam-820.63-lamoffset)**2/sigma) +
1000*np.exp(-(lam-828.01-lamoffset)**2/sigma) +
100*np.exp(-(lam-834.68-lamoffset)**2/sigma) +
180*np.exp(-(lam-840.82-lamoffset)**2/sigma))
sig = sig/max(sig)*peak + offset
return sig
def save_fitted_ds9(fitted, outname='fine'):
xs = []
ys = []
ds9 = 'physical\n'
for ix,S in enumerate(fitted):
if S.lamcoeff is None: continue
if S.xrange is None: continue
xvals = np.arange(*S.xrange)
res = chebval(xvals, S.lamcoeff)
invcoeffs = chebfit(res, xvals, 4)
pxs= chebval([400., 500., 600., 656.3, 700., 800., 900.], invcoeffs)
startx = S.xrange[0]
for ix, px in enumerate(pxs):
X = px
Y = np.poly1d(S.poly)(X)
if ix == 3:
ds9 += 'point(%s,%s) # point=cross text={%s} color=blue\n' % \
(X,Y, S.seg_id)
elif ix == 0:
ds9 += 'point(%s,%s) # point=box color=red\n' % (X,Y)
elif ix == 6:
ds9 += 'point(%s,%s) # point=circle color=red\n' % (X,Y)
else:
ds9 += 'point(%s,%s) # point=cross color=red\n' % (X,Y)
f = open(outname+".reg", "w")
f.write(ds9)
f.close()
def xe_890nm(p, lam):
'''Xe comoplex near 890 nm.
See: http://www2.keck.hawaii.edu/inst/lris/arc_calibrations.html'''
sigma,lamoffset,offset,peak,p937 = p
sig=(5000*np.exp(-(lam-881.94-lamoffset)**2/sigma) +
1000*np.exp(-(lam-895.22-lamoffset)**2/sigma) +
1000*np.exp(-(lam-904.54-lamoffset)**2/sigma) +
1900*np.exp(-(lam-916.26-lamoffset)**2/sigma) +
p937*np.exp(-(lam-937.42-lamoffset)**2/sigma) )
#0000*np.exp(-(lam-951.33-lamoffset)**2/sigma) +
#000*np.exp(-(lam-979.69-lamoffset)**2/sigma))
sig = sig/max(sig)*peak + offset
return sig
def assign_fit_to_spectra(target, gridded, rss, fix, stretch, lamfit):
''' Put wavelength solution into target
Args:
target(list of Extraciton): Target list of extractions
gridded(list of Extractions[Ne]): Gridded spectra
rss (list of float[Ne]): RSS wavelength fit error
fix (list of float): Fiducial spectral index for "stretch"
stretch (list of float [Ne x Nfloat]): Float polynomials to stretch
spectra onto
lamfit (list of float [Ne x Ncoeff]): Wavelength fitting function
coefficients
Returns:
New grid with coefficients assigned to it
'''
for i in xrange(len(gridded)):
try: L,S = coeffs_to_spec(fix, gridded[i], stretch[i], lamfit[i])
except: continue
cc = chebfit(np.arange(*target[i].xrange), L, 5)
target[i].lamcoeff = cc
target[i].lamrms = rss[i]
return target
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=\
'''Wavelength.py performs:
1. Rough wavelength calibration based on Mercury lamp lines.
2. Fine wavelength calbiration based on Xenon and Mercury lamp lines.
3. Extraction of spectra with a fine wavelength calibration.
For each step, various report files are written, often ds9 region
files.
the _coarse.npy file contains a length-1 list with a dictionary. The
dictionary contains {wavelength: [(XY point)]} with all XY points
for a given Hg emission line wavelength.
the assoc_Hg.npy file contains a length-1 list with the associated
Hg solutions from the above *_coarse file.
--dome comes from FindSpectra.py
for rough set --dome [npy], --hgcat [txt], and --outname
for fine set --xefits [fits], --hefits [fits] --cdfits [fits] --hgassoc [npy], and --outname
''', formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('step', type=str, help='One of [rough|fine|extract]')
parser.add_argument('--infile', type=str, help='Infile name, purpose depends on step')
parser.add_argument('--dome', type=str, help='Dome segment definition npy file. Used in rough.')
parser.add_argument('--hgfits', type=str, help='Name of mercury fits file')
parser.add_argument('--xefits', type=str, help='Name of xenon fits file')
parser.add_argument('--cdfits', type=str, help='Name of cadmium fits file')
parser.add_argument('--hefits', type=str, help='Name of helium fits file')
parser.add_argument('--hgcat', type=str, help='Name of mercury sextractor catalog')
parser.add_argument('--coarse', type=str, help='Name of coarse Hg solution [npy]')
parser.add_argument('--hgassoc', type=str, help='Name of coarse Hg solution [npy]')
parser.add_argument('--fine', type=str, help='Name of fine solution [npy]')
parser.add_argument('--toextract', type=str, help='Name of fine solution [npy]')
parser.add_argument('--outname', type=str, help='Prefix name of output file')
args = parser.parse_args()
outname = args.outname
if args.step == 'rough':
hgfits = args.hgfits
catname = args.hgcat
catalog = read_catalog(catname)
spec_loc_fname = args.dome
spec_loc = read_spec_loc(spec_loc_fname)
hg_spec = find_hg_spectra(catalog, outname=outname)
assoc_hg_with_flats(spec_loc, hg_spec)
elif args.step == 'fine':
XeDat = pf.open(args.xefits)
HgDat = pf.open(args.hgfits)
if args.cdfits is not None: CdDat = pf.open(args.cdfits)
else: CdDat = None
if args.hefits is not None: HeDat = pf.open(args.hefits)
else: HeDat = None
assoc_hg_spec = np.load(args.hgassoc)[0]
Xe_E = extract(XeDat, assoc_hg_spec, filename="Xe_ext_"+args.outname)
Hg_E = extract(HgDat, assoc_hg_spec, filename="Hg_ext_"+args.outname)
Cd_E = None
if CdDat is not None:
Cd_E = extract(CdDat, assoc_hg_spec, filename="Cd_ext_"+args.outname)
He_E = None
if HeDat is not None:
He_E = extract(HeDat, assoc_hg_spec, filename="He_ext_"+args.outname)
gridded = rough_grid(Hg_E)
stretchset, fiducial, xcors = stretch_set(gridded, Xe_E)
fix, f1, f2 = fiducial
fits, residuals, rss, locs = fit_all_lines(fix,
gridded,
Xe_E,
stretchset,
cd_spec = Cd_E,
he_spec = He_E)
result = assign_fit_to_spectra(Hg_E, gridded, rss,
fix, stretchset, fits)
result = median_fine_grid(result)
print "Snapping solution into place"
snap_solution_into_place_all(result, Hg_E, Xe_E, Cds=Cd_E, Hes=He_E)
np.save(args.outname, result)
'''
elif args.step == 'fineold':
This step kept for historical purposes
XeDat = pf.open(args.xefits)
HgDat = pf.open(args.hgfits)
assoc_hg_spec = np.load(args.hgassoc)[0]
Xe_E = extract(XeDat, assoc_hg_spec, filename="Xe_ext_"+args.outname)
Hg_E = extract(HgDat, assoc_hg_spec, filename="Hg_ext_"+args.outname)
#Xe_E = np.load('Xe_ext_tester.npy')
#Hg_E = np.load('Hg_ext_tester.npy')
gridded = rough_grid(Hg_E, outname=outname)
import pdb
pdb.set_trace()
tree, segments = hg_to_kdtree(assoc_hg_spec)
fitted = fit_spectra_Hg_Xe(gridded, Xe_E, tree, segments,
outname=outname)
fitted = median_fine_grid(fitted)
np.save("%s.npy" % outname, fitted)
save_fitted_ds9(fitted, outname=outname)
'''
elif args.step == 'extract':
fitted = np.load(args.fine)
hdu = pf.open(args.toextract)
outname = args.outname
ww = wavelength_extract(hdu, fitted, filename=outname,
inname=args.toextract)
ww[1]['airmass'] = hdu.header['airmass']
np.save(outname, ww)
sys.exit()
#hg_spec = np.load('Hg.txt.npy')[0]
##hg_spec = find_hg_spectra(catalog, outname=outname)
##assoc_hg_spec = assoc_hg_with_flats(spec_loc, hg_spec)
#assoc_hg_spec = np.load('assoc_Hg.npy')[0]
#XeDat = pf.open("Xe.fits")
##S2 = extract(XeDat, assoc_hg_spec, filename="raw_xe_extractions.npy")
#S2 = np.load("raw_xe_extractions.npy")
##S = extract(dat, assoc_hg_spec)
#extractions = np.load('raw_hg_extractions.npy')
##gridded = rough_grid(extractions)
#gridded = np.load('gridded.npy')
##fitted = fit_spectra_Hg_Xe(gridded, S2, plot=False)
#fitted = np.load('fitted.npy')
#save_fitted_ds9(fitted)
| gpl-2.0 | -5,669,991,538,113,968,000 | 28.164319 | 230 | 0.546541 | false |
2013Commons/HUE-SHARK | desktop/core/src/desktop/views.py | 1 | 12982 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
import sys
import tempfile
import time
import traceback
import zipfile
from django.conf import settings
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.core.servers.basehttp import FileWrapper
from django.shortcuts import redirect
from django.utils.translation import ugettext as _
import django.views.debug
from desktop.lib import django_mako
from desktop.lib.conf import GLOBAL_CONFIG
from desktop.lib.django_util import login_notrequired, render_json, render, render_to_string
from desktop.lib.paths import get_desktop_root
from desktop.log.access import access_log_level, access_warn
from desktop.models import UserPreferences, Settings
from desktop import appmanager
import desktop.conf
import desktop.log.log_buffer
LOG = logging.getLogger(__name__)
@access_log_level(logging.WARN)
def home(request):
apps = appmanager.get_apps(request.user)
apps = dict([(app.name, app) for app in apps])
return render('home.mako', request, dict(apps=apps))
@access_log_level(logging.WARN)
def log_view(request):
"""
We have a log handler that retains the last X characters of log messages.
If it is attached to the root logger, this view will display that history,
otherwise it will report that it can't be found.
"""
if not request.user.is_superuser:
return HttpResponse(_("You must be a superuser."))
l = logging.getLogger()
for h in l.handlers:
if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
return render('logs.mako', request, dict(log=[l for l in h.buf], query=request.GET.get("q", "")))
return render('logs.mako', request, dict(log=[_("No logs found!")]))
@access_log_level(logging.WARN)
def download_log_view(request):
"""
Zip up the log buffer and then return as a file attachment.
"""
if not request.user.is_superuser:
return HttpResponse(_("You must be a superuser."))
l = logging.getLogger()
for h in l.handlers:
if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
try:
# We want to avoid doing a '\n'.join of the entire log in memory
# in case it is rather big. So we write it to a file line by line
# and pass that file to zipfile, which might follow a more efficient path.
tmp = tempfile.NamedTemporaryFile()
log_tmp = tempfile.NamedTemporaryFile("w+t")
for l in h.buf:
log_tmp.write(l + '\n')
# This is not just for show - w/out flush, we often get truncated logs
log_tmp.flush()
t = time.time()
zip = zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED)
zip.write(log_tmp.name, "hue-logs/hue-%s.log" % t)
zip.close()
length = tmp.tell()
# if we don't seek to start of file, no bytes will be written
tmp.seek(0)
wrapper = FileWrapper(tmp)
response = HttpResponse(wrapper,content_type="application/zip")
response['Content-Disposition'] = 'attachment; filename=hue-logs-%s.zip' % t
response['Content-Length'] = length
return response
except Exception, e:
logging.exception("Couldn't construct zip file to write logs to.")
return log_view(request)
return render_to_response("logs.mako", dict(log=[_("No logs found.")]))
@access_log_level(logging.DEBUG)
def prefs(request, key=None):
"""Get or set preferences."""
if key is None:
d = dict( (x.key, x.value) for x in UserPreferences.objects.filter(user=request.user))
return render_json(d)
else:
if "set" in request.REQUEST:
try:
x = UserPreferences.objects.get(user=request.user, key=key)
except UserPreferences.DoesNotExist:
x = UserPreferences(user=request.user, key=key)
x.value = request.REQUEST["set"]
x.save()
return render_json(True)
if "delete" in request.REQUEST:
try:
x = UserPreferences.objects.get(user=request.user, key=key)
x.delete()
return render_json(True)
except UserPreferences.DoesNotExist:
return render_json(False)
else:
try:
x = UserPreferences.objects.get(user=request.user, key=key)
return render_json(x.value)
except UserPreferences.DoesNotExist:
return render_json(None)
def bootstrap(request):
"""Concatenates bootstrap.js files from all installed Hue apps."""
# Has some None's for apps that don't have bootsraps.
all_bootstraps = [ (app, app.get_bootstrap_file()) for app in appmanager.DESKTOP_APPS if request.user.has_hue_permission(action="access", app=app.name) ]
# Iterator over the streams.
concatenated = [ "\n/* %s */\n%s" % (app.name, b.read()) for app, b in all_bootstraps if b is not None ]
# HttpResponse can take an iteratable as the first argument, which
# is what happens here.
return HttpResponse(concatenated, mimetype='text/javascript')
_status_bar_views = []
def register_status_bar_view(view):
global _status_bar_views
_status_bar_views.append(view)
@access_log_level(logging.DEBUG)
def status_bar(request):
"""
Concatenates multiple views together to build up a "status bar"/"status_bar".
These views are registered using register_status_bar_view above.
"""
resp = ""
for view in _status_bar_views:
try:
r = view(request)
if r.status_code == 200:
resp += r.content
else:
LOG.warning("Failed to execute status_bar view %s" % (view,))
except:
LOG.exception("Failed to execute status_bar view %s" % (view,))
return HttpResponse(resp)
def dump_config(request):
# Note that this requires login (as do most apps).
show_private = False
conf_dir = os.path.realpath(os.getenv("HUE_CONF_DIR", get_desktop_root("conf")))
if not request.user.is_superuser:
return HttpResponse(_("You must be a superuser."))
if request.GET.get("private"):
show_private = True
apps = sorted(appmanager.DESKTOP_MODULES, key=lambda app: app.menu_index)
apps_names = [app.name for app in apps]
top_level = sorted(GLOBAL_CONFIG.get().values(), key=lambda obj: apps_names.index(obj.config.key))
return render("dump_config.mako", request, dict(
show_private=show_private,
top_level=top_level,
conf_dir=conf_dir,
apps=apps))
if sys.version_info[0:2] <= (2,4):
def _threads():
import threadframe
return threadframe.dict().iteritems()
else:
def _threads():
return sys._current_frames().iteritems()
@access_log_level(logging.WARN)
def threads(request):
"""Dumps out server threads. Useful for debugging."""
if not request.user.is_superuser:
return HttpResponse(_("You must be a superuser."))
out = []
for thread_id, stack in _threads():
out.append("Thread id: %s" % thread_id)
for filename, lineno, name, line in traceback.extract_stack(stack):
out.append(" %-20s %s(%d)" % (name, filename, lineno))
out.append(" %-80s" % (line))
out.append("")
return HttpResponse("\n".join(out), content_type="text/plain")
def jasmine(request):
return render('jasmine.mako', request, None)
def index(request):
if request.user.is_superuser:
return redirect(reverse('about:index'))
else:
return home(request)
def serve_404_error(request, *args, **kwargs):
"""Registered handler for 404. We just return a simple error"""
access_warn(request, "404 not found")
return render("404.mako", request, dict(uri=request.build_absolute_uri()))
def serve_500_error(request, *args, **kwargs):
"""Registered handler for 500. We use the debug view to make debugging easier."""
exc_info = sys.exc_info()
if desktop.conf.HTTP_500_DEBUG_MODE.get():
return django.views.debug.technical_500_response(request, *exc_info)
try:
return render("500.mako", request, {'traceback': traceback.extract_tb(exc_info[2])})
except:
# Fallback to technical 500 response if ours fails
# Will end up here:
# - Middleware or authentication backends problems
# - Certain missing imports
# - Packaging and install issues
return django.views.debug.technical_500_response(request, *exc_info)
_LOG_LEVELS = {
"critical": logging.CRITICAL,
"error": logging.ERROR,
"warning": logging.WARNING,
"info": logging.INFO,
"debug": logging.DEBUG
}
_MAX_LOG_FRONTEND_EVENT_LENGTH = 1024
_LOG_FRONTEND_LOGGER = logging.getLogger("desktop.views.log_frontend_event")
@login_notrequired
def log_frontend_event(request):
"""
Logs arguments to server's log. Returns an
empty string.
Parameters (specified via either GET or POST) are
"logname", "level" (one of "debug", "info", "warning",
"error", or "critical"), and "message".
"""
def get(param, default=None):
return request.REQUEST.get(param, default)
level = _LOG_LEVELS.get(get("level"), logging.INFO)
msg = "Untrusted log event from user %s: %s" % (
request.user,
get("message", "")[:_MAX_LOG_FRONTEND_EVENT_LENGTH])
_LOG_FRONTEND_LOGGER.log(level, msg)
return HttpResponse("")
def who_am_i(request):
"""
Returns username and FS username, and optionally sleeps.
"""
try:
sleep = float(request.REQUEST.get("sleep") or 0.0)
except ValueError:
sleep = 0.0
time.sleep(sleep)
return HttpResponse(request.user.username + "\t" + request.fs.user + "\n")
def commonheader(title, section, user, padding="60px"):
"""
Returns the rendered common header
"""
apps = appmanager.get_apps(user)
apps_list = sorted(apps, key=lambda app: app.menu_index)
return django_mako.render_to_string("common_header.mako", dict(
apps=apps_list,
title=title,
section=section,
padding=padding,
user=user
))
def commonfooter(messages=None):
"""
Returns the rendered common footer
"""
if messages is None:
messages = {}
hue_settings = Settings.get_settings()
return render_to_string("common_footer.html", {
'messages': messages,
'version': settings.HUE_DESKTOP_VERSION,
'collect_usage': hue_settings.collect_usage
})
# If the app's conf.py has a config_validator() method, call it.
CONFIG_VALIDATOR = 'config_validator'
#
# Cache config errors because (1) they mostly don't go away until restart,
# and (2) they can be costly to compute. So don't stress the system just because
# the dock bar wants to refresh every n seconds.
#
# The actual viewing of all errors may choose to disregard the cache.
#
_CONFIG_ERROR_LIST = None
def _get_config_errors(request, cache=True):
"""Returns a list of (confvar, err_msg) tuples."""
global _CONFIG_ERROR_LIST
if not cache or _CONFIG_ERROR_LIST is None:
error_list = [ ]
for module in appmanager.DESKTOP_MODULES:
# Get the config_validator() function
try:
validator = getattr(module.conf, CONFIG_VALIDATOR)
except AttributeError:
continue
if not callable(validator):
LOG.warn("Auto config validation: %s.%s is not a function" %
(module.conf.__name__, CONFIG_VALIDATOR))
continue
try:
error_list.extend(validator(request.user))
except Exception, ex:
LOG.exception("Error in config validation by %s: %s" % (module.nice_name, ex))
_CONFIG_ERROR_LIST = error_list
return _CONFIG_ERROR_LIST
def check_config(request):
"""Check config and view for the list of errors"""
if not request.user.is_superuser:
return HttpResponse(_("You must be a superuser."))
conf_dir = os.path.realpath(os.getenv("HUE_CONF_DIR", get_desktop_root("conf")))
return render('check_config.mako', request, dict(
error_list=_get_config_errors(request, cache=False),
conf_dir=conf_dir))
def check_config_ajax(request):
"""Alert administrators about configuration problems."""
if not request.user.is_superuser:
return HttpResponse('')
error_list = _get_config_errors(request)
if not error_list:
# Return an empty response, rather than using the mako template, for performance.
return HttpResponse('')
return render('config_alert_dock.mako',
request,
dict(error_list=error_list),
force_template=True)
register_status_bar_view(check_config_ajax)
| apache-2.0 | -3,279,796,561,292,132,400 | 32.202046 | 155 | 0.685334 | false |
sbywater/django-asana | djasana/connect.py | 1 | 1910 | import logging
from requests.exceptions import ChunkedEncodingError
from asana import Client as AsanaClient
from asana.error import ServerError
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
logger = logging.getLogger(__name__)
class Client(AsanaClient, object):
"""An http client for making requests to an Asana API and receiving responses."""
def request(self, method, path, **options):
logger.debug('%s, %s', method, path)
try:
return super(Client, self).request(method, path, **options)
except (SystemExit, ServerError, ChunkedEncodingError):
logger.error('Error for %s, %s with options %s', method, path, options)
# Try once more
return super(Client, self).request(method, path, **options)
def client_connect():
if getattr(settings, 'ASANA_ACCESS_TOKEN', None):
client = Client.access_token(settings.ASANA_ACCESS_TOKEN)
elif getattr(settings, 'ASANA_CLIENT_ID', None) and \
getattr(settings, 'ASANA_CLIENT_SECRET', None) and \
getattr(settings, 'ASANA_OAUTH_REDIRECT_URI', None):
client = Client.oauth(
client_id=settings.ASANA_CLIENT_ID,
client_secret=settings.ASANA_CLIENT_SECRET,
redirect_uri=settings.ASANA_OAUTH_REDIRECT_URI
)
else:
raise ImproperlyConfigured(
'It is required to set the ASANA_ACCESS_TOKEN or the three OAuth2 settings ' +
'ASANA_CLIENT_ID, ASANA_CLIENT_SECRET, and ASANA_OAUTH_REDIRECT_URI.')
if getattr(settings, 'ASANA_WORKSPACE', None):
workspaces = client.workspaces.find_all()
for workspace in workspaces:
if settings.ASANA_WORKSPACE == workspace['name']:
client.options['workspace_id'] = workspace['gid']
client.options['Asana-Fast-Api'] = 'true'
return client
| mit | 819,242,340,096,198,900 | 38.791667 | 90 | 0.662304 | false |
webnull/RaspAP | raspapd/src/libraspapd/daemons/SecureShellServer.py | 1 | 1642 | from BaseDaemon import BaseDaemon
import time
import os
class SecureShellServer(BaseDaemon):
"""
Controls Privoxy daemon
"""
def start(self, interface, settings):
"""
Start processes
:param interface:
:param settings:
:return:
"""
# openssh-server
if 'openssh' in settings:
if settings['openssh']:
# copy /etc/ssh/sshd_raspap into /etc/ssh/sshd_config preserving permissions
if os.path.isfile('/etc/ssh/sshd_raspap'):
open('/etc/ssh/sshd_config', 'w').write(open('/etc/ssh/sshd_raspap').read())
self.callSystemService('sshd', 'restart')
else:
self.callSystemService('sshd', 'stop')
# shell in a box support
if 'shellinabox' in settings and settings['shellinabox']:
port = 8021
# allow custom port
if 'shellinabox_port' in settings:
port = int(settings['shellinabox_port'])
result, output = self.app.executeCommand('cd /tmp && screen -d -m shellinaboxd --port ' + str(port) + ' --no-beep -d', shell=True)
time.sleep(5)
if not self.find_process('shellinaboxd', withoutSudo=False):
self.app.logging.output('shellinaboxd process unexpectedly quit', interface)
return False
return True
def finish(self):
"""
Shutdown processes
:return:
"""
self.callSystemService('sshd', 'stop')
return self.find_and_kill_process('shellinaboxd', self.interface) | gpl-3.0 | 8,426,370,058,812,727,000 | 27.824561 | 142 | 0.560901 | false |
kenrick95/airmozilla | airmozilla/base/tests/test_mozillians.py | 1 | 10869 | import json
from django.conf import settings
from django.test import TestCase
from django.core.cache import cache
import mock
from nose.tools import ok_, eq_
from airmozilla.base import mozillians
from airmozilla.base.tests.testbase import Response
VOUCHED_FOR_USERS = """
{
"count": 1,
"next": null,
"results": [
{
"username": "peterbe",
"_url": "https://muzillians.fake/api/v2/users/99999/",
"is_vouched": true
}
],
"previous": null
}
"""
NO_USERS = """
{
"count": 0,
"next": null,
"results": [],
"previous": null
}
"""
VOUCHED_FOR = """
{
"photo": {
"300x300": "https://muzillians.fake/media/uplo...1caee0.jpg",
"150x150": "https://muzillians.fake/media/uplo...5636261.jpg",
"500x500": "https://muzillians.fake/media/uplo...6465a73.jpg",
"value": "https://muzillians.fake/media/uploa...71caee0.jpg",
"privacy": "Public"
},
"date_mozillian": {
"value": null,
"privacy": "Mozillians"
},
"full_name": {
"value": "Peter Bengtsson",
"privacy": "Public"
},
"title": {
"value": "",
"privacy": "Mozillians"
},
"external_accounts": [],
"alternate_emails": [],
"email": {
"value": "[email protected]",
"privacy": "Mozillians"
},
"username": "peterbe",
"is_public": true,
"url": "https://muzillians.fake/en-US/u/peterbe/",
"country": {
"code": "us",
"value": "United States",
"privacy": "Public"
},
"websites": [
{
"website": "http://www.peterbe.com/",
"privacy": "Public"
}
],
"_url": "https://muzillians.fake/api/v2/users/441/",
"story_link": {
"value": "",
"privacy": "Mozillians"
},
"ircname": {
"value": "peterbe",
"privacy": "Public"
},
"is_vouched": true
}
"""
NOT_VOUCHED_FOR = """
{
"photo": {
"300x300": "https://muzillians.fake/media/uplo...1caee0.jpg",
"150x150": "https://muzillians.fake/media/uplo...5636261.jpg",
"500x500": "https://muzillians.fake/media/uplo...6465a73.jpg",
"value": "https://muzillians.fake/media/uploa...71caee0.jpg",
"privacy": "Public"
},
"date_mozillian": {
"value": null,
"privacy": "Mozillians"
},
"full_name": {
"value": "Peter Bengtsson",
"privacy": "Private"
},
"title": {
"value": "",
"privacy": "Mozillians"
},
"alternate_emails": [],
"email": {
"value": "[email protected]",
"privacy": "Mozillians"
},
"username": "tmickel",
"bio": {
"html": "<p>Web developer at Mozilla</p>",
"value": "Web developer at Mozilla",
"privacy": "Public"
},
"is_public": true,
"url": "https://muzillians.fake/en-US/u/peterbe/",
"websites": [
{
"website": "http://www.peterbe.com/",
"privacy": "Public"
}
],
"_url": "https://muzillians.fake/api/v2/users/441/",
"story_link": {
"value": "",
"privacy": "Mozillians"
},
"ircname": {
"value": "peterbe",
"privacy": "Public"
},
"is_vouched": false
}
"""
VOUCHED_FOR_NO_USERNAME = """
{
"meta": {
"previous": null,
"total_count": 1,
"offset": 0,
"limit": 20,
"next": null
},
"objects": [
{
"website": "",
"bio": "",
"resource_uri": "/api/v1/users/2429/",
"last_updated": "2012-11-06T14:41:47",
"groups": [
"ugly tuna"
],
"city": "Casino",
"skills": [],
"country": "Albania",
"region": "Bush",
"id": "2429",
"languages": [],
"allows_mozilla_sites": true,
"photo": "http://www.gravatar.com/avatar/0409b497734934400822bb33...",
"is_vouched": true,
"email": "[email protected]",
"ircname": "",
"allows_community_sites": true
}
]
}
"""
NOT_VOUCHED_FOR_USERS = """
{
"count": 1,
"next": null,
"results": [
{
"username": "[email protected]",
"_url": "https://muzillians.fake/api/v2/users/00000/",
"is_vouched": false
}
],
"previous": null
}
"""
NO_VOUCHED_FOR = """
{
"meta": {
"previous": null,
"total_count": 0,
"offset": 0,
"limit": 20,
"next": null
},
"objects": []
}
"""
GROUPS1 = """
{
"count": 3,
"previous": null,
"results": [
{
"url": "https://muzillians.fake/en-US/group/9090909/",
"_url": "https://muzillians.fake/api/v2/groups/909090/",
"id": 12426,
"member_count": 3,
"name": "GROUP NUMBER 1"
},
{
"url": "https://muzillians.fake/en-US/group/2009-intern/",
"_url": "https://muzillians.fake/api/v2/groups/08080808/",
"id": 196,
"member_count": 7,
"name": "GROUP NUMBER 2"
}
],
"next": "https://muzillians.fake/api/v2/groups/?api-key=xxxkey&page=2"
}
"""
GROUPS2 = """
{
"count": 3,
"previous": "https://muzillians.fake/api/v2/groups/?api-key=xxxkey",
"results": [
{
"url": "https://muzillians.fake/en-US/group/2013summitassembly/",
"_url": "https://muzillians.fake/api/v2/groups/02020202/",
"id": 2002020,
"member_count": 53,
"name": "GROUP NUMBER 3"
}
],
"next": null
}
"""
assert json.loads(VOUCHED_FOR_USERS)
assert json.loads(VOUCHED_FOR)
assert json.loads(NOT_VOUCHED_FOR_USERS)
assert json.loads(NO_VOUCHED_FOR)
assert json.loads(GROUPS1)
assert json.loads(GROUPS2)
class TestMozillians(TestCase):
@mock.patch('requests.get')
def test_is_vouched(self, rget):
def mocked_get(url, **options):
if 'tmickel' in url:
return Response(NOT_VOUCHED_FOR_USERS)
if 'peterbe' in url:
return Response(VOUCHED_FOR_USERS)
if 'trouble' in url:
return Response('Failed', status_code=500)
raise NotImplementedError(url)
rget.side_effect = mocked_get
ok_(not mozillians.is_vouched('[email protected]'))
ok_(mozillians.is_vouched('[email protected]'))
self.assertRaises(
mozillians.BadStatusCodeError,
mozillians.is_vouched,
'[email protected]'
)
# also check that the API key is scrubbed
try:
mozillians.is_vouched('[email protected]')
raise
except mozillians.BadStatusCodeError as msg:
ok_(settings.MOZILLIANS_API_KEY not in str(msg))
@mock.patch('requests.get')
def test_is_not_vouched(self, rget):
def mocked_get(url, **options):
if 'tmickel' in url:
return Response(NOT_VOUCHED_FOR_USERS)
raise NotImplementedError(url)
rget.side_effect = mocked_get
ok_(not mozillians.is_vouched('[email protected]'))
@mock.patch('requests.get')
def test_fetch_user_name(self, rget):
def mocked_get(url, **options):
if '/v2/users/99999' in url:
return Response(VOUCHED_FOR)
if '/v2/users/00000' in url:
return Response(NOT_VOUCHED_FOR)
if 'peterbe' in url:
return Response(VOUCHED_FOR_USERS)
if 'tmickel' in url:
return Response(NOT_VOUCHED_FOR_USERS)
raise NotImplementedError(url)
rget.side_effect = mocked_get
result = mozillians.fetch_user_name('[email protected]')
eq_(result, 'Peter Bengtsson')
result = mozillians.fetch_user_name('[email protected]')
eq_(result, None)
@mock.patch('requests.get')
def test_fetch_user_name_failure(self, rget):
"""if the fetching of a single user barfs it shouldn't reveal
the API key"""
def mocked_get(url, **options):
if 'peterbe' in url:
return Response(VOUCHED_FOR_USERS)
return Response('Failed', status_code=500)
rget.side_effect = mocked_get
try:
mozillians.fetch_user('[email protected]')
raise AssertionError("shouldn't happen")
except mozillians.BadStatusCodeError as msg:
ok_(settings.MOZILLIANS_API_KEY not in str(msg))
ok_('xxxscrubbedxxx' in str(msg))
@mock.patch('requests.get')
def test_fetch_user_name_no_user_name(self, rget):
def mocked_get(url, **options):
if '/v2/users/99999' in url:
return Response(VOUCHED_FOR_NO_USERNAME)
if 'peterbe' in url and '/v2/users/' in url:
return Response(VOUCHED_FOR_USERS)
raise NotImplementedError(url)
rget.side_effect = mocked_get
result = mozillians.fetch_user_name('[email protected]')
eq_(result, None)
@mock.patch('requests.get')
def test_in_group(self, rget):
def mocked_get(url, **options):
if 'peterbe' in url:
if 'group=losers' in url:
return Response(NO_USERS)
if 'group=winners' in url:
return Response(VOUCHED_FOR_USERS)
raise NotImplementedError(url)
rget.side_effect = mocked_get
ok_(not mozillians.in_group('[email protected]', 'losers'))
ok_(mozillians.in_group('[email protected]', 'winners'))
@mock.patch('requests.get')
def test_get_all_groups(self, rget):
calls = []
def mocked_get(url, **options):
calls.append(url)
if '/v2/groups/' in url and 'page=2' in url:
return Response(GROUPS2)
if '/v2/groups/' in url:
return Response(GROUPS1)
raise NotImplementedError(url)
rget.side_effect = mocked_get
all = mozillians.get_all_groups()
eq_(len(all), 3)
eq_(all[0]['name'], 'GROUP NUMBER 1')
eq_(all[1]['name'], 'GROUP NUMBER 2')
eq_(all[2]['name'], 'GROUP NUMBER 3')
eq_(len(calls), 2)
@mock.patch('requests.get')
def test_get_all_groups_failure(self, rget):
def mocked_get(url, **options):
return Response('Failed', status_code=500)
rget.side_effect = mocked_get
try:
mozillians.get_all_groups()
raise AssertionError("shouldn't happen")
except mozillians.BadStatusCodeError as msg:
ok_(settings.MOZILLIANS_API_KEY not in str(msg))
ok_('xxxscrubbedxxx' in str(msg))
@mock.patch('requests.get')
def test_get_all_groups_cached(self, rget):
cache.clear()
calls = []
def mocked_get(url, **options):
calls.append(url)
if '/v2/groups/' in url and 'page=2' in url:
return Response(GROUPS2)
if '/v2/groups/' in url:
return Response(GROUPS1)
raise NotImplementedError(url)
rget.side_effect = mocked_get
all = mozillians.get_all_groups_cached()
eq_(len(all), 3)
eq_(len(calls), 2)
# a second time
all = mozillians.get_all_groups_cached()
eq_(len(all), 3)
eq_(len(calls), 2)
| bsd-3-clause | 999,102,141,390,220,300 | 24.940334 | 76 | 0.556905 | false |
caseywstark/colab | colab/apps/account/views.py | 1 | 17703 | from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.http import HttpResponseRedirect, HttpResponseForbidden, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.utils.http import base36_to_int
from django.utils.translation import ugettext, ugettext_lazy as _
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from emailconfirmation.models import EmailAddress, EmailConfirmation
association_model = models.get_model("django_openid", "Association")
if association_model is not None:
from django_openid.models import UserOpenidAssociation
from account.utils import get_default_redirect, user_display
from account.models import OtherServiceInfo
from account.forms import AddEmailForm, ChangeLanguageForm, ChangePasswordForm
from account.forms import ChangeTimezoneForm, LoginForm, ResetPasswordKeyForm
from account.forms import ResetPasswordForm, SetPasswordForm, SignupForm
from account.forms import TwitterForm
def group_and_bridge(kwargs):
"""
Given kwargs from the view (with view specific keys popped) pull out the
bridge and fetch group from database.
"""
bridge = kwargs.pop("bridge", None)
if bridge:
try:
group = bridge.get_group(**kwargs)
except ObjectDoesNotExist:
raise Http404
else:
group = None
return group, bridge
def group_context(group, bridge):
# @@@ use bridge
return {
"group": group,
}
def login(request, **kwargs):
form_class = kwargs.pop("form_class", LoginForm)
template_name = kwargs.pop("template_name", "account/login.html")
success_url = kwargs.pop("success_url", None)
associate_openid = kwargs.pop("associate_openid", False)
openid_success_url = kwargs.pop("openid_success_url", None)
url_required = kwargs.pop("url_required", False)
extra_context = kwargs.pop("extra_context", {})
redirect_field_name = kwargs.pop("redirect_field_name", "next")
group, bridge = group_and_bridge(kwargs)
if extra_context is None:
extra_context = {}
if success_url is None:
success_url = get_default_redirect(request, redirect_field_name)
if request.method == "POST" and not url_required:
form = form_class(request.POST, group=group)
if form.login(request):
if associate_openid and association_model is not None:
for openid in request.session.get("openids", []):
assoc, created = UserOpenidAssociation.objects.get_or_create(
user=form.user, openid=openid.openid
)
success_url = openid_success_url or success_url
messages.add_message(request, messages.SUCCESS,
ugettext(u"Successfully logged in as %(user)s.") % {
"user": user_display(form.user)
}
)
return HttpResponseRedirect(success_url)
else:
form = form_class(group=group)
ctx = group_context(group, bridge)
ctx.update({
"form": form,
"url_required": url_required,
"redirect_field_name": redirect_field_name,
"redirect_field_value": request.GET.get(redirect_field_name),
})
ctx.update(extra_context)
return render_to_response(template_name, RequestContext(request, ctx))
def signup(request, **kwargs):
form_class = kwargs.pop("form_class", SignupForm)
template_name = kwargs.pop("template_name", "account/signup.html")
redirect_field_name = kwargs.pop("redirect_field_name", "next")
success_url = kwargs.pop("success_url", None)
group, bridge = group_and_bridge(kwargs)
if success_url is None:
success_url = get_default_redirect(request, redirect_field_name)
if request.method == "POST":
form = form_class(request.POST, group=group)
if form.is_valid():
credentials = form.save(request=request)
if settings.ACCOUNT_EMAIL_VERIFICATION:
return render_to_response("account/verification_sent.html", {
"email": form.cleaned_data["email"],
}, context_instance=RequestContext(request))
else:
user = authenticate(**credentials)
auth_login(request, user)
messages.add_message(request, messages.SUCCESS,
ugettext("Successfully logged in as %(user)s.") % {
"user": user_display(user)
}
)
return HttpResponseRedirect(success_url)
else:
form = form_class(group=group)
ctx = group_context(group, bridge)
ctx.update({
"form": form,
"redirect_field_name": redirect_field_name,
"redirect_field_value": request.GET.get(redirect_field_name),
})
return render_to_response(template_name, RequestContext(request, ctx))
@login_required
def email(request, **kwargs):
form_class = kwargs.pop("form_class", AddEmailForm)
template_name = kwargs.pop("template_name", "account/email.html")
group, bridge = group_and_bridge(kwargs)
if request.method == "POST" and request.user.is_authenticated():
if request.POST["action"] == "add":
add_email_form = form_class(request.user, request.POST)
if add_email_form.is_valid():
add_email_form.save()
messages.add_message(request, messages.INFO,
ugettext(u"Confirmation email sent to %(email)s") % {
"email": add_email_form.cleaned_data["email"]
}
)
add_email_form = form_class() # @@@
else:
add_email_form = form_class()
if request.POST["action"] == "send":
email = request.POST["email"]
try:
email_address = EmailAddress.objects.get(
user=request.user,
email=email,
)
messages.add_message(request, messages.INFO,
ugettext("Confirmation email sent to %(email)s") % {
"email": email,
}
)
EmailConfirmation.objects.send_confirmation(email_address)
except EmailAddress.DoesNotExist:
pass
elif request.POST["action"] == "remove":
email = request.POST["email"]
try:
email_address = EmailAddress.objects.get(
user=request.user,
email=email
)
email_address.delete()
messages.add_message(request, messages.SUCCESS,
ugettext("Removed email address %(email)s") % {
"email": email,
}
)
except EmailAddress.DoesNotExist:
pass
elif request.POST["action"] == "primary":
email = request.POST["email"]
email_address = EmailAddress.objects.get(
user=request.user,
email=email,
)
email_address.set_as_primary()
else:
add_email_form = form_class()
ctx = group_context(group, bridge)
ctx.update({
"add_email_form": add_email_form,
})
return render_to_response(template_name, RequestContext(request, ctx))
@login_required
def password_change(request, **kwargs):
form_class = kwargs.pop("form_class", ChangePasswordForm)
template_name = kwargs.pop("template_name", "account/password_change.html")
group, bridge = group_and_bridge(kwargs)
if not request.user.password:
return HttpResponseRedirect(reverse("acct_passwd_set"))
if request.method == "POST":
password_change_form = form_class(request.user, request.POST)
if password_change_form.is_valid():
password_change_form.save()
messages.add_message(request, messages.SUCCESS,
ugettext(u"Password successfully changed.")
)
password_change_form = form_class(request.user)
else:
password_change_form = form_class(request.user)
ctx = group_context(group, bridge)
ctx.update({
"password_change_form": password_change_form,
})
return render_to_response(template_name, RequestContext(request, ctx))
@login_required
def password_set(request, **kwargs):
form_class = kwargs.pop("form_class", SetPasswordForm)
template_name = kwargs.pop("template_name", "account/password_set.html")
group, bridge = group_and_bridge(kwargs)
if request.user.password:
return HttpResponseRedirect(reverse("acct_passwd"))
if request.method == "POST":
password_set_form = form_class(request.user, request.POST)
if password_set_form.is_valid():
password_set_form.save()
messages.add_message(request, messages.SUCCESS,
ugettext(u"Password successfully set.")
)
return HttpResponseRedirect(reverse("acct_passwd"))
else:
password_set_form = form_class(request.user)
ctx = group_context(group, bridge)
ctx.update({
"password_set_form": password_set_form,
})
return render_to_response(template_name, RequestContext(request, ctx))
@login_required
def password_delete(request, **kwargs):
template_name = kwargs.pop("template_name", "account/password_delete.html")
# prevent this view when openids is not present or it is empty.
if not request.user.password or \
(not hasattr(request, "openids") or \
not getattr(request, "openids", None)):
return HttpResponseForbidden()
group, bridge = group_and_bridge(kwargs)
if request.method == "POST":
request.user.password = u""
request.user.save()
return HttpResponseRedirect(reverse("acct_passwd_delete_done"))
ctx = group_context(group, bridge)
return render_to_response(template_name, RequestContext(request, ctx))
def password_reset(request, **kwargs):
form_class = kwargs.pop("form_class", ResetPasswordForm)
template_name = kwargs.pop("template_name", "account/password_reset.html")
group, bridge = group_and_bridge(kwargs)
ctx = group_context(group, bridge)
if request.method == "POST":
password_reset_form = form_class(request.POST)
if password_reset_form.is_valid():
email = password_reset_form.save()
if group:
redirect_to = bridge.reverse("acct_passwd_reset_done", group)
else:
redirect_to = reverse("acct_passwd_reset_done")
return HttpResponseRedirect(redirect_to)
else:
password_reset_form = form_class()
ctx.update({
"password_reset_form": password_reset_form,
})
return render_to_response(template_name, RequestContext(request, ctx))
def password_reset_done(request, **kwargs):
template_name = kwargs.pop("template_name", "account/password_reset_done.html")
group, bridge = group_and_bridge(kwargs)
ctx = group_context(group, bridge)
return render_to_response(template_name, RequestContext(request, ctx))
def password_reset_from_key(request, uidb36, key, **kwargs):
form_class = kwargs.get("form_class", ResetPasswordKeyForm)
template_name = kwargs.get("template_name", "account/password_reset_from_key.html")
token_generator = kwargs.get("token_generator", default_token_generator)
group, bridge = group_and_bridge(kwargs)
ctx = group_context(group, bridge)
# pull out user
try:
uid_int = base36_to_int(uidb36)
except ValueError:
raise Http404
user = get_object_or_404(User, id=uid_int)
if token_generator.check_token(user, key):
if request.method == "POST":
password_reset_key_form = form_class(request.POST, user=user, temp_key=key)
if password_reset_key_form.is_valid():
password_reset_key_form.save()
messages.add_message(request, messages.SUCCESS,
ugettext(u"Password successfully changed.")
)
password_reset_key_form = None
else:
password_reset_key_form = form_class()
ctx.update({
"form": password_reset_key_form,
})
else:
ctx.update({
"token_fail": True,
})
return render_to_response(template_name, RequestContext(request, ctx))
@login_required
def timezone_change(request, **kwargs):
form_class = kwargs.pop("form_class", ChangeTimezoneForm)
template_name = kwargs.pop("template_name", "account/timezone_change.html")
group, bridge = group_and_bridge(kwargs)
if request.method == "POST":
form = form_class(request.user, request.POST)
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS,
ugettext(u"Timezone successfully updated.")
)
else:
form = form_class(request.user)
ctx = group_context(group, bridge)
ctx.update({
"form": form,
})
return render_to_response(template_name, RequestContext(request, ctx))
@login_required
def language_change(request, **kwargs):
form_class = kwargs.pop("form_class", ChangeLanguageForm)
template_name = kwargs.pop("template_name", "account/language_change.html")
group, bridge = group_and_bridge(kwargs)
if request.method == "POST":
form = form_class(request.user, request.POST)
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS,
ugettext(u"Language successfully updated.")
)
next = request.META.get("HTTP_REFERER", None)
return HttpResponseRedirect(next)
else:
form = form_class(request.user)
ctx = group_context(group, bridge)
ctx.update({
"form": form,
})
return render_to_response(template_name, RequestContext(request, ctx))
@login_required
def other_services(request, **kwargs):
from microblogging.utils import twitter_verify_credentials
template_name = kwargs.pop("template_name", "account/other_services.html")
group, bridge = group_and_bridge(kwargs)
twitter_form = TwitterForm(request.user)
twitter_authorized = False
if request.method == "POST":
twitter_form = TwitterForm(request.user, request.POST)
if request.POST["actionType"] == "saveTwitter":
if twitter_form.is_valid():
from microblogging.utils import twitter_account_raw
twitter_account = twitter_account_raw(
request.POST["username"], request.POST["password"])
twitter_authorized = twitter_verify_credentials(
twitter_account)
if not twitter_authorized:
messages.add_message(request, messages.ERROR,
ugettext("Twitter authentication failed")
)
else:
twitter_form.save()
messages.add_message(request, messages.SUCCESS,
ugettext(u"Successfully authenticated.")
)
else:
from microblogging.utils import twitter_account_for_user
twitter_account = twitter_account_for_user(request.user)
twitter_authorized = twitter_verify_credentials(twitter_account)
twitter_form = TwitterForm(request.user)
ctx = group_context(group, bridge)
ctx.update({
"twitter_form": twitter_form,
"twitter_authorized": twitter_authorized,
})
return render_to_response(template_name, RequestContext(request, ctx))
@login_required
def other_services_remove(request):
group, bridge = group_and_bridge(kwargs)
# @@@ this is a bit coupled
OtherServiceInfo.objects.filter(user=request.user).filter(
Q(key="twitter_user") | Q(key="twitter_password")
).delete()
messages.add_message(request, messages.SUCCESS,
ugettext("Removed twitter account information successfully.")
)
return HttpResponseRedirect(reverse("acct_other_services"))
| mit | 6,328,315,120,799,732,000 | 33.981707 | 87 | 0.589674 | false |
luispedro/jug | jug/subcommands/execute.py | 1 | 6180 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2020, Luis Pedro Coelho <[email protected]>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# 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.
from collections import defaultdict
import logging
import sys
from .. import task
from ..hooks import jug_hook, register_hook, register_hook_once
from ..io import print_task_summary_table
from ..jug import init
from . import SubCommand, maybe_print_citation_info
__all__ = [
'execute'
]
def _sigterm(_, __):
sys.exit(1)
def _log_loadable(t):
logging.info('Loadable {0}...'.format(t.name))
class TaskStats:
def __init__(self):
self.loaded = defaultdict(int)
self.executed = defaultdict(int)
register_hook('execute.task-loadable', self.loadable)
register_hook('execute.task-executed1', self.executed1)
def loadable(self, t):
self.loaded[t.name] += 1
def executed1(self, t):
self.executed[t.name] += 1
class ExecuteCommand(SubCommand):
'''Execute tasks
execute(options)
Implement 'execute' command
'''
name = "execute"
def run(self, options, *args, **kwargs):
from signal import signal, SIGTERM
from ..hooks.exit_checks import exit_env_vars, exit_if_file_exists
from ..jug import execution_loop
signal(SIGTERM, _sigterm)
if not options.execute_no_check_environment:
exit_env_vars()
exit_if_file_exists('__jug_please_stop_running.txt')
tasks = task.alltasks
tstats = TaskStats()
store = None
register_hook_once('execute.task-loadable', '_log_loadable', _log_loadable)
nr_wait_cycles = int(options.execute_nr_wait_cycles)
noprogress = 0
failures = False
while noprogress < nr_wait_cycles:
del tasks[:]
on_error = ('propagate' if options.pdb else 'exit')
store, jugspace = init(options.jugfile, options.jugdir, on_error=on_error, store=store)
if options.debug:
for t in tasks:
# Trigger hash computation:
t.hash()
previous = sum(tstats.executed.values())
failures = execution_loop(tasks, options) or failures
after = sum(tstats.executed.values())
done = not jugspace.get('__jug__hasbarrier__', False)
if done:
break
if after == previous:
from time import sleep
noprogress += 1
sleep(int(options.execute_wait_cycle_time))
else:
noprogress = 0
else:
logging.info('No tasks can be run!')
jug_hook('execute.finished_pre_status')
maybe_print_citation_info(options)
print_task_summary_table(options, [("Executed", tstats.executed), ("Loaded", tstats.loaded)])
jug_hook('execute.finished_post_status')
if failures:
sys.exit(1)
def parse(self, parser):
defaults = self.parse_defaults()
parser.add_argument('--wait-cycle-time', action='store', dest='execute_wait_cycle_time',
metavar='WAIT_CYCLE_TIME', type=int,
help=("How long to wait in each cycle (in seconds) "
"(Default: {execute_wait_cycle_time})".format(**defaults)))
parser.add_argument('--nr-wait-cycles', action='store',
dest='execute_nr_wait_cycles',
metavar='NR_WAIT_CYCLES', type=int,
help=("How many wait cycles to do "
"(Default: {execute_nr_wait_cycles})".format(**defaults)))
parser.add_argument('--target', action='store', dest='execute_target',
metavar='TARGET',
help="Restrict tasks to execute based on their name")
parser.add_argument('--keep-going',
action='store_const', const=True,
dest='execute_keep_going',
help='Continue after errors')
parser.add_argument('--keep-failed',
action='store_const', const=True,
dest='execute_keep_failed',
help='Keep failed tasks locked')
parser.add_argument('--no-check-environment',
action='store_const', const=True,
dest='execute_no_check_environment',
help='Do not check environment variables JUG_* and file __jug_please_stop_running.txt')
def parse_defaults(self):
wait_cycle_time = 12
default_values = {
"execute_keep_going": False,
"execute_keep_failed": False,
"execute_target": None,
"execute_wait_cycle_time": wait_cycle_time,
"execute_nr_wait_cycles": (30 * 60) // wait_cycle_time,
"execute_no_check_environment": False,
}
return default_values
execute = ExecuteCommand()
| mit | 8,235,745,497,830,285,000 | 36.682927 | 115 | 0.590777 | false |
karlssonper/gpuip | python/gpuip.py | 1 | 6372 | #!/usr/bin/env python
import utils
import sys
import signal
import os
try:
import argparse
parsermodule = argparse.ArgumentParser
except:
import optparse
parsermodule = optparse.OptionParser
parsermodule.add_argument = parsermodule.add_option
def getCommandLineArguments():
# Command line arguments
desc = "Framework for Image Processing on the GPU"
parser = parsermodule("gpuip", description=desc)
parser.add_argument("-f", "--file",
help="Image Processing file *.ip")
parser.add_argument("-p", "--param",
action="append",
nargs = 3,
metavar = ("kernel", "param", "value"),
help="Change value of a parameter.")
parser.add_argument("-i", "--inbuffer",
action="append",
nargs = 2,
metavar = ("buffer", "path"),
help = "Set input image to a buffer")
parser.add_argument("-o", "--outbuffer",
action="append",
nargs = 2,
metavar = ("buffer", "path"),
help = "Set output image to a buffer")
parser.add_argument("-v","--verbose",
action="store_true",
help="Outputs information")
parser.add_argument("--timestamp",
action="store_true",
help="Add timestamp in log output")
parser.add_argument("--nogui",
action="store_true",
help="Command line version")
if parsermodule.__name__ == "ArgumentParser":
return parser.parse_args()
else:
return parser.parse_args()[0]
def terminate(msg):
print msg
sys.exit(1)
def getSettings(args):
import settings
if not args.file or not os.path.isfile(args.file):
return None
ipsettings = settings.Settings()
ipsettings.read(args.file)
# Change parameter values
if args.param:
for p in args.param:
kernelName, paramName, value = p
kernel = ipsettings.getKernel(kernelName)
if not kernel:
terminate("gpuip error: No kernel %s found." % kernelName)
param = kernel.getParam(paramName)
if param:
param.setValue(utils.safeEval(value))
else:
terminate("gpuip error: No param %s found in kernel %s." \
% (paramName, kernelName))
# Change input buffers
if args.inbuffer:
for inb in args.inbuffer:
bufferName, path = inb[0], inb[1]
buffer = ipsettings.getBuffer(bufferName)
if buffer:
buffer.input = path
if not os.path.isfile(buffer.input):
raise IOError("No such file: '%s'" % buffer.input)
else:
terminate("gpuip error: No buffer %s found." % buffer)
# Change output buffers
if args.outbuffer:
for outb in args.outbuffer:
bufferName, path = outb[0], outb[1]
buffer = ipsettings.getBuffer(bufferName)
if buffer:
buffer.output = path
os.makedirs(os.path.dirname(os.path.realpath(path)))
else:
terminate("gpuip error: No buffer %s found." % bufferName)
return ipsettings
def runGUI(ippath, ipsettings):
# Run GUI version
from PySide import QtGui
import mainwindow
# Makes it possible to close program with ctrl+c in a terminal
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QtGui.QApplication(sys.argv)
app.setStyle("plastique")
mainwindow = mainwindow.MainWindow(path = ippath, settings = ipsettings)
mainwindow.show()
sys.exit(app.exec_())
def runCommandLine(ipsettings, verbose):
# Can't run non-gui version if there's no *.ip file
if not ipsettings:
err = "Must specify an existing *.ip file in the command-line version\n"
err += "example: \n"
err += " gpuip --nogui smooth.ip"""
terminate(err)
def check_error(err):
if err:
terminate(err)
def log(text, stopwatch = None, time = True):
time = time and args.timestamp
if verbose:
stopwatchStr = str(stopwatch) if stopwatch else ""
timeStr = utils.getTimeStr() if time else ""
print timeStr + text + " " + stopwatchStr
overall_clock = utils.StopWatch()
### 0. Create gpuip items from settings
ip, buffers, kernels = ipsettings.create()
log("Created elements from settings.", overall_clock)
### 1. Build
c = utils.StopWatch()
check_error(ip.Build())
log("Building kernels [%s]." % [k.name for k in kernels], c)
### 2. Import data from images
c = utils.StopWatch()
for b in ipsettings.buffers:
if b.input:
log("Importing data from %s to %s" %(b.input, b.name))
check_error(buffers[b.name].Read(b.input, utils.getNumCores()))
log("Importing data done.", c)
### 3. Allocate and transfer data to GPU
c = utils.StopWatch()
width, height = utils.allocateBufferData(buffers)
ip.SetDimensions(width, height)
check_error(ip.Allocate())
log("Allocating done.", c)
c = utils.StopWatch()
for b in ipsettings.buffers:
if b.input:
check_error(ip.WriteBufferToGPU(buffers[b.name]))
log("Transfering data to GPU done.", c)
### 4. Process
c = utils.StopWatch()
check_error(ip.Run())
log("Processing done.", c)
### 5. Export buffers to images
c = utils.StopWatch()
for b in ipsettings.buffers:
if b.output:
log("Exporting data from %s to %s" %(b.name, b.output))
check_error(ip.ReadBufferFromGPU(buffers[b.name]))
check_error(buffers[b.name].Write(b.output,utils.getNumCores()))
log("Exporting data done.", c)
log("\nAll steps done. Total runtime:", overall_clock, time = False)
if __name__ == "__main__":
args = getCommandLineArguments()
ipsettings = getSettings(args)
if args.nogui:
runCommandLine(ipsettings, args.verbose)
else:
runGUI(args.file if ipsettings else None, ipsettings)
| mit | 2,553,237,519,268,901,400 | 32.893617 | 80 | 0.569052 | false |
cmput402w2016/CMPUT402W16T2 | src/models/frame.py | 1 | 6534 | import math
import cv2
import imutils
import numpy as np
import settings
MIN_AREA = 500
class Frame():
"""
Takes a given image with a background subtractor and provides
all the functions required to count the vehicles in the frame
for the CLI or drawCountVehicles can be called for the GUI
that returns a marked up image with cars highlighted and a count
displayed.
"""
def __init__(self, img, background_subtractor, blob_detector):
#blob detector is passed in so it is not recreated for each frame
# still unsure if reducing resolution aids in image identification
image = imutils.resize(img, width=500)
self.image = img
self.fgbs = background_subtractor
self.detector = blob_detector
self.subtracted = self._subtractImage()
def _subtractImage(self):
"""
Increases contrast with histogram equalization and then applies
the background subtractor using a heavy blurring filter to merge vehicles
into a single detectable blob. Image thesholding is then applied using
Otsu to autocalculate the binary image
"""
sub = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
sub = cv2.equalizeHist(sub)
sub = self.fgbs.apply(sub)
sub = cv2.blur(sub,(20,20)) # blur the frame. this gives better result
_, sub = cv2.threshold(sub, 150, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
thresh, sub = cv2.threshold(sub, 150, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
return sub
def analyzeFrame(self, old_keypoints, world):
"""
The primary class function. Given the parsed world coordinates from the command line,
the old_keypoints that the previous frame passed to run_Interval, and the new image,
the function first detects new keypoints. Then for each point it determines if there
is another pixel within the proximity that it belongs to the same vehicle. If it
can detect such a point, it calculates the trajectory, and increments the world_direction
count accordingly. Keypoints that cannot be trajectoried are evenly distributed among
the average counts so that the overall counts can still be meaningfully divided by the
number of frames.
"""
averages_dict = {}
for k in world.keys():
averages_dict[k] = 0
def sortInWorld(angle, world):
"""
given an angle, decomposes the world coordinates to increment the proper value of the dictionary
"""
for k in world.keys():
anglerange = k.replace('(',"").replace(")","").\
replace("'","").split(',')
min = int(anglerange[0])
max = int(anglerange[1])
if (min <= angle) and (angle < max):
averages_dict[k] += 1
count = 0
keypoints = self.detector.detect(self.subtracted)
lines = []
if (old_keypoints is not None) and len(old_keypoints):
#Not all keypoints will have a direction, in this case, they
# are randomly distributed to all gropus
freeze_keys = world.keys()
key_cycler = 0
for kp in keypoints:
parray = np.array([k.pt for k in old_keypoints])
p0 = np.array(kp.pt)
old_point = self.find_nearest(parray, kp.pt)
#if the keypoint can be associated with an already detected
#vehicle, detect its motion and sort it into the averages count
dist = np.linalg.norm(p0-old_point)
#do not track stationary vehicles
if (dist > settings.MIN_DIST) and (dist < settings.MAX_DIST):
angle = self.angle_between(old_point,p0)
sortInWorld(angle, world)
lines.append([(int(old_point[0]),int(old_point[1])),
(int(p0[0]), int(p0[1])), round(angle, 0)])
else:
key = freeze_keys[key_cycler]
averages_dict[key] += 1
key_cycler = (key_cycler + 1) % len(freeze_keys)
if settings.DEBUG:
im_with_keypoints = cv2.drawKeypoints(self.subtracted, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
#=======================================================================
# cv2.putText(im_with_keypoints ,"Count: %d" % len(),(10,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,0,255),2)
# cv2.imshow('keypoints', im_with_keypoints)
#=======================================================================
for l in lines:
cv2.line(im_with_keypoints, l[0],l[1], (0,255,0), 3 )
#write the angle next to the end point of the line
cv2.putText(im_with_keypoints, str(l[2]), l[1], cv2.FONT_HERSHEY_SIMPLEX, 0.5, (100,100,100),2)
cv2.imshow("keypoints", im_with_keypoints)
cv2.waitKey(0)
return (keypoints, averages_dict)
#===========================================================================
# def _getContours(self):
# # Applies contouring to subtracted image to identify areas of interest
# thresh = cv2.blur(self.subtracted,(20,20)) # blur the frame. this gives better result
# _, thresh = cv2.threshold(self.subtracted, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# (contours, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
# cv2.CHAIN_APPROX_SIMPLE)
# return contours
#===========================================================================
def find_nearest(self, points, coord):
"""Element in nd array `points` closest to the scalar value coord.
Assumes that points is a non-empty list
"""
p = points[np.sum(np.square(np.abs(points-coord)),1).argmin()]
return p
def angle_between(self, p1, p2):
"""
calculates the trajectory of 2 points from p1 to p2
recalculates with 0 as it is on unit circle and in deg
"""
deltax = p2[1] - p1[1]
deltay = p2[0] - p1[0]
trajectory = math.atan2(deltay, deltax) * 180/np.pi
trajectory = (trajectory - 90) % 360
return trajectory | apache-2.0 | 8,302,586,132,701,142,000 | 44.381944 | 154 | 0.556321 | false |
memsharded/conan | conans/client/generators/cmake_find_package_multi.py | 1 | 4329 | from conans.client.generators.cmake import DepsCppCmake
from conans.client.generators.cmake_find_package import find_dependency_lines
from conans.client.generators.cmake_find_package_common import target_template
from conans.model import Generator
class CMakeFindPackageMultiGenerator(Generator):
config_xxx_template = """
# Requires CMake > 3.0
if(${{CMAKE_VERSION}} VERSION_LESS "3.0")
message(FATAL_ERROR "The 'cmake_find_package_multi' only works with CMake > 3.0" )
endif()
include(${{CMAKE_CURRENT_LIST_DIR}}/{name}Targets.cmake)
{target_props_block}
{find_dependencies_block}
"""
targets_file = """
if(NOT TARGET {name}::{name})
add_library({name}::{name} INTERFACE IMPORTED)
endif()
# Load the debug and release library finders
get_filename_component(_DIR "${{CMAKE_CURRENT_LIST_FILE}}" PATH)
file(GLOB CONFIG_FILES "${{_DIR}}/{name}Target-*.cmake")
foreach(f ${{CONFIG_FILES}})
include(${{f}})
endforeach()
"""
target_properties = """
# Assign target properties
set_property(TARGET {name}::{name}
PROPERTY INTERFACE_LINK_LIBRARIES
$<$<CONFIG:Release>:${{{name}_LIBRARIES_TARGETS_RELEASE}} ${{{name}_LINKER_FLAGS_RELEASE_LIST}}>
$<$<CONFIG:RelWithDebInfo>:${{{name}_LIBRARIES_TARGETS_RELWITHDEBINFO}} ${{{name}_LINKER_FLAGS_RELWITHDEBINFO_LIST}}>
$<$<CONFIG:MinSizeRel>:${{{name}_LIBRARIES_TARGETS_MINSIZEREL}} ${{{name}_LINKER_FLAGS_MINSIZEREL_LIST}}>
$<$<CONFIG:Debug>:${{{name}_LIBRARIES_TARGETS_DEBUG}} ${{{name}_LINKER_FLAGS_DEBUG_LIST}}>)
set_property(TARGET {name}::{name}
PROPERTY INTERFACE_INCLUDE_DIRECTORIES
$<$<CONFIG:Release>:${{{name}_INCLUDE_DIRS_RELEASE}}>
$<$<CONFIG:RelWithDebInfo>:${{{name}_INCLUDE_DIRS_RELWITHDEBINFO}}>
$<$<CONFIG:MinSizeRel>:${{{name}_INCLUDE_DIRS_MINSIZEREL}}>
$<$<CONFIG:Debug>:${{{name}_INCLUDE_DIRS_DEBUG}}>)
set_property(TARGET {name}::{name}
PROPERTY INTERFACE_COMPILE_DEFINITIONS
$<$<CONFIG:Release>:${{{name}_COMPILE_DEFINITIONS_RELEASE}}>
$<$<CONFIG:RelWithDebInfo>:${{{name}_COMPILE_DEFINITIONS_RELWITHDEBINFO}}>
$<$<CONFIG:MinSizeRel>:${{{name}_COMPILE_DEFINITIONS_MINSIZEREL}}>
$<$<CONFIG:Debug>:${{{name}_COMPILE_DEFINITIONS_DEBUG}}>)
set_property(TARGET {name}::{name}
PROPERTY INTERFACE_COMPILE_OPTIONS
$<$<CONFIG:Release>:${{{name}_COMPILE_OPTIONS_RELEASE_LIST}}>
$<$<CONFIG:RelWithDebInfo>:${{{name}_COMPILE_OPTIONS_RELWITHDEBINFO_LIST}}>
$<$<CONFIG:MinSizeRel>:${{{name}_COMPILE_OPTIONS_MINSIZEREL_LIST}}>
$<$<CONFIG:Debug>:${{{name}_COMPILE_OPTIONS_DEBUG_LIST}}>)
"""
@property
def filename(self):
pass
@property
def content(self):
ret = {}
build_type = self.conanfile.settings.get_safe("build_type")
build_type_suffix = "_{}".format(build_type.upper()) if build_type else ""
for depname, cpp_info in self.deps_build_info.dependencies:
deps = DepsCppCmake(cpp_info)
ret["{}Config.cmake".format(depname)] = self._find_for_dep(depname, cpp_info)
find_lib = target_template.format(name=depname, deps=deps,
build_type_suffix=build_type_suffix)
ret["{}Targets.cmake".format(depname)] = self.targets_file.format(name=depname)
ret["{}Target-{}.cmake".format(depname, build_type.lower())] = find_lib
return ret
def _build_type_suffix(self, build_type):
return
def _find_for_dep(self, name, cpp_info):
lines = []
if cpp_info.public_deps:
# Here we are generating only Config files, so do not search for FindXXX modules
lines = find_dependency_lines(name, cpp_info, find_modules=False)
targets_props = self.target_properties.format(name=name)
tmp = self.config_xxx_template.format(name=name,
version=cpp_info.version,
find_dependencies_block="\n".join(lines),
target_props_block=targets_props)
return tmp
| mit | -8,448,485,614,641,776,000 | 42.727273 | 134 | 0.603835 | false |
smarttang/dnsfind | core/config.py | 1 | 1176 | #coding:utf-8
import os
version = 'V1.1'
author = 'Smarttang'
def init_option(keys):
vardict = {
'timeout': check_time(keys.timeout),
'target': check_target(keys.target),
'dictname': check_dictname(keys.dictname),
'threads_count': check_threads(keys.threads_count),
'finger':keys.finger,
'keywords':check_keywords(keys.keywords)
}
return vardict
# 检查关键字
def check_keywords(val):
if val:
return val.split(',')
else:
return None
# 最高设置为超时10
def check_time(val):
if val > 0 and val < 10:
return val
else:
return 5
# 默认不能有空值
def check_target(val):
domain = val.split('.')
if len(domain) > 1 and '' not in domain:
return '.'.join(domain)
else:
return 'baidu.com'
# 字典检查
def check_dictname(val):
default_val = 'dict/domain.txt'
if val:
if os.path.exists('dict/'+val):
return 'dict/'+val
else:
return default_val
else:
return default_val
# 线程数控制
def check_threads(val):
try:
threads_count = int(val)
if threads_count > 0 and threads_count < 21:
return threads_count
else:
return 10
except Exception, e:
threads_count = 5
finally:
return threads_count | mit | -6,830,396,850,794,522,000 | 16.515625 | 53 | 0.673214 | false |
mtlchun/edx | lms/djangoapps/course_wiki/tests/test_access.py | 1 | 8503 | """
Tests for wiki permissions
"""
from django.contrib.auth.models import Group
from student.tests.factories import UserFactory
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from django.test.utils import override_settings
from courseware.tests.factories import InstructorFactory, StaffFactory
from xmodule.modulestore.tests.django_utils import TEST_DATA_MOCK_MODULESTORE
from wiki.models import URLPath
from course_wiki.views import get_or_create_root
from course_wiki.utils import user_is_article_course_staff, course_wiki_slug
from course_wiki import settings
class TestWikiAccessBase(ModuleStoreTestCase):
"""Base class for testing wiki access."""
def setUp(self):
super(TestWikiAccessBase, self).setUp()
self.wiki = get_or_create_root()
self.course_math101 = CourseFactory.create(org='org', number='math101', display_name='Course', metadata={'use_unique_wiki_id': 'false'})
self.course_math101_staff = self.create_staff_for_course(self.course_math101)
wiki_math101 = self.create_urlpath(self.wiki, course_wiki_slug(self.course_math101))
wiki_math101_page = self.create_urlpath(wiki_math101, 'Child')
wiki_math101_page_page = self.create_urlpath(wiki_math101_page, 'Grandchild')
self.wiki_math101_pages = [wiki_math101, wiki_math101_page, wiki_math101_page_page]
self.course_math101b = CourseFactory.create(org='org', number='math101b', display_name='Course', metadata={'use_unique_wiki_id': 'true'})
self.course_math101b_staff = self.create_staff_for_course(self.course_math101b)
wiki_math101b = self.create_urlpath(self.wiki, course_wiki_slug(self.course_math101b))
wiki_math101b_page = self.create_urlpath(wiki_math101b, 'Child')
wiki_math101b_page_page = self.create_urlpath(wiki_math101b_page, 'Grandchild')
self.wiki_math101b_pages = [wiki_math101b, wiki_math101b_page, wiki_math101b_page_page]
def create_urlpath(self, parent, slug):
"""Creates an article at /parent/slug and returns its URLPath"""
return URLPath.create_article(parent, slug, title=slug)
def create_staff_for_course(self, course):
"""Creates and returns users with instructor and staff access to course."""
return [
InstructorFactory(course_key=course.id), # Creates instructor_org/number/run role name
StaffFactory(course_key=course.id), # Creates staff_org/number/run role name
]
class TestWikiAccess(TestWikiAccessBase):
"""Test wiki access for course staff."""
def setUp(self):
super(TestWikiAccess, self).setUp()
self.course_310b = CourseFactory.create(org='org', number='310b', display_name='Course')
self.course_310b_staff = self.create_staff_for_course(self.course_310b)
self.course_310b2 = CourseFactory.create(org='org', number='310b_', display_name='Course')
self.course_310b2_staff = self.create_staff_for_course(self.course_310b2)
self.wiki_310b = self.create_urlpath(self.wiki, course_wiki_slug(self.course_310b))
self.wiki_310b2 = self.create_urlpath(self.wiki, course_wiki_slug(self.course_310b2))
def test_no_one_is_root_wiki_staff(self):
all_course_staff = self.course_math101_staff + self.course_310b_staff + self.course_310b2_staff
for course_staff in all_course_staff:
self.assertFalse(user_is_article_course_staff(course_staff, self.wiki.article))
def test_course_staff_is_course_wiki_staff(self):
for page in self.wiki_math101_pages:
for course_staff in self.course_math101_staff:
self.assertTrue(user_is_article_course_staff(course_staff, page.article))
for page in self.wiki_math101b_pages:
for course_staff in self.course_math101b_staff:
self.assertTrue(user_is_article_course_staff(course_staff, page.article))
def test_settings(self):
for page in self.wiki_math101_pages:
for course_staff in self.course_math101_staff:
self.assertTrue(settings.CAN_DELETE(page.article, course_staff))
self.assertTrue(settings.CAN_MODERATE(page.article, course_staff))
self.assertTrue(settings.CAN_CHANGE_PERMISSIONS(page.article, course_staff))
self.assertTrue(settings.CAN_ASSIGN(page.article, course_staff))
self.assertTrue(settings.CAN_ASSIGN_OWNER(page.article, course_staff))
for page in self.wiki_math101b_pages:
for course_staff in self.course_math101b_staff:
self.assertTrue(settings.CAN_DELETE(page.article, course_staff))
self.assertTrue(settings.CAN_MODERATE(page.article, course_staff))
self.assertTrue(settings.CAN_CHANGE_PERMISSIONS(page.article, course_staff))
self.assertTrue(settings.CAN_ASSIGN(page.article, course_staff))
self.assertTrue(settings.CAN_ASSIGN_OWNER(page.article, course_staff))
def test_other_course_staff_is_not_course_wiki_staff(self):
for page in self.wiki_math101_pages:
for course_staff in self.course_math101b_staff:
self.assertFalse(user_is_article_course_staff(course_staff, page.article))
for page in self.wiki_math101_pages:
for course_staff in self.course_310b_staff:
self.assertFalse(user_is_article_course_staff(course_staff, page.article))
for course_staff in self.course_310b_staff:
self.assertFalse(user_is_article_course_staff(course_staff, self.wiki_310b2.article))
for course_staff in self.course_310b2_staff:
self.assertFalse(user_is_article_course_staff(course_staff, self.wiki_310b.article))
class TestWikiAccessForStudent(TestWikiAccessBase):
"""Test access for students."""
def setUp(self):
super(TestWikiAccessForStudent, self).setUp()
self.student = UserFactory.create()
def test_student_is_not_root_wiki_staff(self):
self.assertFalse(user_is_article_course_staff(self.student, self.wiki.article))
def test_student_is_not_course_wiki_staff(self):
for page in self.wiki_math101_pages:
self.assertFalse(user_is_article_course_staff(self.student, page.article))
class TestWikiAccessForNumericalCourseNumber(TestWikiAccessBase):
"""Test staff has access if course number is numerical and wiki slug has an underscore appended."""
def setUp(self):
super(TestWikiAccessForNumericalCourseNumber, self).setUp()
self.course_200 = CourseFactory.create(org='org', number='200', display_name='Course')
self.course_200_staff = self.create_staff_for_course(self.course_200)
wiki_200 = self.create_urlpath(self.wiki, course_wiki_slug(self.course_200))
wiki_200_page = self.create_urlpath(wiki_200, 'Child')
wiki_200_page_page = self.create_urlpath(wiki_200_page, 'Grandchild')
self.wiki_200_pages = [wiki_200, wiki_200_page, wiki_200_page_page]
def test_course_staff_is_course_wiki_staff_for_numerical_course_number(self): # pylint: disable=invalid-name
for page in self.wiki_200_pages:
for course_staff in self.course_200_staff:
self.assertTrue(user_is_article_course_staff(course_staff, page.article))
class TestWikiAccessForOldFormatCourseStaffGroups(TestWikiAccessBase):
"""Test staff has access if course group has old format."""
def setUp(self):
super(TestWikiAccessForOldFormatCourseStaffGroups, self).setUp()
self.course_math101c = CourseFactory.create(org='org', number='math101c', display_name='Course')
Group.objects.get_or_create(name='instructor_math101c')
self.course_math101c_staff = self.create_staff_for_course(self.course_math101c)
wiki_math101c = self.create_urlpath(self.wiki, course_wiki_slug(self.course_math101c))
wiki_math101c_page = self.create_urlpath(wiki_math101c, 'Child')
wiki_math101c_page_page = self.create_urlpath(wiki_math101c_page, 'Grandchild')
self.wiki_math101c_pages = [wiki_math101c, wiki_math101c_page, wiki_math101c_page_page]
def test_course_staff_is_course_wiki_staff(self):
for page in self.wiki_math101c_pages:
for course_staff in self.course_math101c_staff:
self.assertTrue(user_is_article_course_staff(course_staff, page.article))
| agpl-3.0 | -3,366,610,191,432,532,000 | 49.916168 | 145 | 0.700811 | false |
hanw/sonic-lite | p4/tests/pcap/generate-pcap.py | 1 | 3583 | #!/user/bin/python
import argparse
import collections
import logging
import os
import random
import sys
logging.getLogger("scapy").setLevel(1)
from scapy.all import *
parser = argparse.ArgumentParser(description="Test packet generator")
parser.add_argument('--out-dir', help="Output path", type=str, action='store', default=os.getcwd())
args = parser.parse_args()
all_pkts = collections.OrderedDict()
def gen_udp_pkts():
# ETH|VLAN|VLAN|IP|UDP
all_pkts['vlan2-udp'] = Ether(src="34:17:eb:96:bf:1b", dst="34:17:eb:96:bf:1c") / \
Dot1Q(vlan=3393) / Dot1Q(vlan=2000) / IP(src="10.0.0.1", dst="10.0.0.2") / \
UDP(sport=6000, dport=6639)
# ETH|VLAN|IP|UDP
all_pkts['vlan-udp'] = Ether(src="34:17:eb:96:bf:1b", dst="34:17:eb:96:bf:1c") / \
Dot1Q(vlan=3393) / IP(src="10.0.0.1", dst="10.0.0.2") / \
UDP(sport=6000, dport=20000)
# ETH|VLAN|IP|UDP
all_pkts['udp-small'] = Ether(src="34:17:eb:96:bf:1b", dst="34:17:eb:96:bf:1c") / \
IP(src="10.0.0.1", dst="10.0.0.2") / \
UDP(sport=6000, dport=20000)
# ETH|VLAN|IP|UDP|PAYLOAD
data = bytearray(os.urandom(1000))
all_pkts['udp-large'] = Ether(src="34:17:eb:96:bf:1b", dst="34:17:eb:96:bf:1c") / \
IP(src="10.0.0.1", dst="10.0.0.2") / \
UDP(sport=6000, dport=20000) / Raw(data)
data = bytearray(os.urandom(500))
all_pkts['udp-mid'] = Ether(src="34:17:eb:96:bf:1b", dst="34:17:eb:96:bf:1c") / \
IP(src="10.0.0.1", dst="10.0.0.2") / \
UDP(sport=6000, dport=20000) / Raw(data)
# ETH|VLAN|IP|UDP
sweep_small = PacketList()
for i in range(8):
sweep_small.append(Ether(src="34:17:eb:96:bf:1b", dst="34:17:eb:96:bf:1c") / \
IP(src="10.0.0.12", dst="10.0.0.{}".format(i)) / \
UDP(sport=6000, dport=20000))
all_pkts['udp-sweep-small'] = sweep_small
# ETH|IP|UDP|PAYLOAD X 10
udp_10 = PacketList()
for i in range(10):
data = bytearray(os.urandom(random.randint(1,100)))
udp_10.append(Ether(src="34:17:eb:96:bf:1b", dst="34:17:eb:96:bf:1c") / \
IP(src="10.0.0.1", dst="10.0.0.2") / \
UDP(sport=6000, dport=20000) / Raw(data))
all_pkts['udp-burst'] = udp_10
vlan_10 = PacketList()
for i in range(10):
data = bytearray(os.urandom(random.randint(1,100)))
vlan_10.append(Ether(src="34:17:eb:96:bf:1b", dst="34:17:eb:96:bf:1c") / \
Dot1Q(vlan=3393) / IP(src="10.0.0.1", dst="10.0.0.2") / \
UDP(sport=6000, dport=20000) / Raw(data))
all_pkts['vlan-burst'] = vlan_10
# ETH|IP|UDP|PAYLOAD X 10
udp_5 = PacketList()
for i in range(5):
data = bytearray(os.urandom(random.randint(1,100)))
udp_5.append(Ether(src="34:17:eb:96:bf:1b", dst="34:17:eb:96:bf:1c") / \
IP(src="10.0.0.1", dst="10.0.0.2") / \
UDP(sport=6000, dport=20000) / Raw(data))
all_pkts['udp-burst-5'] = udp_5
def gen_tcp_pkts():
pass
def main():
gen_udp_pkts()
gen_tcp_pkts()
with open("%s/packet.mk" % args.out_dir, "w") as f:
f.write("TEST_PACKET=")
for packet in all_pkts.keys():
f.write(" "+packet)
for k, v in all_pkts.iteritems():
wrpcap('%s/%s.pcap' % (args.out_dir, k), v)
if __name__ == '__main__':
main()
| mit | -1,404,668,318,204,202,500 | 35.561224 | 105 | 0.5247 | false |
bigmlcom/bigmler | bigmler/tests/basic_linear_r_steps.py | 1 | 6880 | # -*- coding: utf-8 -*-
#
# Copyright 2016-2021 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import time
import json
from bigmler.tests.world import world, res_filename
from subprocess import check_call, CalledProcessError
from bigml.api import check_resource
from bigml.io import UnicodeReader
from bigmler.processing.models import MONTECARLO_FACTOR
from bigmler.checkpoint import file_number_of_lines
from bigmler.utils import storage_file_name, open_mode
from bigmler.tests.common_steps import check_debug
from nose.tools import ok_, assert_equal, assert_not_equal
def shell_execute(command, output, test=None, options=None,
test_rows=None, project=True):
"""Excute bigmler command in shell
"""
command = check_debug(command, project=project)
world.directory = os.path.dirname(output)
world.folders.append(world.directory)
try:
retcode = check_call(command, shell=True)
if retcode < 0:
assert False
else:
if test is not None:
world.test_lines = file_number_of_lines(test)
if options is None or \
options.find('--prediction-header') == -1:
# test file has headers in it, so first line must be ignored
world.test_lines -= 1
elif test_rows is not None:
world.test_lines = test_rows
if options is not None and \
options.find('--prediction-header') > -1:
world.test_lines += 1
elif options is not None and \
options.find('--prediction-header') > -1:
world.test_lines += 1
world.output = output
assert True
except (OSError, CalledProcessError, IOError) as exc:
assert False, str(exc)
#@step(r'I create BigML resources uploading train "(.*?)" file with no headers to test "(.*?)" with no headers and log predictions in "([^"]*)"$')
def i_create_all_lr_resources_with_no_headers(step, data=None, test=None, output=None):
ok_(data is not None and test is not None and output is not None)
test = res_filename(test)
command = ("bigmler linear-regression --train " + res_filename(data) +
" --test " + test +
" --store --no-bias --output " + output +
" --no-train-header --default-numeric-value mean --no-test-header")
shell_execute(command, output, test=test, options='--prediction-header')
#@step(r'I create BigML resources uploading train "(.*?)" file to test "(.*?)" and log predictions in "([^"]*)"$')
def i_create_all_lr_resources(step, data=None, test=None, output=None):
ok_(data is not None and test is not None and output is not None)
test = res_filename(test)
command = ("bigmler linear-regression --train " + res_filename(data) +
" --test " + test +
" --store --no-bias --default-numeric-value mean --output " + output)
shell_execute(command, output, test=test)
#@step(r'I create BigML (multi-label\s)?resources using source to test "(.*)" and log predictions in "(.*)"')
def i_create_lr_resources_from_source(step, multi_label=None, test=None, output=None):
ok_(test is not None and output is not None)
test = res_filename(test)
multi_label = "" if multi_label is None else " --multi-label "
command = ("bigmler linear-regression "+ multi_label +"--source " +
world.source['resource'] + " --test " + test +
" --store --no-bias --default-numeric-value mean --output " + output)
shell_execute(command, output, test=test)
#@step(r'I create BigML (multi-label\s)?resources using dataset to test "(.*)" and log predictions in "(.*)"')
def i_create_lr_resources_from_dataset(step, multi_label=None, test=None, output=None):
ok_(test is not None and output is not None)
multi_label = "" if multi_label is None else " --multi-label "
test = res_filename(test)
command = ("bigmler linear-regression "+ multi_label +"--dataset " +
world.dataset['resource'] + " --test " + test +
" --store --no-bias --default-numeric-value mean --output " + output)
shell_execute(command, output, test=test)
#@step(r'I create BigML resources using model to test "(.*)" and log predictions in "(.*)"')
def i_create_lr_resources_from_model(step, test=None, output=None):
ok_(test is not None and output is not None)
test = res_filename(test)
command = ("bigmler linear-regression --linear-regression " +
world.linear_regression['resource'] + " --test " +
test + " --store --no-bias --default-numeric-value mean --output " +
output)
shell_execute(command, output, test=test)
#@step(r'I create BigML resources using model to test "(.*)" as batch prediction and log predictions in "(.*)"')
def i_create_lr_resources_from_model_remote(step, test=None, output=None):
ok_(test is not None and output is not None)
test = res_filename(test)
command = ("bigmler linear-regression --linear-regression " +
world.linear_regression['resource'] + " --test " + test +
" --store --no-bias --default-numeric-value mean --remote --output " +
output)
shell_execute(command, output, test=test)
#@step(r'I check that the linear regression model has been created')
def i_check_create_lr_model(step):
lr_file = "%s%slinear_regressions" % (world.directory, os.sep)
try:
lr_file = open(lr_file, "r")
lr = check_resource(lr_file.readline().strip(),
world.api.get_linear_regression)
world.linear_regressions.append(lr['resource'])
world.linear_regression = lr
lr_file.close()
assert True
except Exception as exc:
assert False, str(exc)
#@step(r'I create BigML linear regression resources uploading train "(.*)" file to evaluate and log evaluation in "([^"]*)"$')
def i_create_all_lr_resources_to_evaluate(step, data=None, output=None):
ok_(data is not None and output is not None)
command = ("bigmler linear-regression --train " + res_filename(data) +
" --evaluate --default-numeric-value mean " +
" --store --no-bias --output " + output)
shell_execute(command, output)
| apache-2.0 | -2,505,341,523,934,095,400 | 44.866667 | 146 | 0.633866 | false |
eoghanbkeegan/eoghanbkeegan | eoghanbkeegan/public/views.py | 1 | 2185 | # -*- coding: utf-8 -*-
"""Public section, including homepage and signup."""
from flask import (
Blueprint,
current_app,
flash,
redirect,
render_template,
request,
url_for,
)
from flask_login import login_required, login_user, logout_user
from eoghanbkeegan.extensions import login_manager
from eoghanbkeegan.public.forms import LoginForm
from eoghanbkeegan.user.forms import RegisterForm
from eoghanbkeegan.user.models import User
from eoghanbkeegan.utils import flash_errors
blueprint = Blueprint("public", __name__, static_folder="../static")
@login_manager.user_loader
def load_user(user_id):
"""Load user by ID."""
return User.get_by_id(int(user_id))
@blueprint.route("/", methods=["GET", "POST"])
def home():
"""Home page."""
form = LoginForm(request.form)
current_app.logger.info("Hello from the home page!")
# Handle logging in
if request.method == "POST":
if form.validate_on_submit():
login_user(form.user)
flash("You are logged in.", "success")
redirect_url = request.args.get("next") or url_for("user.members")
return redirect(redirect_url)
else:
flash_errors(form)
return render_template("public/home.html", form=form)
@blueprint.route("/logout/")
@login_required
def logout():
"""Logout."""
logout_user()
flash("You are logged out.", "info")
return redirect(url_for("public.home"))
@blueprint.route("/register/", methods=["GET", "POST"])
def register():
"""Register new user."""
form = RegisterForm(request.form)
if form.validate_on_submit():
User.create(
username=form.username.data,
email=form.email.data,
password=form.password.data,
active=True,
)
flash("Thank you for registering. You can now log in.", "success")
return redirect(url_for("public.home"))
else:
flash_errors(form)
return render_template("public/register.html", form=form)
@blueprint.route("/about/")
def about():
"""About page."""
form = LoginForm(request.form)
return render_template("public/about.html", form=form)
| mit | -6,613,235,925,513,384,000 | 27.376623 | 78 | 0.64119 | false |
Passaudage/PLD | simulateur/GenerateurEntrees.py | 1 | 3667 | import SimulationManager
import math
import random
import Vehicule
def proba_poisson(k, freq, temps_obs):
#Calcul du lambda correspondant
l = freq * temps_obs
p = math.e ** (-l)
for i in range(0, k):
p *= l/k
k = k-1
return p
def var_poisson(freq, temps_obs):
proba_cumulee = random.random()
k = 0
proba_cumul_iter = proba_poisson(0, freq, temps_obs)
while proba_cumul_iter < proba_cumulee:
k += 1
proba_cumul_iter += proba_poisson(k, freq, temps_obs)
return k
class GenerateurEntrees:
# Contrat : les heures_freqs : liste triées par heures croissantes
# Les frequences sont en nombre de voitures par minutes
duree_journee = 3600 * 24 * SimulationManager.SimulationManager.nombre_ticks_seconde
def __init__(self, heures_freqs):
self._attente = []
self._heures_freqs = heures_freqs
self._timestamp_max = heures_freqs[-1][0]
self._timestamp_min = heures_freqs[0][0]
self._etendue = self._timestamp_max - self._timestamp_min
self._voies_sortantes = []
self._voies_entrantes = []
def ajoute_voie_entrante(self, voies):
self._voies_entrantes = voies
def ajoute_voie_sortante(self, voies):
self._voies_sortantes = voies
def notifie_temps(self, increment, moteur):
#~ print("Le generateur a ete modifie.")
freq = 0
if self._etendue == 0:
freq = self._heures_freqs[0][1]
else:
timestamp = (moteur.temps % self.duree_journee) / self.duree_journee * self._etendue
i = 0
while self._heures_freqs[i+1][0] < timestamp:
i+=1
timestamp_gauche = self._heures_freqs[i][0]
timestamp_droite = self._heures_freqs[i+1][0]
fact_prop = (timestamp - timestamp_gauche) / (timestamp_droite - timestamp_gauche)
freq_gauche = self._heures_freqs[i][1]
freq_droite = self._heures_freqs[i+1][1]
freq = freq_gauche + fact_prop * (freq_droite - freq_gauche)
nombre_voit_crees = var_poisson(freq/(60*moteur.nombre_ticks_seconde), increment)
#~ print("Nombre de voitures : "+str(nombre_voit_crees))
for i in range(nombre_voit_crees):
longueur = random.normalvariate(428, 50)
aggressivite = (random.random() < Vehicule.Vehicule.proportion_discourtois)
somme_probas = 0
for voie in self._voies_sortantes:
somme_probas += voie.get_proba_voie()
probas = [ voie.get_proba_voie() / somme_probas for voie in self._voies_sortantes ]
k = 0
pc = probas[k]
p = random.random()
while pc < p:
k += 1
pc += probas[k]
voie = self._voies_sortantes[k]
voie.creer_vehicule(moteur, aggressivite, longueur)
#pas toujours vrai en vrai
def est_passant(self):
return True
################################################
# TESTS
################################################
#print('##### Tests #####')
#print('## Loi de poisson l = 1')
#for i in range(0, 5):
# print(proba_poisson(i, 1, 1))
#
#print('## Loi de poisson l = 2')
#for i in range(0, 7):
# print(proba_poisson(i, 2, 1))
#
#print('\n##Génération d\'une série de valeurs suivant une loi de Poisson de param. 1')
#R = []
#for i in range(0, 1000):
# R.append(var_poisson(1, 1))
#
#print('\n##Génération d\'une série de valeurs suivant une loi de Poisson de param. 10')
#R = []
#for i in range(0, 1000):
# R.append(var_poisson(1, 10))
#print(R)
| mit | -9,006,118,670,060,994,000 | 32.888889 | 96 | 0.568579 | false |
jhanschoo/imprimo | models.py | 1 | 1659 | # -*- coding: utf-8 -*-
from django.db import models
from .validators import validate_printable
import os
class JobSession(models.Model):
status = models.CharField(max_length=3000)
all_status = models.CharField(max_length=48000)
attachedfile = models.FileField(
upload_to='imprimo',
validators=[validate_printable])
printer = models.CharField(max_length=12)
completed = models.BooleanField()
def __unicode__(self):
returnstring = "id: %s, status: %s" % (str(self.id), self.status)
if self.attachedfile:
returnstring += ", attachedfile: %s" % str(self.attachedfile.name)
return returnstring
def update_status(self, status):
update = JobSession.objects.get(pk=self.pk)
self.status = update.status+"\n"+status
self.all_status += "\n"+status
self.save(update_fields=['status', 'all_status'])
def print_status(self):
status = self.status
self.status = ''
if self.completed:
self.delete()
else:
self.save(update_fields=['status'])
return status
def print_all_status(self):
self.status = ''
if self.completed:
self.deleted()
else:
self.save(update_fields=['status'])
return self.all_status
def attachedfilename(self):
return os.path.basename(self.attachedfile.name)
def filetype(self):
self.attachedfile.open()
magic_number = self.attachedfile.read(2)
self.attachedfile.open()
if magic_number == r'%!':
return 'ps'
else:
return 'pdf'
| mit | -1,411,429,079,755,548,200 | 31.529412 | 78 | 0.596745 | false |
molobrakos/home-assistant | homeassistant/components/traccar/device_tracker.py | 1 | 7651 | """Support for Traccar device tracking."""
from datetime import datetime, timedelta
import logging
import voluptuous as vol
from homeassistant.components.device_tracker import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_PORT, CONF_SSL, CONF_VERIFY_SSL,
CONF_PASSWORD, CONF_USERNAME, ATTR_BATTERY_LEVEL,
CONF_SCAN_INTERVAL, CONF_MONITORED_CONDITIONS,
CONF_EVENT)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.util import slugify
_LOGGER = logging.getLogger(__name__)
ATTR_ADDRESS = 'address'
ATTR_CATEGORY = 'category'
ATTR_GEOFENCE = 'geofence'
ATTR_MOTION = 'motion'
ATTR_SPEED = 'speed'
ATTR_TRACKER = 'tracker'
ATTR_TRACCAR_ID = 'traccar_id'
EVENT_DEVICE_MOVING = 'device_moving'
EVENT_COMMAND_RESULT = 'command_result'
EVENT_DEVICE_FUEL_DROP = 'device_fuel_drop'
EVENT_GEOFENCE_ENTER = 'geofence_enter'
EVENT_DEVICE_OFFLINE = 'device_offline'
EVENT_DRIVER_CHANGED = 'driver_changed'
EVENT_GEOFENCE_EXIT = 'geofence_exit'
EVENT_DEVICE_OVERSPEED = 'device_overspeed'
EVENT_DEVICE_ONLINE = 'device_online'
EVENT_DEVICE_STOPPED = 'device_stopped'
EVENT_MAINTENANCE = 'maintenance'
EVENT_ALARM = 'alarm'
EVENT_TEXT_MESSAGE = 'text_message'
EVENT_DEVICE_UNKNOWN = 'device_unknown'
EVENT_IGNITION_OFF = 'ignition_off'
EVENT_IGNITION_ON = 'ignition_on'
EVENT_ALL_EVENTS = 'all_events'
DEFAULT_SCAN_INTERVAL = timedelta(seconds=30)
SCAN_INTERVAL = DEFAULT_SCAN_INTERVAL
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_PORT, default=8082): cv.port,
vol.Optional(CONF_SSL, default=False): cv.boolean,
vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
vol.Optional(CONF_MONITORED_CONDITIONS,
default=[]): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_EVENT,
default=[]): vol.All(cv.ensure_list,
[vol.Any(EVENT_DEVICE_MOVING,
EVENT_COMMAND_RESULT,
EVENT_DEVICE_FUEL_DROP,
EVENT_GEOFENCE_ENTER,
EVENT_DEVICE_OFFLINE,
EVENT_DRIVER_CHANGED,
EVENT_GEOFENCE_EXIT,
EVENT_DEVICE_OVERSPEED,
EVENT_DEVICE_ONLINE,
EVENT_DEVICE_STOPPED,
EVENT_MAINTENANCE,
EVENT_ALARM,
EVENT_TEXT_MESSAGE,
EVENT_DEVICE_UNKNOWN,
EVENT_IGNITION_OFF,
EVENT_IGNITION_ON,
EVENT_ALL_EVENTS)]),
})
async def async_setup_scanner(hass, config, async_see, discovery_info=None):
"""Validate the configuration and return a Traccar scanner."""
from pytraccar.api import API
session = async_get_clientsession(hass, config[CONF_VERIFY_SSL])
api = API(hass.loop, session, config[CONF_USERNAME], config[CONF_PASSWORD],
config[CONF_HOST], config[CONF_PORT], config[CONF_SSL])
scanner = TraccarScanner(
api, hass, async_see,
config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL),
config[CONF_MONITORED_CONDITIONS], config[CONF_EVENT])
return await scanner.async_init()
class TraccarScanner:
"""Define an object to retrieve Traccar data."""
def __init__(self, api, hass, async_see, scan_interval,
custom_attributes,
event_types):
"""Initialize."""
from stringcase import camelcase
self._event_types = {camelcase(evt): evt for evt in event_types}
self._custom_attributes = custom_attributes
self._scan_interval = scan_interval
self._async_see = async_see
self._api = api
self._hass = hass
async def async_init(self):
"""Further initialize connection to Traccar."""
await self._api.test_connection()
if self._api.authenticated:
await self._async_update()
async_track_time_interval(self._hass,
self._async_update,
self._scan_interval)
return self._api.authenticated
async def _async_update(self, now=None):
"""Update info from Traccar."""
_LOGGER.debug('Updating device data.')
await self._api.get_device_info(self._custom_attributes)
self._hass.async_create_task(self.import_device_data())
if self._event_types:
self._hass.async_create_task(self.import_events())
async def import_device_data(self):
"""Import device data from Traccar."""
for devicename in self._api.device_info:
device = self._api.device_info[devicename]
attr = {}
attr[ATTR_TRACKER] = 'traccar'
if device.get('address') is not None:
attr[ATTR_ADDRESS] = device['address']
if device.get('geofence') is not None:
attr[ATTR_GEOFENCE] = device['geofence']
if device.get('category') is not None:
attr[ATTR_CATEGORY] = device['category']
if device.get('speed') is not None:
attr[ATTR_SPEED] = device['speed']
if device.get('battery') is not None:
attr[ATTR_BATTERY_LEVEL] = device['battery']
if device.get('motion') is not None:
attr[ATTR_MOTION] = device['motion']
if device.get('traccar_id') is not None:
attr[ATTR_TRACCAR_ID] = device['traccar_id']
for custom_attr in self._custom_attributes:
if device.get(custom_attr) is not None:
attr[custom_attr] = device[custom_attr]
await self._async_see(
dev_id=slugify(device['device_id']),
gps=(device.get('latitude'), device.get('longitude')),
attributes=attr)
async def import_events(self):
"""Import events from Traccar."""
device_ids = [device['id'] for device in self._api.devices]
end_interval = datetime.utcnow()
start_interval = end_interval - self._scan_interval
events = await self._api.get_events(
device_ids=device_ids,
from_time=start_interval,
to_time=end_interval,
event_types=self._event_types.keys())
if events is not None:
for event in events:
device_name = next((
dev.get('name') for dev in self._api.devices()
if dev.get('id') == event['deviceId']), None)
self._hass.bus.async_fire(
'traccar_' + self._event_types.get(event["type"]), {
'device_traccar_id': event['deviceId'],
'device_name': device_name,
'type': event['type'],
'serverTime': event['serverTime'],
'attributes': event['attributes']
})
| apache-2.0 | 3,952,886,422,262,228,000 | 41.038462 | 79 | 0.562018 | false |
braincow/python-redisjobqueue | redisjobqueue/__init__.py | 1 | 4096 | import redis
import redlock
import time
import datetime
import json
import time
class JobLockHasExpiredException(Exception):
"""This Exception is raised when access or modify is attempted on a job that had its lock expire"""
pass
class JobNotValidException(Exception):
"""This Exception is raised when access or modify is attempted on a job that was previously already completed"""
pass
class JobAlreadyInQueueException(Exception):
"""This Exception is raised if adding a duplicate job to a queue is detected and therefore refused."""
pass
class RedisJobQueueItem(object):
def __init__(self, data, lock, queue):
"""Job item in work queue"""
# store job info for later use
self.data = data
self.lock = lock
self.queue = queue
# on init this job becomes valid as it has a lock
self.valid = True
# and also calculate the datetime in UTC after which the lock expires
self.expires = datetime.datetime.utcnow() + datetime.timedelta(milliseconds=self.lock.validity)
def _isvalid(self):
# check for internal status flag
if not self.valid:
raise JobNotValidException("This job has been released previously.")
# check for job lock validity
if datetime.datetime.utcnow() > self.expires:
raise JobLockHasExpiredException("Lock for this job has expired.")
# always return true if no exception on validity checks were raised
return True
def get(self):
"""Fetch the data stored in this job"""
if self._isvalid():
return self.data
def complete(self):
"""Delete job from queue and release the lock"""
if self._isvalid():
# delete item from queue
self.queue.rem(self.data)
# release lock after removal or failure
self.queue.dlm.unlock(self.lock)
# mark job as invalid
self.valid = False
def release(self):
"""Release lock only and leave data in queue"""
if self._isvalid():
# mark job as invalid
self.valid = False
# release lock
self.queue.dlm.unlock(self.lock)
class RedisJobQueue(object):
def __init__(self, queue_name="jobs", redis_host="localhost", redis_port=6379, redis_db=0, queue_namespace="queue"):
"""Simple message queue with Redis backend and distributed locking"""
# construct queue namespace
self.key = "%s:%s" % (queue_namespace, queue_name)
# try to open redis connection to host
self.redis = redis.Redis(host=redis_host, port=redis_port, db=redis_db)
# also open a lock redis connection to host, ugh its ugly. Is there a better way to do this?
conn_params = [{"host": redis_host, "port": redis_port, "db": redis_db}, ]
self.dlm = redlock.Redlock(conn_params)
def size(self):
"""Return the approximate size of the queue."""
return self.redis.zcard(self.key)
def isempty(self):
"""Returns True if the queue currently contains no jobs"""
if self.size() > 0:
return False
else:
return True
def put(self, item):
"""Put item into the queue."""
# use current seconds from epoc moment as a score for Redis ZADD to accomplished sorted fifo queue
if not self.redis.zadd(self.key, json.dumps(item), time.time()):
raise JobAlreadyInQueueException("This job was found in Redis based work queue '%s'. Refusing to add it." % self.key)
def get(self, lock_timeout = 1000):
"""Get a job from the list if available and lock it"""
# get the members in the list and try to acquire a lock until succesful
for item in self.redis.zrange(self.key, 0, -1):
my_lock = self.dlm.lock(item, lock_timeout)
if my_lock:
# exit here because we found and locked a job
return RedisJobQueueItem(json.loads(item), my_lock, self)
def wait(self, interval = 0.1, lock_timeout = 1000):
"""Block and wait for a job to appear in the queue and return it when found"""
while True:
time.sleep(interval)
# query on each loop our own get method to check if there is a job available and lock it
job = self.get(lock_timeout = lock_timeout)
if job:
return job
def rem(self, item):
"""Remove item from job queue"""
if not self.redis.zrem(self.key, json.dumps(item)):
raise JobNotValidException("This job was not found in Redis workqueue.")
# eof | mit | 7,279,080,969,133,416,000 | 34.017094 | 120 | 0.714355 | false |
gilestrolab/ethoscope | src/ethoscope/roi_builders/target_roi_builder.py | 1 | 16065 | __author__ = 'quentin'
import cv2
try:
CV_VERSION = int(cv2.__version__.split(".")[0])
except:
CV_VERSION = 2
try:
from cv2.cv import CV_CHAIN_APPROX_SIMPLE as CHAIN_APPROX_SIMPLE
from cv2.cv import CV_AA as LINE_AA
except ImportError:
from cv2 import CHAIN_APPROX_SIMPLE
from cv2 import LINE_AA
import numpy as np
import logging
from ethoscope.roi_builders.roi_builders import BaseROIBuilder
from ethoscope.core.roi import ROI
from ethoscope.utils.debug import EthoscopeException
import itertools
class TargetGridROIBuilder(BaseROIBuilder):
_adaptive_med_rad = 0.10
_expected__min_target_dist = 10 # the minimal distance between two targets, in 'target diameter'
_n_rows = 10
_n_cols = 2
_top_margin = 0
_bottom_margin = None
_left_margin = 0
_right_margin = None
_horizontal_fill = 1
_vertical_fill = None
_description = {"overview": "A flexible ROI builder that allows users to select parameters for the ROI layout."
"Lengths are relative to the distance between the two bottom targets (width)",
"arguments": [
{"type": "number", "min": 1, "max": 16, "step":1, "name": "n_cols", "description": "The number of columns","default":1},
{"type": "number", "min": 1, "max": 16, "step":1, "name": "n_rows", "description": "The number of rows","default":1},
{"type": "number", "min": 0.0, "max": 1.0, "step":.001, "name": "top_margin", "description": "The vertical distance between the middle of the top ROIs and the middle of the top target.","default":0.0},
{"type": "number", "min": 0.0, "max": 1.0, "step":.001, "name": "bottom_margin", "description": "Same as top_margin, but for the bottom.","default":0.0},
{"type": "number", "min": 0.0, "max": 1.0, "step":.001, "name": "right_margin", "description": "Same as top_margin, but for the right.","default":0.0},
{"type": "number", "min": 0.0, "max": 1.0, "step":.001, "name": "left_margin", "description": "Same as top_margin, but for the left.","default":0.0},
{"type": "number", "min": 0.0, "max": 1.0, "step":.001, "name": "horizontal_fill", "description": "The proportion of the grid space used by the roi, horizontally.","default":0.90},
{"type": "number", "min": 0.0, "max": 1.0, "step":.001, "name": "vertical_fill", "description": "Same as horizontal_margin, but vertically.","default":0.90}
]}
def __init__(self, n_rows=1, n_cols=1, top_margin=0, bottom_margin=0,
left_margin=0, right_margin=0, horizontal_fill=.9, vertical_fill=.9):
"""
This roi builder uses three black circles drawn on the arena (targets) to align a grid layout:
IMAGE HERE
:param n_rows: The number of rows in the grid.
:type n_rows: int
:param n_cols: The number of columns.
:type n_cols: int
:param top_margin: The vertical distance between the middle of the top ROIs and the middle of the top target
:type top_margin: float
:param bottom_margin: same as top_margin, but for the bottom.
:type bottom_margin: float
:param left_margin: same as top_margin, but for the left side.
:type left_margin: float
:param right_margin: same as top_margin, but for the right side.
:type right_margin: float
:param horizontal_fill: The proportion of the grid space user by the roi, horizontally (between 0 and 1).
:type horizontal_fill: float
:param vertical_fill: same as vertical_fill, but horizontally.
:type vertical_fill: float
"""
self._n_rows = n_rows
self._n_cols = n_cols
self._top_margin = top_margin
self._bottom_margin = bottom_margin
self._left_margin = left_margin
self._right_margin = right_margin
self._horizontal_fill = horizontal_fill
self._vertical_fill = vertical_fill
# if self._vertical_fill is None:
# self._vertical_fill = self._horizontal_fill
# if self._right_margin is None:
# self._right_margin = self._left_margin
# if self._bottom_margin is None:
# self._bottom_margin = self._top_margin
super(TargetGridROIBuilder,self).__init__()
def _find_blobs(self, im, scoring_fun):
grey= cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
rad = int(self._adaptive_med_rad * im.shape[1])
if rad % 2 == 0:
rad += 1
med = np.median(grey)
scale = 255/(med)
cv2.multiply(grey,scale,dst=grey)
bin = np.copy(grey)
score_map = np.zeros_like(bin)
for t in range(0, 255,5):
cv2.threshold(grey, t, 255,cv2.THRESH_BINARY_INV,bin)
if np.count_nonzero(bin) > 0.7 * im.shape[0] * im.shape[1]:
continue
if CV_VERSION == 3:
_, contours, h = cv2.findContours(bin,cv2.RETR_EXTERNAL,CHAIN_APPROX_SIMPLE)
else:
contours, h = cv2.findContours(bin,cv2.RETR_EXTERNAL,CHAIN_APPROX_SIMPLE)
bin.fill(0)
for c in contours:
score = scoring_fun(c, im)
if score >0:
cv2.drawContours(bin,[c],0,score,-1)
cv2.add(bin, score_map,score_map)
return score_map
def _make_grid(self, n_col, n_row,
top_margin=0.0, bottom_margin=0.0,
left_margin=0.0, right_margin=0.0,
horizontal_fill = 1.0, vertical_fill=1.0):
y_positions = (np.arange(n_row) * 2.0 + 1) * (1-top_margin-bottom_margin)/(2*n_row) + top_margin
x_positions = (np.arange(n_col) * 2.0 + 1) * (1-left_margin-right_margin)/(2*n_col) + left_margin
all_centres = [np.array([x,y]) for x,y in itertools.product(x_positions, y_positions)]
sign_mat = np.array([
[-1, -1],
[+1, -1],
[+1, +1],
[-1, +1]
])
xy_size_vec = np.array([horizontal_fill/float(n_col), vertical_fill/float(n_row)]) / 2.0
rectangles = [sign_mat *xy_size_vec + c for c in all_centres]
return rectangles
def _points_distance(self, pt1, pt2):
x1 , y1 = pt1
x2 , y2 = pt2
return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
def _score_targets(self,contour, im):
area = cv2.contourArea(contour)
perim = cv2.arcLength(contour,True)
if perim == 0:
return 0
circul = 4 * np.pi * area / perim ** 2
if circul < .8: # fixme magic number
return 0
return 1
def _find_target_coordinates(self, img):
map = self._find_blobs(img, self._score_targets)
bin = np.zeros_like(map)
# as soon as we have three objects, we stop
contours = []
for t in range(0, 255,1):
cv2.threshold(map, t, 255,cv2.THRESH_BINARY ,bin)
if CV_VERSION == 3:
_, contours, h = cv2.findContours(bin,cv2.RETR_EXTERNAL, CHAIN_APPROX_SIMPLE)
else:
contours, h = cv2.findContours(bin, cv2.RETR_EXTERNAL, CHAIN_APPROX_SIMPLE)
if len(contours) <3:
raise EthoscopeException("There should be three targets. Only %i objects have been found" % (len(contours)), img)
if len(contours) == 3:
break
target_diams = [cv2.boundingRect(c)[2] for c in contours]
mean_diam = np.mean(target_diams)
mean_sd = np.std(target_diams)
if mean_sd/mean_diam > 0.10:
raise EthoscopeException("Too much variation in the diameter of the targets. Something must be wrong since all target should have the same size", img)
src_points = []
for c in contours:
moms = cv2.moments(c)
x , y = moms["m10"]/moms["m00"], moms["m01"]/moms["m00"]
src_points.append((x,y))
a ,b, c = src_points
pairs = [(a,b), (b,c), (a,c)]
dists = [self._points_distance(*p) for p in pairs]
# that is the AC pair
hypo_vertices = pairs[np.argmax(dists)]
# this is B : the only point not in (a,c)
for sp in src_points:
if not sp in hypo_vertices:
break
sorted_b = sp
dist = 0
for sp in src_points:
if sorted_b is sp:
continue
# b-c is the largest distance, so we can infer what point is c
if self._points_distance(sp, sorted_b) > dist:
dist = self._points_distance(sp, sorted_b)
sorted_c = sp
# the remaining point is a
sorted_a = [sp for sp in src_points if not sp is sorted_b and not sp is sorted_c][0]
sorted_src_pts = np.array([sorted_a, sorted_b, sorted_c], dtype=np.float32)
return sorted_src_pts
def _rois_from_img(self,img):
sorted_src_pts = self._find_target_coordinates(img)
dst_points = np.array([(0,-1),
(0,0),
(-1,0)], dtype=np.float32)
wrap_mat = cv2.getAffineTransform(dst_points, sorted_src_pts)
rectangles = self._make_grid(self._n_cols, self._n_rows,
self._top_margin, self._bottom_margin,
self._left_margin,self._right_margin,
self._horizontal_fill, self._vertical_fill)
shift = np.dot(wrap_mat, [1,1,0]) - sorted_src_pts[1] # point 1 is the ref, at 0,0
rois = []
for i,r in enumerate(rectangles):
r = np.append(r, np.zeros((4,1)), axis=1)
mapped_rectangle = np.dot(wrap_mat, r.T).T
mapped_rectangle -= shift
ct = mapped_rectangle.reshape((1,4,2)).astype(np.int32)
cv2.drawContours(img,[ct], -1, (255,0,0),1,LINE_AA)
rois.append(ROI(ct, idx=i+1))
# cv2.imshow("dbg",img)
# cv2.waitKey(0)
return rois
class ThirtyFliesMonitorWithTargetROIBuilder(TargetGridROIBuilder):
_description = {"overview": "The default sleep monitor arena with ten rows of two tubes.",
"arguments": []}
def __init__(self):
r"""
Class to build ROIs for a two-columns, ten-rows for the sleep monitor
(`see here <https://github.com/gilestrolab/ethoscope_hardware/tree/master/arenas/arena_10x2_shortTubes>`_).
"""
#`sleep monitor tube holder arena <todo>`_
super(SleepMonitorWithTargetROIBuilder, self).__init__(n_rows=10,
n_cols=3,
top_margin= 6.99 / 111.00,
bottom_margin = 6.99 / 111.00,
left_margin = -.033,
right_margin = -.033,
horizontal_fill = .975,
vertical_fill= .7
)
class SleepMonitorWithTargetROIBuilder(TargetGridROIBuilder):
_description = {"overview": "The default sleep monitor arena with ten rows of two tubes.",
"arguments": []}
def __init__(self):
r"""
Class to build ROIs for a two-columns, ten-rows for the sleep monitor
(`see here <https://github.com/gilestrolab/ethoscope_hardware/tree/master/arenas/arena_10x2_shortTubes>`_).
"""
#`sleep monitor tube holder arena <todo>`_
super(SleepMonitorWithTargetROIBuilder, self).__init__(n_rows=10,
n_cols=2,
top_margin= 6.99 / 111.00,
bottom_margin = 6.99 / 111.00,
left_margin = -.033,
right_margin = -.033,
horizontal_fill = .975,
vertical_fill= .7
)
class OlfactionAssayROIBuilder(TargetGridROIBuilder):
_description = {"overview": "The default odor assay roi layout with ten rows of single tubes.",
"arguments": []}
def __init__(self):
"""
Class to build ROIs for a one-column, ten-rows
(`see here <https://github.com/gilestrolab/ethoscope_hardware/tree/master/arenas/arena_10x1_longTubes>`_)
"""
#`olfactory response arena <todo>`_
super(OlfactionAssayROIBuilder, self).__init__(n_rows=10,
n_cols=1,
top_margin=6.99 / 111.00,
bottom_margin =6.99 / 111.00,
left_margin = -.033,
right_margin = -.033,
horizontal_fill = .975,
vertical_fill= .7
)
class ElectricShockAssayROIBuilder(TargetGridROIBuilder):
_description = {"overview": "A ROI layout for the automatic electric shock. 5 rows, 1 column",
"arguments": []}
def __init__(self):
"""
Class to build ROIs for a one-column, five-rows
(`Add gitbook URL when ready`_)
"""
#`olfactory response arena <todo>`_
super(ElectricShockAssayROIBuilder, self).__init__(n_rows=5,
n_cols=1,
top_margin=0.1,
bottom_margin =0.1,
left_margin = -.065,
right_margin = -.065,
horizontal_fill = .975,
vertical_fill= .7
)
class HD12TubesRoiBuilder(TargetGridROIBuilder):
_description = {"overview": "The default high resolution, 12 tubes (1 row) roi layout",
"arguments": []}
def __init__(self):
r"""
Class to build ROIs for a twelve columns, one row for the HD tracking arena
(`see here <https://github.com/gilestrolab/ethoscope_hardware/tree/master/arenas/arena_mini_12_tubes>`_)
"""
super(HD12TubesRoiBuilder, self).__init__( n_rows=1,
n_cols=12,
top_margin= 1.5,
bottom_margin= 1.5,
left_margin=0.05,
right_margin=0.05,
horizontal_fill=.7,
vertical_fill=1.4
)
| gpl-3.0 | -8,499,705,433,721,836,000 | 44.381356 | 237 | 0.484594 | false |
scem/zing | src/main/zing/follower.py | 1 | 1382 | '''
Created on May 21, 2015
@author: scem
'''
from threading import Thread
import zmq
ONLINE = 'online'
OFFLINE = 'offline'
class Follower(Thread):
'''
classdocs
'''
def __init__(self, me='anonymous', host='localhost', port='7002', timeout=None):
self.me = me
self.host = host
self.port = port
self.timeout = timeout
self._last = None
self._status = OFFLINE
Thread.__init__(self)
def status(self):
return self._status
def last(self):
return self._last
def stop(self):
self._status = OFFLINE
def run(self):
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.RCVBUF, 0)
socket.setsockopt(zmq.SUBSCRIBE, "%s:" % self.me)
socket.connect('tcp://%s:%s' % (self.host, self.port))
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
self._status = ONLINE
while self._status == ONLINE:
socks = dict(poller.poll(self.timeout))
if socket in socks and socks[socket] == zmq.POLLIN:
self._last = socket.recv()
self.publish(self._last)
socket.close()
context.term()
def publish(self,msg):
print msg
| gpl-2.0 | -6,393,160,262,061,951,000 | 22.678571 | 84 | 0.524602 | false |
felixplesoianu/advprompt | advc.py | 1 | 6594 | #!/usr/bin/env python3
# coding=utf-8
from __future__ import print_function
import sys
import configparser
import uuid
obj_types = ["actor", "room", "exit", "thing", "scenery", "vehicle", "text",
"action", "spell", "topic"]
lock_types = ["?", "!", "+", "-", "@", "^", "#", "~"]
def new_meta():
return {
"title": "An Interactive Fiction",
"author": "Anonymous",
"ifid": str(uuid.uuid4())
}
def new_config():
return {"banner": "", "max_score": 0, "use_score": True}
def new_room(name):
return {
"type": "room",
"name": name,
"description": ""
}
def new_actor(name, loc=None):
return {
"type": "actor",
"name": name,
"description": "As good-looking as ever.",
"location": loc
}
def new_game():
game = {
"meta": new_meta(),
"objects": {
"limbo": new_room("Limbo"),
"hero": new_actor("You", "limbo")
},
"config": new_config()
}
game["objects"]["limbo"]["description"] = "You are in limbo."
return game
def merge_data(config, output):
if "META" in config:
for i in config["META"]:
output["meta"][i] = config["META"][i]
if "CONFIG" in config:
for i in config["CONFIG"]:
if i == "max_score":
output["config"][i] = int(config["CONFIG"][i])
elif i == "use_score":
output["config"][i] = config.getboolean(
"CONFIG", i)
else:
output["config"][i] = config["CONFIG"][i]
flags = ["ending", "dark", "light", "sticky", "visited"]
for i in config:
if i in ["DEFAULT", "CONFIG", "META"]:
continue
if i not in output["objects"]:
output["objects"][i] = {}
inobj = config[i]
outobj = output["objects"][i]
for j in inobj:
if j == "score":
outobj[j] = int(inobj[j])
elif j in flags:
outobj[j] = config.getboolean(i, j)
else:
outobj[j] = inobj[j]
def sanity_check(game_data):
errcount = 0
db = game_data["objects"]
linked = set()
for i in db:
if "link" in db[i]:
if db[i]["link"] in db:
linked.add(db[i]["link"])
else:
report_bad_link(i, db[i]["link"])
errcount += 1
if "location" in db[i]:
if db[i]["location"] in db:
linked.add(db[i]["location"])
else: # Not really a problem unless it's the hero.
report_bad_parent(i, db[i]["location"])
errcount += 1
if "lock" in db[i]:
lock = db[i]["lock"][0]
key = db[i]["lock"][1:]
if lock not in lock_types:
report_bad_lock(i, lock)
errcount += 1
if key in db:
linked.add(key)
else:
report_bad_key(i, key)
errcount += 1
for i in list(db.keys()): # Allow for deleting keys within the loop.
if "type" not in db[i]:
db[i]["type"] = "thing"
report_default_type(i)
elif db[i]["type"] not in obj_types:
report_bad_type(i, db[i]["type"])
elif db[i]["type"] == "room":
if i not in linked:
if i == "limbo":
# It's probably the unused default.
del db[i]
else:
report_unlinked_room(i)
return errcount == 0
def report_bad_link(obj_id, link):
e = "Error: {0} links to non-existent object {1}."
print(e.format(obj_id, link), file=sys.stderr)
def report_bad_parent(obj_id, link):
e = "Error: {0} located in non-existent object {1}."
print(e.format(obj_id, link), file=sys.stderr)
def report_default_type(obj_id):
e = "Warning: Object {0} has no type, was set to 'thing'."
print(e.format(obj_id), file=sys.stderr)
def report_bad_type(obj_id, type_id):
e = "Warning: Object {0} has unknown type {1}."
print(e.format(obj_id, type_id), file=sys.stderr)
def report_bad_lock(obj_id, lock):
e = "Error: Bad key type {0} in object {1}."
print(e.format(lock, obj_id), file=sys.stderr)
def report_bad_key(obj_id, key_id):
e = "Error: {0} locked to non-existent object {1}."
print(e.format(obj_id, key_id), file=sys.stderr)
def report_unlinked_room(obj_id):
e = "Warning: room {0} has no links pointing to it."
print(e.format(obj_id), file=sys.stderr)
def story_stats(game_data):
type_count = {}
for i in game_data["objects"]:
obj = game_data["objects"][i]
t = obj["type"]
if t in type_count:
type_count[t] += 1
else:
type_count[t] = 1
return type_count
def game2config(game):
output = configparser.ConfigParser()
output["META"] = {}
for i in game["meta"]:
output["META"][i] = str(game["meta"][i])
output["CONFIG"] = {}
for i in game["config"]:
if type(game["config"][i]) == float:
output["CONFIG"][i] = str(int(game["config"][i]))
else:
output["CONFIG"][i] = str(game["config"][i])
for i in game["objects"]:
obj = game["objects"][i]
output[i] = {}
for j in obj:
if type(obj[j]) == float:
output[i][j] = str(int(obj[j]))
else:
output[i][j] = str(obj[j])
return output
if __name__ == "__main__":
import json
import argparse
pargs = argparse.ArgumentParser(prog="advc.py",
description="Compile Adventure Prompt config to a story file.",
epilog="Give no input files to get a minimal, default story.")
pargs.add_argument("-v", "--version", action="version",
version="%(prog)s version 1.0, 4 April 2018")
group = pargs.add_mutually_exclusive_group()
group.add_argument("-c", "--check", action="store_true",
help="only perform sanity checks, don't output a story")
group.add_argument("-s", "--stats", action="store_true",
help="output statistics instead of a story file")
group.add_argument("-m", "--merge", action="store_true",
help="output a merged configuration instead of a story file")
group.add_argument("-r", "--runner",
type=argparse.FileType('r'), nargs=1,
help="bundle a stand-alone game using the given runner")
pargs.add_argument("source", type=argparse.FileType('r'), nargs='*',
help="configuration files to use as input")
args = pargs.parse_args()
output = new_game()
try:
for i in args.source:
config = configparser.ConfigParser()
config.read_file(i)
i.close()
merge_data(config, output)
if not sanity_check(output):
pass # Should this say something to cap the errors?
elif args.check:
pass
elif args.stats:
stats = story_stats(output)
print("Object count by type:")
for i in stats:
print("{0:10s}: {1:3d}".format(i, stats[i]))
print("Total: {0:5d}".format(sum(stats.values())))
elif args.merge:
game2config(output).write(sys.stdout)
elif args.runner != None:
tpl = args.runner[0].read(-1)
args.runner[0].close()
place = "var game_data = null;"
text = "var game_data = " + json.dumps(output) + ";"
print(tpl.replace(place, text), end='')
else:
print(json.dumps(output), end='')
except ValueError as e:
print("Error in game data: " + str(e), file=sys.stderr)
except Exception as e:
print("Error compiling story file: " + str(e), file=sys.stderr)
| artistic-2.0 | 3,651,045,482,471,274,500 | 26.475 | 76 | 0.617683 | false |
oisdk/PyParse | ParseResult.py | 1 | 2795 | from FunctorApplicativeMonad import Functor, Applicative, Monad
from abc import ABCMeta, abstractmethod
class ParseResult(Functor, Applicative, Monad, metaclass=ABCMeta):
@abstractmethod
def fmap(self, fn) -> 'ParseResult':
return NotImplemented
@abstractmethod
def apply(self, something: 'ParseResult') -> 'ParseResult':
return NotImplemented
@abstractmethod
def bind(self, something) -> 'ParseResult':
return NotImplemented
@classmethod
def pure(cls, x) -> 'Success[A]':
return Success(x, (0,0))
@abstractmethod
def finish(self):
return NotImplemented
@abstractmethod
def __repr__(self) -> str:
return NotImplemented
@abstractmethod
def __bool__(self) -> bool:
return NotImplemented
@staticmethod
@abstractmethod
def pure(val) -> 'ParseResult':
return NotImplemented
def _locstr(self) -> str:
return "line %i, column %i" % (self._loc[0] + 1, self._loc[1] + 1)
class Success(ParseResult):
def __init__(self, value, loc) -> None:
self._loc, self._val = loc, value
def fmap(self, fn):
return Success(fn(self._val), self._loc)
def apply(self, something: ParseResult) -> ParseResult:
return something.fmap(self._val)
def bind(self, something):
return something(self._val)
@staticmethod
def pure(val):
return Success(val, (0,0))
def finish(self):
return self._val
def __bool__(self) -> bool:
return True
def __or__(lhs, _):
return lhs
def __repr__(self) -> str:
return "Success! Finished at %s, with %s" % (self._locstr(), self._val)
class Failure(ParseResult):
def __init__(self, loc, exp, rec: str, com=False):
self._loc, self._exp, self._rec, self._com = loc, exp, rec, com
def fmap(self, fn) -> 'Failure':
return self
def apply(self, something: ParseResult) -> 'Failure':
return self
def bind(self, something):
return self
def __bool__(self) -> bool:
return False
def __or__(lhs,rhs):
if lhs._com: return lhs
if rhs or rhs._com: return rhs
return Failure(lhs._loc, lhs._exp | rhs._exp, lhs._rec, False)
@staticmethod
def pure(val):
return Success(val, (0,0))
def finish(self) -> str:
expect = '\nExpecting '
if len(self._exp) == 2: expect += ' or '.join(self._exp)
elif self._exp:
e = list(self._exp)
f = ', '.join(e[:-1])
if f: expect += f + ', or '
expect += e[-1]
else: expect = ''
return "%s:\nUnexpected %s%s" % (self._locstr(), self._rec, expect)
def __repr__(self) -> str:
return self.finish()
| mit | 3,492,548,122,189,489,700 | 24.409091 | 79 | 0.572809 | false |
A-Julien/ADE-Power | parser.py | 1 | 4937 | #!/usr/bin/python2.7
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
from datetime import * # gestion des dates
import sys
utf = sys.argv[1]
gr = sys.argv[2]
#------ Definition des variables ------#
MIN_activity = 2
ical_date_start = "DTSTART:"
ical_date_end = "DTEND:"
ical_title = "SUMMARY:"
ical_location = "LOCATION:"
ical_description = "DESCRIPTION:"
#------ Ouverture des fichiers --------#
try:
soup = BeautifulSoup(open(utf), "lxml") # ouvrir le fichier ade.html
except :
print ("BeautifulSoup can't open "+utf)
try:
calendar = open("./cal-"+gr+".ical", "w") # creer et écrire dans le fichier cal.ical
except:
print ("BeautifulSoup can't open/create cal-"+gr+".ical")
try:
cours_unknown = open("/home/pi/ADE-Power/cours/cours_unknown.txt", 'r+')
with open("/home/pi/ADE-Power/cours/cours_1h.txt") as f:
cours_1h = f.read().splitlines()
with open("/home/pi/ADE-Power/cours/cours_1h30.txt") as f:
cours_1h30 = f.read().splitlines()
with open("/home/pi/ADE-Power/cours/cours_2h.txt") as f:
cours_2h = f.read().splitlines()
with open("/home/pi/ADE-Power/cours/cours_3h.txt") as f:
cours_3h = f.read().splitlines()
except:
print("can't open folders")
#--------------------------------------#
# --- Gestion des dates --- #
def jour_semaine(jour_entree): # indique le nombre de jours qu'il faut ajouter au début de la semaine
if jour_entree == "Lundi":
entier = 0
elif jour_entree == "Mardi":
entier = 1
elif jour_entree == "Mercredi":
entier = 2
elif jour_entree == "Jeudi":
entier = 3
elif jour_entree == "Vendredi":
entier = 4
else:
entier = 5
return entier
def date_debut(date_entree, jour_entree): # renvoie la date de début d'événement formatée ical
delta = jour_semaine(jour_entree)
date_entree = datetime.strptime(date_entree, '%d %b. %Y%Hh%M') + timedelta(days=delta, hours=-2)
event_date_start = date_entree.strftime('%Y%m%dT%H%M%SZ')
return event_date_start
def duree_cours(code_cours): # renvoie la durée du cours en fonction de son code
if code_cours in cours_1h :
delta = 1
elif code_cours in cours_1h30 :
delta = 1.5
elif code_cours in cours_2h :
delta = 2
elif code_cours in cours_3h :
delta = 3
elif code_cours + "\n" in cours_unknown :
print "!!!!!!!!le cours est deja inconu"
delta = 2
else :
print "Le code cours " + code_cours + " n'est pas dans une liste de cours, on le rajoute !"
cours_unknown.write(code_cours + "\n")
delta = 2
return delta
def date_fin(date_entree, code_cours, jour_entree): # renvoie la date de fin de cours en fonction du code cours
duree = duree_cours ( code_cours )
delta = jour_semaine ( jour_entree )
date_entree = datetime.strptime ( date_entree, '%d %b. %Y%Hh%M')
date_fin = date_entree + timedelta ( days=delta, hours=duree-2 )
event_date_end = date_fin.strftime ( '%Y%m%dT%H%M%SZ' )
return event_date_end
# --- Fin gestion des dates ---------------------- #
activity = soup.find_all('tr') # recherche chaque ligne du tableau
calendar.write("BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//adePower//ADETOICAL v2.1//FR\n") # introduction du fichier ical
#print activity
for i in range(MIN_activity, len(activity)):
attribut = activity[i].find_all('td') # séparation de chaque ligne du tableau
calendar.write("BEGIN:VEVENT\n") # début d'un événement ical
event_location = attribut[8].string
event_description_ID = attribut[0].string
event_description_group = attribut[6].string
event_date_start = date_debut(attribut[1].string+attribut[3].string,
attribut[2].string)
event_date_end = date_fin(attribut[1].string+attribut[3].string,
event_description_ID, attribut[2].string)
try:
event_description_prof = attribut[7].string
except:
event_description_prof = None
try:
event_title = attribut[5].string
except:
event_title = None
calendar.write( ical_date_start + event_date_start + '\n')
calendar.write( ical_date_end + event_date_end + '\n')
try:
calendar.write( ical_location + event_location + '\n')
except:
calendar.write( ical_location + 'Pas de salle' + '\n')
calendar.write( ical_description + event_description_ID + '\\n')
if event_description_prof!=None:
calendar.write( "Prof : " + event_description_prof + '\\n')
calendar.write( "Groupe : " + event_description_group + '\\n')
calendar.write( "Exporté le : " + str(datetime.today()) + '\n')
try:
calendar.write( ical_title + event_title + '\n')
except:
calendar.write( ical_title + 'Sans titre' + '\n')
calendar.write("END:VEVENT\n")
calendar.write("END:VCALENDAR")
print ("ICAL file correctly exported !")
print ("parsing " + gr + " ok")
# ---- Fermeture des fichiers --- #
calendar.close()
cours_unknown.close()
# -------------------------------
| apache-2.0 | 6,176,875,498,330,314,000 | 27.468208 | 119 | 0.635736 | false |
marclanepitt/ot | blogs/views.py | 1 | 1847 | from django.shortcuts import render,get_object_or_404, HttpResponseRedirect
from .models import Article
from .forms import BlogForm
def index(request):
latest_article_list = Article.objects.order_by('-pub_date')[:20]
context = {'latest_article_list': latest_article_list}
return render(request, 'index.html',context)
def list_index(request):
latest_article_list = Article.objects.order_by('-pub_date')[:20]
context = {'latest_article_list': latest_article_list}
return render(request, 'list_index.html', context)
def blog_index(request):
latest_article_list = Article.objects.order_by('-pub_date')[:20]
context = {'latest_article_list': latest_article_list}
return render(request, 'blog_index.html', context)
def countdown_index(request):
latest_article_list = Article.objects.order_by('-pub_date')[:20]
context = {'latest_article_list': latest_article_list}
return render(request, 'countdown_index.html', context)
def detail(request, slug):
article = get_object_or_404(Article, slug=slug)
return render(request, 'blog.html', {'article': article})
def search(request):
latest_article_list = Article.objects.order_by('-pub_date')[:20]
context = {'latest_article_list': latest_article_list}
return render(request, 'search.html',context)
def submit(request):
return render(request, 'submit.html')
def submit_blog(request):
if request.method == 'POST':
form = BlogForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('submit_success.html')
else:
form = BlogForm()
return render(request, 'submit_blog.html', {'form': form})
def submit_list(request):
return render(request, 'submit_list.html')
def submit_countdown(request):
return render(request, 'submit_countdown.html')
| mit | -6,052,535,252,031,581,000 | 32.581818 | 75 | 0.691933 | false |
m0she/template-relocation | relocation/processors.py | 1 | 3698 | import copy, hashlib, logging
from bunch import Bunch
from django.conf import settings
from django.core.cache import DEFAULT_CACHE_ALIAS
from django.core.urlresolvers import reverse
from .cache import cached_data
from .utils import buf_to_unicode
CACHE_NAME=getattr(settings, 'RELOCATION_CACHE', DEFAULT_CACHE_ALIAS)
def relocation_cache_get_or_set(key_prefix, data, func):
with cached_data('%s_%s' % (key_prefix, hashlib.md5(data).hexdigest()), backend=CACHE_NAME) as ctx:
if not ctx.found:
ctx.response = func(data)
return ctx.response
def external_http_reference_with_data_hash(destination_format, reverse_view):
def reference_builder(template_name, section_name, section_data):
return destination_format % reverse(reverse_view, kwargs=dict(
template_name=template_name,
section=section_name,
data_hash=hashlib.md5(buf_to_unicode(section_data)).hexdigest(),
))
return reference_builder
def external_http_reference(destination_format, reverse_view):
return lambda template_name, section_name, section_data: (
destination_format % reverse(reverse_view, kwargs=dict(template_name=template_name, section=section_name)))
EXTERNIFY_VIEW = getattr(settings, 'RELOCATION_EXTERNIFY_VIEW', 'externified_view')
EXTERNIFY_SECTION_RULES = getattr(settings, 'RELOCATION_EXTERNIFY_RULES', None) or Bunch(
javascript = Bunch(
reference = external_http_reference_with_data_hash(
destination_format = '<script type="text/javascript" src="%s"></script>',
reverse_view = EXTERNIFY_VIEW,
),
mimetype = 'application/javascript',
),
css = Bunch(
reference = external_http_reference_with_data_hash(
destination_format = '<link rel="stylesheet" type="text/css" href="%s"/>',
reverse_view = EXTERNIFY_VIEW,
),
mimetype = 'text/css',
),
)
def externify(template_name, main, sections, rules=EXTERNIFY_SECTION_RULES):
for section_name, ruledata in rules.items():
if section_name not in sections:
continue
new_section = copy.deepcopy(sections[section_name])
sections[section_name].clear()
sections[section_name].append(ruledata.reference(template_name, section_name, new_section))
sections[section_name] = new_section
scss_compiler = None
def get_scss_compiler():
global scss_compiler
if scss_compiler:
return scss_compiler
import scss
# Use our own logger instead of their default
scss.log = logging.getLogger('reloc.scss')
scss_compiler = scss.Scss()
return scss_compiler
def scss(template_name, main, sections):
scss_sections = ('css',)
for section in scss_sections:
if section not in sections:
continue
scssed = relocation_cache_get_or_set('scss', buf_to_unicode(sections[section]), lambda data: get_scss_compiler().compile(data))
sections[section].clear()
sections[section].append(scssed)
def coffee(template_name, main, sections):
from .coffeeutils import coffee as compile_coffeescript
if not all(section in sections for section in ('coffee', 'javascript')):
return
sections['javascript'].append(buf_to_unicode(
relocation_cache_get_or_set('coffee', part, compile_coffeescript) for part in sections['coffee']))
def minify_js(template_name, main, sections):
import slimit
section = 'javascript'
if section not in sections:
return
minified = relocation_cache_get_or_set('minify', buf_to_unicode(sections[section]), slimit.minify)
sections[section].clear()
sections[section].append(minified)
| bsd-3-clause | 3,781,865,000,782,170,600 | 38.340426 | 135 | 0.685776 | false |
Forage/Gramps | gramps/gen/filters/rules/note/_allnotes.py | 1 | 1602 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .._everything import Everything
#-------------------------------------------------------------------------
#
# Everyone
#
#-------------------------------------------------------------------------
class AllNotes(Everything):
"""Matches every note"""
name = _('Every note')
description = _('Matches every note in the database')
| gpl-2.0 | 797,620,912,098,693,600 | 33.085106 | 75 | 0.523096 | false |
bbondy/brianbondy.gae | libs/markdown/extensions/headerid.py | 1 | 6539 | #!/usr/bin/python
"""
HeaderID Extension for Python-Markdown
======================================
Adds ability to set HTML IDs for headers.
Basic usage:
>>> import markdown
>>> text = "# Some Header # {#some_id}"
>>> md = markdown.markdown(text, ['headerid'])
>>> md
u'<h1 id="some_id">Some Header</h1>'
All header IDs are unique:
>>> text = '''
... #Header
... #Another Header {#header}
... #Third Header {#header}'''
>>> md = markdown.markdown(text, ['headerid'])
>>> md
u'<h1 id="header">Header</h1>\\n<h1 id="header_1">Another Header</h1>\\n<h1 id="header_2">Third Header</h1>'
To fit within a html template's hierarchy, set the header base level:
>>> text = '''
... #Some Header
... ## Next Level'''
>>> md = markdown.markdown(text, ['headerid(level=3)'])
>>> md
u'<h3 id="some_header">Some Header</h3>\\n<h4 id="next_level">Next Level</h4>'
Turn off auto generated IDs:
>>> text = '''
... # Some Header
... # Header with ID # { #foo }'''
>>> md = markdown.markdown(text, ['headerid(forceid=False)'])
>>> md
u'<h1>Some Header</h1>\\n<h1 id="foo">Header with ID</h1>'
Use with MetaData extension:
>>> text = '''header_level: 2
... header_forceid: Off
...
... # A Header'''
>>> md = markdown.markdown(text, ['headerid', 'meta'])
>>> md
u'<h2>A Header</h2>'
Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/).
Project website: <http://www.freewisdom.org/project/python-markdown/HeaderId>
Contact: [email protected]
License: BSD (see ../docs/LICENSE for details)
Dependencies:
* [Python 2.3+](http://python.org)
* [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/)
"""
import markdown
from markdown import etree
import re
from string import ascii_lowercase, digits, punctuation
ID_CHARS = ascii_lowercase + digits + '-_'
IDCOUNT_RE = re.compile(r'^(.*)_([0-9]+)$')
class HeaderIdProcessor(markdown.blockprocessors.BlockProcessor):
""" Replacement BlockProcessor for Header IDs. """
# Detect a header at start of any line in block
RE = re.compile(r"""(^|\n)
(?P<level>\#{1,6}) # group('level') = string of hashes
(?P<header>.*?) # group('header') = Header text
\#* # optional closing hashes
(?:[ \t]*\{[ \t]*\#(?P<id>[-_:a-zA-Z0-9]+)[ \t]*\})?
(\n|$) # ^^ group('id') = id attribute
""",
re.VERBOSE)
IDs = []
def test(self, parent, block):
return bool(self.RE.search(block))
def run(self, parent, blocks):
block = blocks.pop(0)
m = self.RE.search(block)
if m:
before = block[:m.start()] # All lines before header
after = block[m.end():] # All lines after header
if before:
# As the header was not the first line of the block and the
# lines before the header must be parsed first,
# recursively parse this lines as a block.
self.parser.parseBlocks(parent, [before])
# Create header using named groups from RE
start_level, force_id = self._get_meta()
level = len(m.group('level')) + start_level
if level > 6:
level = 6
h = markdown.etree.SubElement(parent, 'h%d' % level)
h.text = m.group('header').strip()
if m.group('id'):
h.set('id', self._unique_id(m.group('id')))
elif force_id:
h.set('id', self._create_id(m.group('header').strip()))
if after:
# Insert remaining lines as first block for future parsing.
blocks.insert(0, after)
else:
# This should never happen, but just in case...
message(CRITICAL, "We've got a problem header!")
def _get_meta(self):
""" Return meta data suported by this ext as a tuple """
level = int(self.config['level'][0]) - 1
force = self._str2bool(self.config['forceid'][0])
if hasattr(self.md, 'Meta'):
if self.md.Meta.has_key('header_level'):
level = int(self.md.Meta['header_level'][0]) - 1
if self.md.Meta.has_key('header_forceid'):
force = self._str2bool(self.md.Meta['header_forceid'][0])
return level, force
def _str2bool(self, s, default=False):
""" Convert a string to a booleen value. """
s = str(s)
if s.lower() in ['0', 'f', 'false', 'off', 'no', 'n']:
return False
elif s.lower() in ['1', 't', 'true', 'on', 'yes', 'y']:
return True
return default
def _unique_id(self, id):
""" Ensure ID is unique. Append '_1', '_2'... if not """
while id in self.IDs:
m = IDCOUNT_RE.match(id)
if m:
id = '%s_%d'% (m.group(1), int(m.group(2))+1)
else:
id = '%s_%d'% (id, 1)
self.IDs.append(id)
return id
def _create_id(self, header):
""" Return ID from Header text. """
h = ''
for c in header.lower().replace(' ', '_'):
if c in ID_CHARS:
h += c
elif c not in punctuation:
h += '+'
return self._unique_id(h)
class HeaderIdExtension (markdown.Extension):
def __init__(self, configs):
# set defaults
self.config = {
'level' : ['1', 'Base level for headers.'],
'forceid' : ['True', 'Force all headers to have an id.']
}
for key, value in configs:
self.setConfig(key, value)
def extendMarkdown(self, md, md_globals):
md.registerExtension(self)
self.processor = HeaderIdProcessor(md.parser)
self.processor.md = md
self.processor.config = self.config
# Replace existing hasheader in place.
md.parser.blockprocessors['hashheader'] = self.processor
def reset(self):
self.processor.IDs = []
def makeExtension(configs=None):
return HeaderIdExtension(configs=configs)
if __name__ == "__main__":
import doctest
doctest.testmod()
| mit | 2,910,823,453,277,771,300 | 31.533333 | 112 | 0.513993 | false |
gotpredictions/vue-todo | server/server/settings.py | 1 | 3202 | """
Django settings for server project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&d1&i8-+jj)z8u_60vv2=&fx&5_m#2wm!bldp@vgo&)_mk1!=a'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'todolist',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'server.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'server.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = '/tmp' | apache-2.0 | 2,283,973,397,942,834,200 | 25.04065 | 91 | 0.686758 | false |
bnbowman/HlaTools | src/pbhla/alleles/trim.py | 1 | 2639 | #! /usr/bin/env python
import logging
from operator import itemgetter
from pbcore.io.FastqIO import FastqWriter, FastqRecord
from pbcore.io.FastaIO import FastaWriter, FastaRecord
from pbhla.fasta.utils import write_fasta
from pbhla.filenames import get_file_type
from pbhla.utils import check_output_file
from pbhla.sequences.utils import read_sequences
log = logging.getLogger()
def trim_alleles( input_file, output_file=None, trim=0 ):
"""Pick the top 2 Amplicon Analysis consensus seqs per group from a Fasta"""
# If no trim or output file is specified, we can skip this module
if trim == 0 and output_file is None:
log.info('No trimming necessary for "%s", skipping...' % input_file)
return input_file
# Set the output file if not specified
output_file = output_file or _get_output_file( input_file )
output_type = get_file_type( output_file )
# Read the input sequences and trim each record
sequences = read_sequences( input_file )
log.info('Trimming sequences by %s bp from each end' % trim)
trimmed = _trim_sequences( sequences, trim )
log.info('Writing the trimmed sequences out to %s' % output_file)
_write_output( trimmed, output_file, output_type )
return output_file
def _trim_sequences( records, trim ):
"""Trim X bases from each end of each sequence"""
trimmed = []
for record in records:
if isinstance(record, FastaRecord):
trimmed_record = FastaRecord( record.name, record.sequence[trim:-trim])
elif isinstance(record, FastqRecord):
trimmed_record = FastqRecord( record.name, record.sequence[trim:-trim], record.quality[trim:-trim])
else:
raise TypeError("Only FastaRecord and FastqRecords support, not '%s'" % type(record))
trimmed.append( trimmed_record )
return trimmed
def _write_output( records, output_file, output_type ):
"""Write the records out to file"""
if output_type == 'fasta':
write_fasta( records, output_file )
else:
with FastqWriter( output_file ) as writer:
for record in records:
writer.writeRecord( record )
check_output_file( output_file )
def _get_output_file( input_file ):
basename = '.'.join( input_file.split('.')[:-1] )
file_type = get_file_type( input_file )
return '%s.trimmed.%s' % (basename, file_type)
if __name__ == '__main__':
import sys
logging.basicConfig( level=logging.INFO )
input_file = sys.argv[1]
output_file = sys.argv[2]
trim = int(sys.argv[3])
trim_alleles( input_file, output_file, trim )
| bsd-3-clause | 8,150,863,833,012,426,000 | 35.150685 | 111 | 0.665404 | false |
edgedb/edgedb | edb/schema/expr.py | 1 | 13042 | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
from typing import *
import copy
import uuid
from edb.common import checked
from edb.common import struct
from edb.edgeql import ast as qlast_
from edb.edgeql import codegen as qlcodegen
from edb.edgeql import compiler as qlcompiler
from edb.edgeql import parser as qlparser
from edb.edgeql import qltypes
from . import abc as s_abc
from . import objects as so
if TYPE_CHECKING:
from edb.schema import schema as s_schema
from edb.schema import types as s_types
from edb.ir import ast as irast_
class Expression(struct.MixedRTStruct, so.ObjectContainer, s_abc.Expression):
text = struct.Field(str, frozen=True)
# mypy wants an argument to the ObjectSet generic, but
# that wouldn't work for struct.Field, since subscripted
# generics are not types.
refs = struct.Field(
so.ObjectSet, # type: ignore
coerce=True,
default=None,
frozen=True,
)
def __init__(
self,
*args: Any,
_qlast: Optional[qlast_.Base] = None,
_irast: Optional[irast_.Command] = None,
**kwargs: Any
) -> None:
super().__init__(*args, **kwargs)
self._qlast = _qlast
self._irast = _irast
def __getstate__(self) -> Dict[str, Any]:
return {
'text': self.text,
'refs': self.refs,
'_qlast': None,
'_irast': None,
}
@property
def qlast(self) -> qlast_.Base:
if self._qlast is None:
self._qlast = qlparser.parse_fragment(self.text)
return self._qlast
@property
def irast(self) -> Optional[irast_.Command]:
return self._irast
def is_compiled(self) -> bool:
return self.refs is not None
@classmethod
def compare_values(cls: Type[Expression],
ours: Expression,
theirs: Expression,
*,
our_schema: s_schema.Schema,
their_schema: s_schema.Schema,
context: so.ComparisonContext,
compcoef: float) -> float:
if not ours and not theirs:
return 1.0
elif not ours or not theirs:
return compcoef
elif ours.text == theirs.text:
return 1.0
else:
return compcoef
@classmethod
def from_ast(
cls: Type[Expression],
qltree: qlast_.Base,
schema: s_schema.Schema,
modaliases: Optional[Mapping[Optional[str], str]] = None,
localnames: AbstractSet[str] = frozenset(),
*,
as_fragment: bool = False,
orig_text: Optional[str] = None,
) -> Expression:
if modaliases is None:
modaliases = {}
if orig_text is None:
orig_text = qlcodegen.generate_source(qltree, pretty=False)
if not as_fragment:
qlcompiler.normalize(
qltree,
schema=schema,
modaliases=modaliases,
localnames=localnames
)
norm_text = qlcodegen.generate_source(qltree, pretty=False)
return cls(
text=norm_text,
_qlast=qltree,
)
@classmethod
def not_compiled(cls: Type[Expression], expr: Expression) -> Expression:
return Expression(text=expr.text)
@classmethod
def compiled(
cls: Type[Expression],
expr: Expression,
schema: s_schema.Schema,
*,
options: Optional[qlcompiler.CompilerOptions] = None,
as_fragment: bool = False,
) -> Expression:
from edb.ir import ast as irast_
if as_fragment:
ir: irast_.Command = qlcompiler.compile_ast_fragment_to_ir(
expr.qlast,
schema=schema,
options=options,
)
else:
ir = qlcompiler.compile_ast_to_ir(
expr.qlast,
schema=schema,
options=options,
)
assert isinstance(ir, irast_.Statement)
return cls(
text=expr.text,
refs=so.ObjectSet.create(schema, ir.schema_refs),
_qlast=expr.qlast,
_irast=ir,
)
@classmethod
def from_ir(cls: Type[Expression],
expr: Expression,
ir: irast_.Statement,
schema: s_schema.Schema) -> Expression:
return cls(
text=expr.text,
refs=so.ObjectSet.create(schema, ir.schema_refs),
_qlast=expr.qlast,
_irast=ir,
)
@classmethod
def from_expr(cls: Type[Expression],
expr: Expression,
schema: s_schema.Schema) -> Expression:
return cls(
text=expr.text,
refs=(
so.ObjectSet.create(schema, expr.refs.objects(schema))
if expr.refs is not None else None
),
_qlast=expr._qlast,
_irast=expr._irast,
)
def as_shell(self, schema: s_schema.Schema) -> ExpressionShell:
return ExpressionShell(
text=self.text,
refs=(
r.as_shell(schema) for r in self.refs.objects(schema)
) if self.refs is not None else None,
_qlast=self._qlast,
)
def schema_reduce(
self,
) -> Tuple[
str,
Tuple[
str,
Optional[Union[Tuple[type, ...], type]],
Tuple[uuid.UUID, ...],
Tuple[Tuple[str, Any], ...],
],
]:
assert self.refs is not None, 'expected expression to be compiled'
return (
self.text,
self.refs.schema_reduce(),
)
@classmethod
def schema_restore(
cls,
data: Tuple[
str,
Tuple[
str,
Optional[Union[Tuple[type, ...], type]],
Tuple[uuid.UUID, ...],
Tuple[Tuple[str, Any], ...],
],
],
) -> Expression:
text, refs_data = data
return Expression(
text=text,
refs=so.ObjectCollection.schema_restore(refs_data),
)
@classmethod
def schema_refs_from_data(
cls,
data: Tuple[
str,
Tuple[
str,
Optional[Union[Tuple[type, ...], type]],
Tuple[uuid.UUID, ...],
Tuple[Tuple[str, Any], ...],
],
],
) -> FrozenSet[uuid.UUID]:
return so.ObjectCollection.schema_refs_from_data(data[1])
@property
def ir_statement(self) -> irast_.Statement:
"""Assert this expr is a compiled EdgeQL statement and return its IR"""
from edb.ir import ast as irast_
if not self.is_compiled():
raise AssertionError('expected a compiled expression')
ir = self.irast
if not isinstance(ir, irast_.Statement):
raise AssertionError(
'expected the result of an expression to be a Statement')
return ir
@property
def stype(self) -> s_types.Type:
return self.ir_statement.stype
@property
def cardinality(self) -> qltypes.Cardinality:
return self.ir_statement.cardinality
@property
def schema(self) -> s_schema.Schema:
return self.ir_statement.schema
class ExpressionShell(so.Shell):
def __init__(
self,
*,
text: str,
refs: Optional[Iterable[so.ObjectShell]],
_qlast: Optional[qlast_.Base] = None,
_irast: Optional[irast_.Command] = None,
) -> None:
self.text = text
self.refs = tuple(refs) if refs is not None else None
self._qlast = _qlast
self._irast = _irast
def resolve(self, schema: s_schema.Schema) -> Expression:
return Expression(
text=self.text,
refs=so.ObjectSet.create(
schema,
(s.resolve(schema) for s in self.refs),
) if self.refs is not None else None,
_qlast=self._qlast,
_irast=self._irast,
)
@property
def qlast(self) -> qlast_.Base:
if self._qlast is None:
self._qlast = qlparser.parse_fragment(self.text)
return self._qlast
def __repr__(self) -> str:
if self.refs is None:
refs = 'N/A'
else:
refs = ', '.join(repr(obj) for obj in self.refs)
return f'<ExpressionShell {self.text} refs=({refs})>'
class ExpressionList(checked.FrozenCheckedList[Expression]):
@staticmethod
def merge_values(target: so.Object,
sources: Sequence[so.Object],
field_name: str,
*,
ignore_local: bool = False,
schema: s_schema.Schema) -> Any:
if not ignore_local:
result = target.get_explicit_field_value(schema, field_name, None)
else:
result = None
for source in sources:
theirs = source.get_explicit_field_value(schema, field_name, None)
if theirs:
if result is None:
result = theirs[:]
else:
result.extend(theirs)
return result
@classmethod
def compare_values(cls: Type[ExpressionList],
ours: Optional[ExpressionList],
theirs: Optional[ExpressionList],
*,
our_schema: s_schema.Schema,
their_schema: s_schema.Schema,
context: so.ComparisonContext,
compcoef: float) -> float:
"""See the comment in Object.compare_values"""
if not ours and not theirs:
basecoef = 1.0
elif (not ours or not theirs) or (len(ours) != len(theirs)):
basecoef = 0.2
else:
similarity = []
for expr1, expr2 in zip(ours, theirs):
similarity.append(
Expression.compare_values(
expr1, expr2, our_schema=our_schema,
their_schema=their_schema, context=context,
compcoef=compcoef))
basecoef = sum(similarity) / len(similarity)
return basecoef + (1 - basecoef) * compcoef
def imprint_expr_context(
qltree: qlast_.Base,
modaliases: Mapping[Optional[str], str],
) -> qlast_.Base:
# Imprint current module aliases as explicit
# alias declarations in the expression.
if (isinstance(qltree, qlast_.BaseConstant)
or qltree is None
or (isinstance(qltree, qlast_.Set)
and not qltree.elements)
or (isinstance(qltree, qlast_.Array)
and all(isinstance(el, qlast_.BaseConstant)
for el in qltree.elements))):
# Leave constants alone.
return qltree
if not isinstance(qltree, qlast_.Command):
qltree = qlast_.SelectQuery(result=qltree, implicit=True)
else:
qltree = copy.copy(qltree)
qltree.aliases = list(qltree.aliases)
existing_aliases: Dict[Optional[str], str] = {}
for alias in qltree.aliases:
if isinstance(alias, qlast_.ModuleAliasDecl):
existing_aliases[alias.alias] = alias.module
aliases_to_add = set(modaliases) - set(existing_aliases)
for alias_name in aliases_to_add:
qltree.aliases.append(
qlast_.ModuleAliasDecl(
alias=alias_name,
module=modaliases[alias_name],
)
)
return qltree
def get_expr_referrers(schema: s_schema.Schema,
obj: so.Object) -> Dict[so.Object, List[str]]:
"""Return schema referrers with refs in expressions."""
refs: Dict[Tuple[Type[so.Object], str], FrozenSet[so.Object]] = (
schema.get_referrers_ex(obj))
result: Dict[so.Object, List[str]] = {}
for (mcls, fn), referrers in refs.items():
field = mcls.get_field(fn)
if issubclass(field.type, (Expression, ExpressionList)):
for ref in referrers:
result.setdefault(ref, []).append(fn)
return result
| apache-2.0 | -3,343,619,543,085,199,000 | 28.981609 | 79 | 0.547079 | false |
nqnmovil/nqnm_e16 | encuesta/settings.py | 1 | 3613 | """
Django settings for encuesta project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3onqk62p0$kvns3me&%ty&^ty8o*e5c1c1%e=9d2^6v&eox49f'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'appencuesta',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'encuesta.urls'
CRISPY_TEMPLATE_PACK = 'bootstrap3'
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates') #agregado basado en rango
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_PATH,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'encuesta.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'nqnmovil_encuesta2016',
'USER': os.getenv('nqnmovil_encuesta16_dbusr', 'usuario'),
'PASSWORD':os.getenv('nqnmovil_encuesta16_dbpass', 'clave'),
'HOST':'localhost',
'PORT':'',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'es-AR'
TIME_ZONE = 'America/Argentina/Buenos_Aires'
DATE_INPUT_FORMATS = ('%d-%m-%Y')
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
LOGIN_REDIRECT_URL = '/appencuesta/encuesta/'
LOGIN_URL = '/appencuesta/login/'
| apache-2.0 | 7,439,655,797,284,314,000 | 26.165414 | 91 | 0.691946 | false |
JASchilz/RoverMUD | interpreter/interpreter.py | 1 | 2078 | #------------------------------------------------------------------------------
# interpreter/interpreter.py
# Copyright 2011 Joseph Schilz
# Licensed under Apache v2
#------------------------------------------------------------------------------
articles = [" a ", " the "]
def verb(command):
# A function to isolate the verb in a command.
this_verb = ""
the_rest = ""
first_space = command.find(" ")
# If this_input contains a space, the verb is everything before the
# first space.
if first_space > 0:
this_verb = command[0:first_space]
the_rest = command[first_space + 1:len(command)]
# If it doesn't contain a space, the whole thing is the verb.
else:
this_verb = command
# We handle simple verb aliases at this level...
if command[0] == "'":
this_verb = "say"
the_rest = command[1:len(command)]
if command == "north" or command == "n":
this_verb = "go"
the_rest = "north"
elif command == "south" or command == "s":
this_verb = "go"
the_rest = "south"
elif command == "east" or command == "e":
this_verb = "go"
the_rest = "east"
elif command == "west" or command == "w":
this_verb = "go"
the_rest = "west"
elif command == "up" or command == "u":
this_verb = "go"
the_rest = "up"
elif command == "down" or command == "d":
this_verb = "go"
the_rest = "down"
if this_verb == "l":
this_verb = "look"
elif this_verb == "i":
this_verb = "inv"
elif this_verb == "h":
this_verb = "health"
return this_verb, the_rest
def interpret(the_verb, the_rest, transitivity=1):
the_rest = " " + the_rest.lower() + " "
for article in articles:
the_rest = the_rest.replace(article, '')
if transitivity == 1:
the_rest = the_rest.strip().split()
if len(the_rest) > 0:
# This might not be stable.
return [the_rest.pop(), the_rest]
else:
return False
| apache-2.0 | 7,014,852,203,973,416,000 | 26.342105 | 79 | 0.498075 | false |
Jordan-Zhu/RoboVision | unsorted/merge_lines_py.py | 1 | 3796 | import math
import numpy as np
from itertools import combinations, chain
from collections import Counter
def compare(s, t):
return Counter(s) == Counter(t)
def math_stuff(x1, y1, x2, y2):
slope = float((y2 - y1) / (x2 - x1) if ((x2 - x1) != 0) else math.inf)
line_len = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
alpha = math.degrees(math.atan(-slope))
return slope, line_len, alpha
def relevant_lines(i, pairs, lines):
pt1 = pairs[i][0]
pt2 = pairs[i][1]
line1 = lines[pt1]
line2 = lines[pt2]
alph1 = line1[6]
alph2 = line2[6]
temp1 = [line1[8], line1[9]]
temp2 = [line2[8], line2[9]]
return pt1, pt2, alph1, alph2, temp1, temp2
def merge_listpoints(listpt, pt1, pt2, px1, px2):
lp1 = listpt[pt1]
lp2 = listpt[pt2]
startpt1 = np.where(lp1 == px1)[0]
startpt2 = np.where(lp1 == px2)[0]
startpt3 = np.where(lp2 == px1)[0]
startpt4 = np.where(lp2 == px2)[0]
if not startpt1 and startpt1.shape[0] < 1:
line_start = lp2
line_end = lp1
if startpt3 > 0:
line_start = line_start[::-1]
if startpt2 == 0:
line_end = line_end[::-1]
else:
line_start = lp1
line_end = lp2
if startpt1 > 0:
line_start = line_start[::-1]
if startpt4 == 0:
line_end = line_end[::-1]
# print(listpt[max(pt1, pt2)])
# listpt = np.delete(listpt, max(pt1, pt2), axis=0)
# listpt = np.delete(listpt, min(pt1, pt2), axis=0)
del listpt[max(pt1, pt2)]
del listpt[min(pt1, pt2)]
merged = np.r_[line_start[0:-1], line_end]
# print('merged', merged)
listpt.append(merged)
return listpt
def merge_lines(lines, listpt, thresh, imgsize):
listpt = list(listpt)
out = [[n] for n in range(0, lines.shape[0])]
unique_pts = np.sort(np.unique(lines[:, 8:10]))
for index, ptx in enumerate(unique_pts):
pairs = list(combinations(list(np.where(lines == ptx)[0]), 2))
if not pairs:
continue
for i in range(len(pairs)):
pt1, pt2, alph1, alph2, temp1, temp2 = relevant_lines(i, pairs, lines)
# Check that the lines are within the threshold and not coincident
if abs(alph1 - alph2) > thresh or compare(temp1, temp2):
continue
lind1, lind2 = np.sort([int(i) for i in list(filter(lambda e: e not in [ptx], chain(temp1 + temp2)))])
# print('linear indices: ', lind1, lind2)
x1, y1 = np.squeeze(np.unravel_index([lind1], imgsize, order='C'))
x2, y2 = np.squeeze(np.unravel_index([lind2], imgsize, order='C'))
# print('x1', x1, 'y1', y1, 'x2', x2, 'y2', y2)
slope, line_len, alpha = math_stuff(x1, y1, x2, y2)
# Intersection point is in the middle of the new line
if min(alph1, alph2) <= alpha <= max(alph1, alph2):
lines = np.delete(lines, max(pt1, pt2), axis=0)
lines = np.delete(lines, min(pt1, pt2), axis=0)
val1 = out[pt1]
val2 = out[pt2]
del out[max(pt1, pt2)]
del out[min(pt1, pt2)]
# Update both lists to reflect the addition of the merged line.
lines = np.append(lines, [[int(x1), int(y1), int(x2), int(y2), line_len, slope, alpha, 0, lind1, lind2]], axis=0)
out.append([val1, val2])
listpt = merge_listpoints(listpt, pt1, pt2, lind1, lind2)
# Merged lines, so don't check the other pairs
break
else:
continue
return lines, np.array(listpt), np.array(out)
| gpl-3.0 | 3,452,265,371,909,360,600 | 32.198198 | 129 | 0.532929 | false |
twz915/django | tests/auth_tests/test_views.py | 1 | 50966 | import datetime
import itertools
import os
import re
from importlib import import_module
from urllib.parse import ParseResult, urlparse
from django.apps import apps
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django.contrib.auth import REDIRECT_FIELD_NAME, SESSION_KEY
from django.contrib.auth.forms import (
AuthenticationForm, PasswordChangeForm, SetPasswordForm,
)
from django.contrib.auth.models import User
from django.contrib.auth.views import (
INTERNAL_RESET_SESSION_TOKEN, LoginView, logout_then_login,
redirect_to_login,
)
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.sites.requests import RequestSite
from django.core import mail
from django.db import connection
from django.http import HttpRequest, QueryDict
from django.middleware.csrf import CsrfViewMiddleware, get_token
from django.test import Client, TestCase, override_settings
from django.test.utils import patch_logger
from django.urls import NoReverseMatch, reverse, reverse_lazy
from django.utils.deprecation import RemovedInDjango21Warning
from django.utils.encoding import force_text
from django.utils.http import urlquote
from django.utils.translation import LANGUAGE_SESSION_KEY
from .client import PasswordResetConfirmClient
from .models import CustomUser, UUIDUser
from .settings import AUTH_TEMPLATES
@override_settings(
LANGUAGES=[('en', 'English')],
LANGUAGE_CODE='en',
TEMPLATES=AUTH_TEMPLATES,
ROOT_URLCONF='auth_tests.urls',
)
class AuthViewsTestCase(TestCase):
"""
Helper base class for all the follow test cases.
"""
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create_user(username='testclient', password='password', email='[email protected]')
cls.u3 = User.objects.create_user(username='staff', password='password', email='[email protected]')
def login(self, username='testclient', password='password'):
response = self.client.post('/login/', {
'username': username,
'password': password,
})
self.assertIn(SESSION_KEY, self.client.session)
return response
def logout(self):
response = self.client.get('/admin/logout/')
self.assertEqual(response.status_code, 200)
self.assertNotIn(SESSION_KEY, self.client.session)
def assertFormError(self, response, error):
"""Assert that error is found in response.context['form'] errors"""
form_errors = list(itertools.chain(*response.context['form'].errors.values()))
self.assertIn(force_text(error), form_errors)
def assertURLEqual(self, url, expected, parse_qs=False):
"""
Given two URLs, make sure all their components (the ones given by
urlparse) are equal, only comparing components that are present in both
URLs.
If `parse_qs` is True, then the querystrings are parsed with QueryDict.
This is useful if you don't want the order of parameters to matter.
Otherwise, the query strings are compared as-is.
"""
fields = ParseResult._fields
for attr, x, y in zip(fields, urlparse(url), urlparse(expected)):
if parse_qs and attr == 'query':
x, y = QueryDict(x), QueryDict(y)
if x and y and x != y:
self.fail("%r != %r (%s doesn't match)" % (url, expected, attr))
@override_settings(ROOT_URLCONF='django.contrib.auth.urls')
class AuthViewNamedURLTests(AuthViewsTestCase):
def test_named_urls(self):
"Named URLs should be reversible"
expected_named_urls = [
('login', [], {}),
('logout', [], {}),
('password_change', [], {}),
('password_change_done', [], {}),
('password_reset', [], {}),
('password_reset_done', [], {}),
('password_reset_confirm', [], {
'uidb64': 'aaaaaaa',
'token': '1111-aaaaa',
}),
('password_reset_complete', [], {}),
]
for name, args, kwargs in expected_named_urls:
try:
reverse(name, args=args, kwargs=kwargs)
except NoReverseMatch:
self.fail("Reversal of url named '%s' failed with NoReverseMatch" % name)
class PasswordResetTest(AuthViewsTestCase):
def setUp(self):
self.client = PasswordResetConfirmClient()
def test_email_not_found(self):
"""If the provided email is not registered, don't raise any error but
also don't send any email."""
response = self.client.get('/password_reset/')
self.assertEqual(response.status_code, 200)
response = self.client.post('/password_reset/', {'email': '[email protected]'})
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 0)
def test_email_found(self):
"Email is sent if a valid email address is provided for password reset"
response = self.client.post('/password_reset/', {'email': '[email protected]'})
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertIn("http://", mail.outbox[0].body)
self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
# optional multipart text/html email has been added. Make sure original,
# default functionality is 100% the same
self.assertFalse(mail.outbox[0].message().is_multipart())
def test_extra_email_context(self):
"""
extra_email_context should be available in the email template context.
"""
response = self.client.post(
'/password_reset_extra_email_context/',
{'email': '[email protected]'},
)
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertIn('Email email context: "Hello!"', mail.outbox[0].body)
def test_html_mail_template(self):
"""
A multipart email with text/plain and text/html is sent
if the html_email_template parameter is passed to the view
"""
response = self.client.post('/password_reset/html_email_template/', {'email': '[email protected]'})
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0].message()
self.assertEqual(len(message.get_payload()), 2)
self.assertTrue(message.is_multipart())
self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
self.assertNotIn('<html>', message.get_payload(0).get_payload())
self.assertIn('<html>', message.get_payload(1).get_payload())
def test_email_found_custom_from(self):
"Email is sent if a valid email address is provided for password reset when a custom from_email is provided."
response = self.client.post('/password_reset_from_email/', {'email': '[email protected]'})
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual("[email protected]", mail.outbox[0].from_email)
# Skip any 500 handler action (like sending more mail...)
@override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True)
def test_poisoned_http_host(self):
"Poisoned HTTP_HOST headers can't be used for reset emails"
# This attack is based on the way browsers handle URLs. The colon
# should be used to separate the port, but if the URL contains an @,
# the colon is interpreted as part of a username for login purposes,
# making 'evil.com' the request domain. Since HTTP_HOST is used to
# produce a meaningful reset URL, we need to be certain that the
# HTTP_HOST header isn't poisoned. This is done as a check when get_host()
# is invoked, but we check here as a practical consequence.
with patch_logger('django.security.DisallowedHost', 'error') as logger_calls:
response = self.client.post(
'/password_reset/',
{'email': '[email protected]'},
HTTP_HOST='www.example:[email protected]'
)
self.assertEqual(response.status_code, 400)
self.assertEqual(len(mail.outbox), 0)
self.assertEqual(len(logger_calls), 1)
# Skip any 500 handler action (like sending more mail...)
@override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True)
def test_poisoned_http_host_admin_site(self):
"Poisoned HTTP_HOST headers can't be used for reset emails on admin views"
with patch_logger('django.security.DisallowedHost', 'error') as logger_calls:
response = self.client.post(
'/admin_password_reset/',
{'email': '[email protected]'},
HTTP_HOST='www.example:[email protected]'
)
self.assertEqual(response.status_code, 400)
self.assertEqual(len(mail.outbox), 0)
self.assertEqual(len(logger_calls), 1)
def _test_confirm_start(self):
# Start by creating the email
self.client.post('/password_reset/', {'email': '[email protected]'})
self.assertEqual(len(mail.outbox), 1)
return self._read_signup_email(mail.outbox[0])
def _read_signup_email(self, email):
urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
self.assertIsNotNone(urlmatch, "No URL found in sent email")
return urlmatch.group(), urlmatch.groups()[0]
def test_confirm_valid(self):
url, path = self._test_confirm_start()
response = self.client.get(path)
# redirect to a 'complete' page:
self.assertContains(response, "Please enter your new password")
def test_confirm_invalid(self):
url, path = self._test_confirm_start()
# Let's munge the token in the path, but keep the same length,
# in case the URLconf will reject a different length.
path = path[:-5] + ("0" * 4) + path[-1]
response = self.client.get(path)
self.assertContains(response, "The password reset link was invalid")
def test_confirm_invalid_user(self):
# A non-existent user returns a 200 response, not a 404.
response = self.client.get('/reset/123456/1-1/')
self.assertContains(response, "The password reset link was invalid")
def test_confirm_overflow_user(self):
# A base36 user id that overflows int returns a 200 response.
response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/')
self.assertContains(response, "The password reset link was invalid")
def test_confirm_invalid_post(self):
# Same as test_confirm_invalid, but trying to do a POST instead.
url, path = self._test_confirm_start()
path = path[:-5] + ("0" * 4) + path[-1]
self.client.post(path, {
'new_password1': 'anewpassword',
'new_password2': ' anewpassword',
})
# Check the password has not been changed
u = User.objects.get(email='[email protected]')
self.assertTrue(not u.check_password("anewpassword"))
def test_confirm_invalid_hash(self):
"""A POST with an invalid token is rejected."""
u = User.objects.get(email='[email protected]')
original_password = u.password
url, path = self._test_confirm_start()
path_parts = path.split('-')
path_parts[-1] = ("0") * 20 + '/'
path = '-'.join(path_parts)
response = self.client.post(path, {
'new_password1': 'anewpassword',
'new_password2': 'anewpassword',
})
self.assertIs(response.context['validlink'], False)
u.refresh_from_db()
self.assertEqual(original_password, u.password) # password hasn't changed
def test_confirm_complete(self):
url, path = self._test_confirm_start()
response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
# Check the password has been changed
u = User.objects.get(email='[email protected]')
self.assertTrue(u.check_password("anewpassword"))
# The reset token is deleted from the session.
self.assertNotIn(INTERNAL_RESET_SESSION_TOKEN, self.client.session)
# Check we can't use the link again
response = self.client.get(path)
self.assertContains(response, "The password reset link was invalid")
def test_confirm_different_passwords(self):
url, path = self._test_confirm_start()
response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'x'})
self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch'])
def test_reset_redirect_default(self):
response = self.client.post('/password_reset/', {'email': '[email protected]'})
self.assertRedirects(response, '/password_reset/done/', fetch_redirect_response=False)
def test_reset_custom_redirect(self):
response = self.client.post('/password_reset/custom_redirect/', {'email': '[email protected]'})
self.assertRedirects(response, '/custom/', fetch_redirect_response=False)
def test_reset_custom_redirect_named(self):
response = self.client.post('/password_reset/custom_redirect/named/', {'email': '[email protected]'})
self.assertRedirects(response, '/password_reset/', fetch_redirect_response=False)
def test_confirm_redirect_default(self):
url, path = self._test_confirm_start()
response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
self.assertRedirects(response, '/reset/done/', fetch_redirect_response=False)
def test_confirm_redirect_custom(self):
url, path = self._test_confirm_start()
path = path.replace('/reset/', '/reset/custom/')
response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
self.assertRedirects(response, '/custom/', fetch_redirect_response=False)
def test_confirm_redirect_custom_named(self):
url, path = self._test_confirm_start()
path = path.replace('/reset/', '/reset/custom/named/')
response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
self.assertRedirects(response, '/password_reset/', fetch_redirect_response=False)
def test_confirm_login_post_reset(self):
url, path = self._test_confirm_start()
path = path.replace('/reset/', '/reset/post_reset_login/')
response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
self.assertRedirects(response, '/reset/done/', fetch_redirect_response=False)
self.assertIn(SESSION_KEY, self.client.session)
def test_confirm_display_user_from_form(self):
url, path = self._test_confirm_start()
response = self.client.get(path)
# The password_reset_confirm() view passes the user object to the
# SetPasswordForm``, even on GET requests (#16919). For this test,
# {{ form.user }}`` is rendered in the template
# registration/password_reset_confirm.html.
username = User.objects.get(email='[email protected]').username
self.assertContains(response, "Hello, %s." % username)
# However, the view should NOT pass any user object on a form if the
# password reset link was invalid.
response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/')
self.assertContains(response, "Hello, .")
def test_confirm_link_redirects_to_set_password_page(self):
url, path = self._test_confirm_start()
# Don't use PasswordResetConfirmClient (self.client) here which
# automatically fetches the redirect page.
client = Client()
response = client.get(path)
token = response.resolver_match.kwargs['token']
uuidb64 = response.resolver_match.kwargs['uidb64']
self.assertRedirects(response, '/reset/%s/set-password/' % uuidb64)
self.assertEqual(client.session['_password_reset_token'], token)
def test_invalid_link_if_going_directly_to_the_final_reset_password_url(self):
url, path = self._test_confirm_start()
_, uuidb64, _ = path.strip('/').split('/')
response = Client().get('/reset/%s/set-password/' % uuidb64)
self.assertContains(response, 'The password reset link was invalid')
@override_settings(AUTH_USER_MODEL='auth_tests.CustomUser')
class CustomUserPasswordResetTest(AuthViewsTestCase):
user_email = '[email protected]'
@classmethod
def setUpTestData(cls):
cls.u1 = CustomUser.custom_objects.create(
email='[email protected]',
date_of_birth=datetime.date(1976, 11, 8),
)
cls.u1.set_password('password')
cls.u1.save()
def setUp(self):
self.client = PasswordResetConfirmClient()
def _test_confirm_start(self):
# Start by creating the email
response = self.client.post('/password_reset/', {'email': self.user_email})
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
return self._read_signup_email(mail.outbox[0])
def _read_signup_email(self, email):
urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
self.assertIsNotNone(urlmatch, "No URL found in sent email")
return urlmatch.group(), urlmatch.groups()[0]
def test_confirm_valid_custom_user(self):
url, path = self._test_confirm_start()
response = self.client.get(path)
# redirect to a 'complete' page:
self.assertContains(response, "Please enter your new password")
# then submit a new password
response = self.client.post(path, {
'new_password1': 'anewpassword',
'new_password2': 'anewpassword',
})
self.assertRedirects(response, '/reset/done/')
@override_settings(AUTH_USER_MODEL='auth_tests.UUIDUser')
class UUIDUserPasswordResetTest(CustomUserPasswordResetTest):
def _test_confirm_start(self):
# instead of fixture
UUIDUser.objects.create_user(
email=self.user_email,
username='foo',
password='foo',
)
return super(UUIDUserPasswordResetTest, self)._test_confirm_start()
class ChangePasswordTest(AuthViewsTestCase):
def fail_login(self):
response = self.client.post('/login/', {
'username': 'testclient',
'password': 'password',
})
self.assertFormError(response, AuthenticationForm.error_messages['invalid_login'] % {
'username': User._meta.get_field('username').verbose_name
})
def logout(self):
self.client.get('/logout/')
def test_password_change_fails_with_invalid_old_password(self):
self.login()
response = self.client.post('/password_change/', {
'old_password': 'donuts',
'new_password1': 'password1',
'new_password2': 'password1',
})
self.assertFormError(response, PasswordChangeForm.error_messages['password_incorrect'])
def test_password_change_fails_with_mismatched_passwords(self):
self.login()
response = self.client.post('/password_change/', {
'old_password': 'password',
'new_password1': 'password1',
'new_password2': 'donuts',
})
self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch'])
def test_password_change_succeeds(self):
self.login()
self.client.post('/password_change/', {
'old_password': 'password',
'new_password1': 'password1',
'new_password2': 'password1',
})
self.fail_login()
self.login(password='password1')
def test_password_change_done_succeeds(self):
self.login()
response = self.client.post('/password_change/', {
'old_password': 'password',
'new_password1': 'password1',
'new_password2': 'password1',
})
self.assertRedirects(response, '/password_change/done/', fetch_redirect_response=False)
@override_settings(LOGIN_URL='/login/')
def test_password_change_done_fails(self):
response = self.client.get('/password_change/done/')
self.assertRedirects(response, '/login/?next=/password_change/done/', fetch_redirect_response=False)
def test_password_change_redirect_default(self):
self.login()
response = self.client.post('/password_change/', {
'old_password': 'password',
'new_password1': 'password1',
'new_password2': 'password1',
})
self.assertRedirects(response, '/password_change/done/', fetch_redirect_response=False)
def test_password_change_redirect_custom(self):
self.login()
response = self.client.post('/password_change/custom/', {
'old_password': 'password',
'new_password1': 'password1',
'new_password2': 'password1',
})
self.assertRedirects(response, '/custom/', fetch_redirect_response=False)
def test_password_change_redirect_custom_named(self):
self.login()
response = self.client.post('/password_change/custom/named/', {
'old_password': 'password',
'new_password1': 'password1',
'new_password2': 'password1',
})
self.assertRedirects(response, '/password_reset/', fetch_redirect_response=False)
class SessionAuthenticationTests(AuthViewsTestCase):
def test_user_password_change_updates_session(self):
"""
#21649 - Ensure contrib.auth.views.password_change updates the user's
session auth hash after a password change so the session isn't logged out.
"""
self.login()
original_session_key = self.client.session.session_key
response = self.client.post('/password_change/', {
'old_password': 'password',
'new_password1': 'password1',
'new_password2': 'password1',
})
# if the hash isn't updated, retrieving the redirection page will fail.
self.assertRedirects(response, '/password_change/done/')
# The session key is rotated.
self.assertNotEqual(original_session_key, self.client.session.session_key)
class LoginTest(AuthViewsTestCase):
def test_current_site_in_context_after_login(self):
response = self.client.get(reverse('login'))
self.assertEqual(response.status_code, 200)
if apps.is_installed('django.contrib.sites'):
Site = apps.get_model('sites.Site')
site = Site.objects.get_current()
self.assertEqual(response.context['site'], site)
self.assertEqual(response.context['site_name'], site.name)
else:
self.assertIsInstance(response.context['site'], RequestSite)
self.assertIsInstance(response.context['form'], AuthenticationForm)
def test_security_check(self):
login_url = reverse('login')
# Those URLs should not pass the security check
for bad_url in ('http://example.com',
'http:///example.com',
'https://example.com',
'ftp://example.com',
'///example.com',
'//example.com',
'javascript:alert("XSS")'):
nasty_url = '%(url)s?%(next)s=%(bad_url)s' % {
'url': login_url,
'next': REDIRECT_FIELD_NAME,
'bad_url': urlquote(bad_url),
}
response = self.client.post(nasty_url, {
'username': 'testclient',
'password': 'password',
})
self.assertEqual(response.status_code, 302)
self.assertNotIn(bad_url, response.url,
"%s should be blocked" % bad_url)
# These URLs *should* still pass the security check
for good_url in ('/view/?param=http://example.com',
'/view/?param=https://example.com',
'/view?param=ftp://example.com',
'view/?param=//example.com',
'https://testserver/',
'HTTPS://testserver/',
'//testserver/',
'/url%20with%20spaces/'): # see ticket #12534
safe_url = '%(url)s?%(next)s=%(good_url)s' % {
'url': login_url,
'next': REDIRECT_FIELD_NAME,
'good_url': urlquote(good_url),
}
response = self.client.post(safe_url, {
'username': 'testclient',
'password': 'password',
})
self.assertEqual(response.status_code, 302)
self.assertIn(good_url, response.url, "%s should be allowed" % good_url)
def test_security_check_https(self):
login_url = reverse('login')
non_https_next_url = 'http://testserver/path'
not_secured_url = '%(url)s?%(next)s=%(next_url)s' % {
'url': login_url,
'next': REDIRECT_FIELD_NAME,
'next_url': urlquote(non_https_next_url),
}
post_data = {
'username': 'testclient',
'password': 'password',
}
response = self.client.post(not_secured_url, post_data, secure=True)
self.assertEqual(response.status_code, 302)
self.assertNotEqual(response.url, non_https_next_url)
self.assertEqual(response.url, settings.LOGIN_REDIRECT_URL)
def test_login_form_contains_request(self):
# 15198
self.client.post('/custom_requestauth_login/', {
'username': 'testclient',
'password': 'password',
}, follow=True)
# the custom authentication form used by this login asserts
# that a request is passed to the form successfully.
def test_login_csrf_rotate(self):
"""
Makes sure that a login rotates the currently-used CSRF token.
"""
# Do a GET to establish a CSRF token
# TestClient isn't used here as we're testing middleware, essentially.
req = HttpRequest()
CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {})
# get_token() triggers CSRF token inclusion in the response
get_token(req)
resp = LoginView.as_view()(req)
resp2 = CsrfViewMiddleware().process_response(req, resp)
csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
token1 = csrf_cookie.coded_value
# Prepare the POST request
req = HttpRequest()
req.COOKIES[settings.CSRF_COOKIE_NAME] = token1
req.method = "POST"
req.POST = {'username': 'testclient', 'password': 'password', 'csrfmiddlewaretoken': token1}
# Use POST request to log in
SessionMiddleware().process_request(req)
CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {})
req.META["SERVER_NAME"] = "testserver" # Required to have redirect work in login view
req.META["SERVER_PORT"] = 80
resp = LoginView.as_view()(req)
resp2 = CsrfViewMiddleware().process_response(req, resp)
csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
token2 = csrf_cookie.coded_value
# Check the CSRF token switched
self.assertNotEqual(token1, token2)
def test_session_key_flushed_on_login(self):
"""
To avoid reusing another user's session, ensure a new, empty session is
created if the existing session corresponds to a different authenticated
user.
"""
self.login()
original_session_key = self.client.session.session_key
self.login(username='staff')
self.assertNotEqual(original_session_key, self.client.session.session_key)
def test_session_key_flushed_on_login_after_password_change(self):
"""
As above, but same user logging in after a password change.
"""
self.login()
original_session_key = self.client.session.session_key
# If no password change, session key should not be flushed.
self.login()
self.assertEqual(original_session_key, self.client.session.session_key)
user = User.objects.get(username='testclient')
user.set_password('foobar')
user.save()
self.login(password='foobar')
self.assertNotEqual(original_session_key, self.client.session.session_key)
def test_login_session_without_hash_session_key(self):
"""
Session without django.contrib.auth.HASH_SESSION_KEY should login
without an exception.
"""
user = User.objects.get(username='testclient')
engine = import_module(settings.SESSION_ENGINE)
session = engine.SessionStore()
session[SESSION_KEY] = user.id
session.save()
original_session_key = session.session_key
self.client.cookies[settings.SESSION_COOKIE_NAME] = original_session_key
self.login()
self.assertNotEqual(original_session_key, self.client.session.session_key)
class LoginURLSettings(AuthViewsTestCase):
"""Tests for settings.LOGIN_URL."""
def assertLoginURLEquals(self, url, parse_qs=False):
response = self.client.get('/login_required/')
self.assertEqual(response.status_code, 302)
self.assertURLEqual(response.url, url, parse_qs=parse_qs)
@override_settings(LOGIN_URL='/login/')
def test_standard_login_url(self):
self.assertLoginURLEquals('/login/?next=/login_required/')
@override_settings(LOGIN_URL='login')
def test_named_login_url(self):
self.assertLoginURLEquals('/login/?next=/login_required/')
@override_settings(LOGIN_URL='http://remote.example.com/login')
def test_remote_login_url(self):
quoted_next = urlquote('http://testserver/login_required/')
expected = 'http://remote.example.com/login?next=%s' % quoted_next
self.assertLoginURLEquals(expected)
@override_settings(LOGIN_URL='https:///login/')
def test_https_login_url(self):
quoted_next = urlquote('http://testserver/login_required/')
expected = 'https:///login/?next=%s' % quoted_next
self.assertLoginURLEquals(expected)
@override_settings(LOGIN_URL='/login/?pretty=1')
def test_login_url_with_querystring(self):
self.assertLoginURLEquals('/login/?pretty=1&next=/login_required/', parse_qs=True)
@override_settings(LOGIN_URL='http://remote.example.com/login/?next=/default/')
def test_remote_login_url_with_next_querystring(self):
quoted_next = urlquote('http://testserver/login_required/')
expected = 'http://remote.example.com/login/?next=%s' % quoted_next
self.assertLoginURLEquals(expected)
@override_settings(LOGIN_URL=reverse_lazy('login'))
def test_lazy_login_url(self):
self.assertLoginURLEquals('/login/?next=/login_required/')
class LoginRedirectUrlTest(AuthViewsTestCase):
"""Tests for settings.LOGIN_REDIRECT_URL."""
def assertLoginRedirectURLEqual(self, url):
response = self.login()
self.assertRedirects(response, url, fetch_redirect_response=False)
def test_default(self):
self.assertLoginRedirectURLEqual('/accounts/profile/')
@override_settings(LOGIN_REDIRECT_URL='/custom/')
def test_custom(self):
self.assertLoginRedirectURLEqual('/custom/')
@override_settings(LOGIN_REDIRECT_URL='password_reset')
def test_named(self):
self.assertLoginRedirectURLEqual('/password_reset/')
@override_settings(LOGIN_REDIRECT_URL='http://remote.example.com/welcome/')
def test_remote(self):
self.assertLoginRedirectURLEqual('http://remote.example.com/welcome/')
class RedirectToLoginTests(AuthViewsTestCase):
"""Tests for the redirect_to_login view"""
@override_settings(LOGIN_URL=reverse_lazy('login'))
def test_redirect_to_login_with_lazy(self):
login_redirect_response = redirect_to_login(next='/else/where/')
expected = '/login/?next=/else/where/'
self.assertEqual(expected, login_redirect_response.url)
@override_settings(LOGIN_URL=reverse_lazy('login'))
def test_redirect_to_login_with_lazy_and_unicode(self):
login_redirect_response = redirect_to_login(next='/else/where/झ/')
expected = '/login/?next=/else/where/%E0%A4%9D/'
self.assertEqual(expected, login_redirect_response.url)
class LogoutThenLoginTests(AuthViewsTestCase):
"""Tests for the logout_then_login view"""
def confirm_logged_out(self):
self.assertNotIn(SESSION_KEY, self.client.session)
@override_settings(LOGIN_URL='/login/')
def test_default_logout_then_login(self):
self.login()
req = HttpRequest()
req.method = 'GET'
req.session = self.client.session
response = logout_then_login(req)
self.confirm_logged_out()
self.assertRedirects(response, '/login/', fetch_redirect_response=False)
def test_logout_then_login_with_custom_login(self):
self.login()
req = HttpRequest()
req.method = 'GET'
req.session = self.client.session
response = logout_then_login(req, login_url='/custom/')
self.confirm_logged_out()
self.assertRedirects(response, '/custom/', fetch_redirect_response=False)
def test_deprecated_extra_context(self):
with self.assertRaisesMessage(RemovedInDjango21Warning, 'The unused `extra_context` parameter'):
logout_then_login(None, extra_context={})
class LoginRedirectAuthenticatedUser(AuthViewsTestCase):
dont_redirect_url = '/login/redirect_authenticated_user_default/'
do_redirect_url = '/login/redirect_authenticated_user/'
def test_default(self):
"""Stay on the login page by default."""
self.login()
response = self.client.get(self.dont_redirect_url)
self.assertEqual(response.status_code, 200)
def test_guest(self):
"""If not logged in, stay on the same page."""
response = self.client.get(self.do_redirect_url)
self.assertEqual(response.status_code, 200)
def test_redirect(self):
"""If logged in, go to default redirected URL."""
self.login()
response = self.client.get(self.do_redirect_url)
self.assertRedirects(response, '/accounts/profile/', fetch_redirect_response=False)
@override_settings(LOGIN_REDIRECT_URL='/custom/')
def test_redirect_url(self):
"""If logged in, go to custom redirected URL."""
self.login()
response = self.client.get(self.do_redirect_url)
self.assertRedirects(response, '/custom/', fetch_redirect_response=False)
def test_redirect_param(self):
"""If next is specified as a GET parameter, go there."""
self.login()
url = self.do_redirect_url + '?next=/custom_next/'
response = self.client.get(url)
self.assertRedirects(response, '/custom_next/', fetch_redirect_response=False)
def test_redirect_loop(self):
"""
Detect a redirect loop if LOGIN_REDIRECT_URL is not correctly set,
with and without custom parameters.
"""
self.login()
msg = (
"Redirection loop for authenticated user detected. Check that "
"your LOGIN_REDIRECT_URL doesn't point to a login page"
)
with self.settings(LOGIN_REDIRECT_URL=self.do_redirect_url):
with self.assertRaisesMessage(ValueError, msg):
self.client.get(self.do_redirect_url)
url = self.do_redirect_url + '?bla=2'
with self.assertRaisesMessage(ValueError, msg):
self.client.get(url)
class LoginSuccessURLAllowedHostsTest(AuthViewsTestCase):
def test_success_url_allowed_hosts_same_host(self):
response = self.client.post('/login/allowed_hosts/', {
'username': 'testclient',
'password': 'password',
'next': 'https://testserver/home',
})
self.assertIn(SESSION_KEY, self.client.session)
self.assertRedirects(response, 'https://testserver/home', fetch_redirect_response=False)
def test_success_url_allowed_hosts_safe_host(self):
response = self.client.post('/login/allowed_hosts/', {
'username': 'testclient',
'password': 'password',
'next': 'https://otherserver/home',
})
self.assertIn(SESSION_KEY, self.client.session)
self.assertRedirects(response, 'https://otherserver/home', fetch_redirect_response=False)
def test_success_url_allowed_hosts_unsafe_host(self):
response = self.client.post('/login/allowed_hosts/', {
'username': 'testclient',
'password': 'password',
'next': 'https://evil/home',
})
self.assertIn(SESSION_KEY, self.client.session)
self.assertRedirects(response, '/accounts/profile/', fetch_redirect_response=False)
class LogoutTest(AuthViewsTestCase):
def confirm_logged_out(self):
self.assertNotIn(SESSION_KEY, self.client.session)
def test_logout_default(self):
"Logout without next_page option renders the default template"
self.login()
response = self.client.get('/logout/')
self.assertContains(response, 'Logged out')
self.confirm_logged_out()
def test_14377(self):
# Bug 14377
self.login()
response = self.client.get('/logout/')
self.assertIn('site', response.context)
def test_logout_doesnt_cache(self):
"""
The logout() view should send "no-cache" headers for reasons described
in #25490.
"""
response = self.client.get('/logout/')
self.assertIn('no-store', response['Cache-Control'])
def test_logout_with_overridden_redirect_url(self):
# Bug 11223
self.login()
response = self.client.get('/logout/next_page/')
self.assertRedirects(response, '/somewhere/', fetch_redirect_response=False)
response = self.client.get('/logout/next_page/?next=/login/')
self.assertRedirects(response, '/login/', fetch_redirect_response=False)
self.confirm_logged_out()
def test_logout_with_next_page_specified(self):
"Logout with next_page option given redirects to specified resource"
self.login()
response = self.client.get('/logout/next_page/')
self.assertRedirects(response, '/somewhere/', fetch_redirect_response=False)
self.confirm_logged_out()
def test_logout_with_redirect_argument(self):
"Logout with query string redirects to specified resource"
self.login()
response = self.client.get('/logout/?next=/login/')
self.assertRedirects(response, '/login/', fetch_redirect_response=False)
self.confirm_logged_out()
def test_logout_with_custom_redirect_argument(self):
"Logout with custom query string redirects to specified resource"
self.login()
response = self.client.get('/logout/custom_query/?follow=/somewhere/')
self.assertRedirects(response, '/somewhere/', fetch_redirect_response=False)
self.confirm_logged_out()
def test_logout_with_named_redirect(self):
"Logout resolves names or URLs passed as next_page."
self.login()
response = self.client.get('/logout/next_page/named/')
self.assertRedirects(response, '/password_reset/', fetch_redirect_response=False)
self.confirm_logged_out()
def test_success_url_allowed_hosts_same_host(self):
self.login()
response = self.client.get('/logout/allowed_hosts/?next=https://testserver/')
self.assertRedirects(response, 'https://testserver/', fetch_redirect_response=False)
self.confirm_logged_out()
def test_success_url_allowed_hosts_safe_host(self):
self.login()
response = self.client.get('/logout/allowed_hosts/?next=https://otherserver/')
self.assertRedirects(response, 'https://otherserver/', fetch_redirect_response=False)
self.confirm_logged_out()
def test_success_url_allowed_hosts_unsafe_host(self):
self.login()
response = self.client.get('/logout/allowed_hosts/?next=https://evil/')
self.assertRedirects(response, '/logout/allowed_hosts/', fetch_redirect_response=False)
self.confirm_logged_out()
def test_security_check(self):
logout_url = reverse('logout')
# Those URLs should not pass the security check
for bad_url in ('http://example.com',
'http:///example.com',
'https://example.com',
'ftp://example.com',
'///example.com',
'//example.com',
'javascript:alert("XSS")'):
nasty_url = '%(url)s?%(next)s=%(bad_url)s' % {
'url': logout_url,
'next': REDIRECT_FIELD_NAME,
'bad_url': urlquote(bad_url),
}
self.login()
response = self.client.get(nasty_url)
self.assertEqual(response.status_code, 302)
self.assertNotIn(bad_url, response.url,
"%s should be blocked" % bad_url)
self.confirm_logged_out()
# These URLs *should* still pass the security check
for good_url in ('/view/?param=http://example.com',
'/view/?param=https://example.com',
'/view?param=ftp://example.com',
'view/?param=//example.com',
'https://testserver/',
'HTTPS://testserver/',
'//testserver/',
'/url%20with%20spaces/'): # see ticket #12534
safe_url = '%(url)s?%(next)s=%(good_url)s' % {
'url': logout_url,
'next': REDIRECT_FIELD_NAME,
'good_url': urlquote(good_url),
}
self.login()
response = self.client.get(safe_url)
self.assertEqual(response.status_code, 302)
self.assertIn(good_url, response.url, "%s should be allowed" % good_url)
self.confirm_logged_out()
def test_security_check_https(self):
logout_url = reverse('logout')
non_https_next_url = 'http://testserver/'
url = '%(url)s?%(next)s=%(next_url)s' % {
'url': logout_url,
'next': REDIRECT_FIELD_NAME,
'next_url': urlquote(non_https_next_url),
}
self.login()
response = self.client.get(url, secure=True)
self.assertRedirects(response, logout_url, fetch_redirect_response=False)
self.confirm_logged_out()
def test_logout_preserve_language(self):
"""Language stored in session is preserved after logout"""
# Create a new session with language
engine = import_module(settings.SESSION_ENGINE)
session = engine.SessionStore()
session[LANGUAGE_SESSION_KEY] = 'pl'
session.save()
self.client.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
self.client.get('/logout/')
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'pl')
@override_settings(LOGOUT_REDIRECT_URL='/custom/')
def test_logout_redirect_url_setting(self):
self.login()
response = self.client.get('/logout/')
self.assertRedirects(response, '/custom/', fetch_redirect_response=False)
@override_settings(LOGOUT_REDIRECT_URL='logout')
def test_logout_redirect_url_named_setting(self):
self.login()
response = self.client.get('/logout/')
self.assertRedirects(response, '/logout/', fetch_redirect_response=False)
# Redirect in test_user_change_password will fail if session auth hash
# isn't updated after password change (#21649)
@override_settings(ROOT_URLCONF='auth_tests.urls_admin')
class ChangelistTests(AuthViewsTestCase):
def setUp(self):
# Make me a superuser before logging in.
User.objects.filter(username='testclient').update(is_staff=True, is_superuser=True)
self.login()
self.admin = User.objects.get(pk=self.u1.pk)
def get_user_data(self, user):
return {
'username': user.username,
'password': user.password,
'email': user.email,
'is_active': user.is_active,
'is_staff': user.is_staff,
'is_superuser': user.is_superuser,
'last_login_0': user.last_login.strftime('%Y-%m-%d'),
'last_login_1': user.last_login.strftime('%H:%M:%S'),
'initial-last_login_0': user.last_login.strftime('%Y-%m-%d'),
'initial-last_login_1': user.last_login.strftime('%H:%M:%S'),
'date_joined_0': user.date_joined.strftime('%Y-%m-%d'),
'date_joined_1': user.date_joined.strftime('%H:%M:%S'),
'initial-date_joined_0': user.date_joined.strftime('%Y-%m-%d'),
'initial-date_joined_1': user.date_joined.strftime('%H:%M:%S'),
'first_name': user.first_name,
'last_name': user.last_name,
}
# #20078 - users shouldn't be allowed to guess password hashes via
# repeated password__startswith queries.
def test_changelist_disallows_password_lookups(self):
# A lookup that tries to filter on password isn't OK
with patch_logger('django.security.DisallowedModelAdminLookup', 'error') as logger_calls:
response = self.client.get(reverse('auth_test_admin:auth_user_changelist') + '?password__startswith=sha1$')
self.assertEqual(response.status_code, 400)
self.assertEqual(len(logger_calls), 1)
def test_user_change_email(self):
data = self.get_user_data(self.admin)
data['email'] = 'new_' + data['email']
response = self.client.post(
reverse('auth_test_admin:auth_user_change', args=(self.admin.pk,)),
data
)
self.assertRedirects(response, reverse('auth_test_admin:auth_user_changelist'))
row = LogEntry.objects.latest('id')
self.assertEqual(row.get_change_message(), 'Changed email.')
def test_user_not_change(self):
response = self.client.post(
reverse('auth_test_admin:auth_user_change', args=(self.admin.pk,)),
self.get_user_data(self.admin)
)
self.assertRedirects(response, reverse('auth_test_admin:auth_user_changelist'))
row = LogEntry.objects.latest('id')
self.assertEqual(row.get_change_message(), 'No fields changed.')
def test_user_change_password(self):
user_change_url = reverse('auth_test_admin:auth_user_change', args=(self.admin.pk,))
password_change_url = reverse('auth_test_admin:auth_user_password_change', args=(self.admin.pk,))
response = self.client.get(user_change_url)
# Test the link inside password field help_text.
rel_link = re.search(
r'you can change the password using <a href="([^"]*)">this form</a>',
force_text(response.content)
).groups()[0]
self.assertEqual(
os.path.normpath(user_change_url + rel_link),
os.path.normpath(password_change_url)
)
response = self.client.post(
password_change_url,
{
'password1': 'password1',
'password2': 'password1',
}
)
self.assertRedirects(response, user_change_url)
row = LogEntry.objects.latest('id')
self.assertEqual(row.get_change_message(), 'Changed password.')
self.logout()
self.login(password='password1')
def test_user_change_different_user_password(self):
u = User.objects.get(email='[email protected]')
response = self.client.post(
reverse('auth_test_admin:auth_user_password_change', args=(u.pk,)),
{
'password1': 'password1',
'password2': 'password1',
}
)
self.assertRedirects(response, reverse('auth_test_admin:auth_user_change', args=(u.pk,)))
row = LogEntry.objects.latest('id')
self.assertEqual(row.user_id, self.admin.pk)
self.assertEqual(row.object_id, str(u.pk))
self.assertEqual(row.get_change_message(), 'Changed password.')
def test_password_change_bad_url(self):
response = self.client.get(reverse('auth_test_admin:auth_user_password_change', args=('foobar',)))
self.assertEqual(response.status_code, 404)
@override_settings(
AUTH_USER_MODEL='auth_tests.UUIDUser',
ROOT_URLCONF='auth_tests.urls_custom_user_admin',
)
class UUIDUserTests(TestCase):
def test_admin_password_change(self):
u = UUIDUser.objects.create_superuser(username='uuid', email='[email protected]', password='test')
self.assertTrue(self.client.login(username='uuid', password='test'))
user_change_url = reverse('custom_user_admin:auth_tests_uuiduser_change', args=(u.pk,))
response = self.client.get(user_change_url)
self.assertEqual(response.status_code, 200)
password_change_url = reverse('custom_user_admin:auth_user_password_change', args=(u.pk,))
response = self.client.get(password_change_url)
self.assertEqual(response.status_code, 200)
# A LogEntry is created with pk=1 which breaks a FK constraint on MySQL
with connection.constraint_checks_disabled():
response = self.client.post(password_change_url, {
'password1': 'password1',
'password2': 'password1',
})
self.assertRedirects(response, user_change_url)
row = LogEntry.objects.latest('id')
self.assertEqual(row.user_id, 1) # hardcoded in CustomUserAdmin.log_change()
self.assertEqual(row.object_id, str(u.pk))
self.assertEqual(row.get_change_message(), 'Changed password.')
# The LogEntry.user column isn't altered to a UUID type so it's set to
# an integer manually in CustomUserAdmin to avoid an error. To avoid a
# constraint error, delete the entry before constraints are checked
# after the test.
row.delete()
| bsd-3-clause | 3,419,193,209,463,145,000 | 42.007595 | 119 | 0.627149 | false |
lupyuen/RaspberryPiImage | usr/share/pyshared/ajenti/users.py | 1 | 4815 | import logging
import syslog
from passlib.hash import sha512_crypt
import ajenti
import ajenti.usersync
from ajenti.api import *
def restrict(permission):
"""
Marks a decorated function as requiring ``permission``.
If the invoking user doesn't have one, :class:`SecurityError` is raised.
"""
def decorator(fx):
def wrapper(*args, **kwargs):
UserManager.get().require_permission(extract_context(), permission)
return fx(*args, **kwargs)
return wrapper
return decorator
class SecurityError (Exception):
"""
Indicates that user didn't have a required permission.
.. attribute:: permission
permission ID
"""
def __init__(self, permission):
self.permission = permission
def __str__(self):
return 'Permission "%s" required' % self.permission
@plugin
@persistent
@rootcontext
class UserManager (BasePlugin):
default_classconfig = {'sync-provider': ''}
classconfig_root = True
def check_password(self, username, password, env=None):
"""
Verifies the given username/password combo
:type username: str
:type password: str
:rtype: bool
"""
if not username or not password:
return False
provider = self.get_sync_provider(fallback=True)
if username == 'root' and not provider.syncs_root:
provider = ajenti.usersync.AjentiSyncProvider.get()
if not username in ajenti.config.tree.users:
return False
try:
provider.sync()
except Exception as e:
logging.error(str(e))
result = provider.check_password(username, password)
provider_name = type(provider).__name__
ip_notion = ''
ip = env.get('REMOTE_ADDR', None) if env else None
if ip:
ip_notion = ' from %s' % ip
if not result:
msg = 'failed login attempt for %s ("%s") through %s%s' % \
(username, password, provider_name, ip_notion)
syslog.syslog(syslog.LOG_WARNING, msg)
logging.warn(msg)
else:
msg = 'user %s logged in through %s%s' % (username, provider_name, ip_notion)
syslog.syslog(syslog.LOG_INFO, msg)
logging.info(msg)
return result
def hash_password(self, password):
"""
:type password: str
:rtype: str
"""
if not password.startswith('sha512|'):
password = 'sha512|%s' % sha512_crypt.encrypt(password)
return password
def hash_passwords(self):
for user in ajenti.config.tree.users.values():
if not user.password.startswith('sha512|'):
user.password = self.hash_password(user.password)
def has_permission(self, context, permission):
"""
Checks whether the current user has a permission
:type permission: str
:rtype: bool
"""
if context.user.name == 'root':
return True
if not permission in context.user.permissions:
return False
return True
def require_permission(self, context, permission):
"""
Checks current user for given permission and
raises :class:`SecurityError` if he doesn't have one
:type permission: str
:raises: SecurityError
"""
if not self.has_permission(context, permission):
raise SecurityError(permission)
def get_sync_provider(self, fallback=False):
"""
:type fallback: bool
:rtype: ajenti.usersync.UserSyncProvider
"""
for p in ajenti.usersync.UserSyncProvider.get_classes():
p.get()
if p.id == self.classconfig['sync-provider']:
try:
p.get().test()
except:
if fallback:
return ajenti.usersync.AjentiSyncProvider.get()
return p.get()
def set_sync_provider(self, provider_id):
self.classconfig['sync-provider'] = provider_id
self.save_classconfig()
def set_password(self, username, password):
ajenti.config.tree.users[username].password = self.hash_password(password)
@interface
class PermissionProvider (object):
"""
Override to create your own set of permissions
"""
def get_permissions(self):
"""
Should return a list of permission names
:rtype: list
"""
return []
def get_name(self):
"""
Should return a human-friendly name for this set
of permissions (displayed in Configurator)
:rtype: str
"""
return ''
__all__ = ['restrict', 'PermissionProvider', 'SecurityError', 'UserManager']
| apache-2.0 | -4,075,475,881,534,769,000 | 27.157895 | 89 | 0.585462 | false |
whaleygeek/MyLittleComputer | src/python/ioinstrs.py | 1 | 1105 | # ioinstrs.py 10/07/2016 D.J.Whale
#
# Add extra IO instructions to the instruction set simulator
import instruction
# Runtime registration of generic form
# you can add specific mnemonic names here if you want,
# see the example in extinstrs.py to see how to do it in a way that
# does not pollute instruction.py with optional features.
instruction.registerMnemonic("IO", 900, False)
# INP and OUT are already handled in simulator.py, and never delegated here.
# 901=INP and 902=OUT, but 900 and 903..999 are not used.
# These undefined instructions are therefore useful to use to define
# other types of IO, such as GPO for general purpose output, GPI for
# general purpose input, AIN for analog input, and other I/O
# related things that would not warrant a HLT for an OS call.
# they could be done as User instrutions (U) but it's handy to group
# all the I/O together into a set of instructions.
def execIOInstr(operand, acc):
"""Execute any user IO instructions here (instruction.IO_xx)"""
print("exec IO instr %d" % str(operand))
# DEFINE NEW IO INSTRUCTIONS HERE
return acc
# END
| mit | 7,846,040,514,561,670,000 | 31.5 | 76 | 0.750226 | false |
kingsdigitallab/gssn-django | cms/models/pages.py | 1 | 14847 | from __future__ import unicode_literals
from datetime import date
import logging
from django.conf import settings
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db import models
from django.db.models import Q
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.shortcuts import render
from modelcluster.fields import ParentalKey
from modelcluster.tags import ClusterTaggableManager
from taggit.models import TaggedItemBase
from wagtail.contrib.wagtailroutablepage.models import RoutablePageMixin, route
from wagtail.wagtailadmin.edit_handlers import (
FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel, PageChooserPanel,
StreamFieldPanel
)
from wagtail.wagtailcore.fields import StreamField
from wagtail.wagtailcore.models import Orderable, Page
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
from wagtail.wagtailsearch import index
from .behaviours import WithFeedImage, WithIntroduction, WithStreamField
from .carousel import AbstractCarouselItem
from .links import AbstractRelatedLink
from .streamfield import CMSStreamBlock
logger = logging.getLogger(__name__)
# HomePage
class HomePageCarouselItem(Orderable, AbstractCarouselItem):
page = ParentalKey('HomePage', related_name='carousel_items')
class HomePageFeaturedPage(Orderable):
page = ParentalKey('HomePage', related_name='featured_pages')
featured_page = models.ForeignKey(Page)
panels = [
PageChooserPanel('featured_page')
]
def __unicode__(self):
return self.featured_page
class HomePageRelatedLink(Orderable, AbstractRelatedLink):
page = ParentalKey('HomePage', related_name='related_links')
class HomePage(Page, WithStreamField):
announcement = StreamField(CMSStreamBlock())
search_fields = Page.search_fields + [
index.SearchField('body'),
index.SearchField('announcement'),
]
subpage_types = ['IndexPage', 'BlogIndexPage', 'EventIndexPage',
'ResourcesIndexPage', 'RichTextPage']
class Meta:
verbose_name = 'Homepage'
def get_latest_blog_posts(self):
bip = self.get_children().type(BlogIndexPage).first().specific
return bip.posts[:2]
def get_live_events(self):
eip = self.get_children().type(EventIndexPage).first().specific
return eip.live_events[:2]
HomePage.content_panels = [
FieldPanel('title', classname='full title'),
StreamFieldPanel('body'),
InlinePanel('featured_pages', label='Featured pages'),
InlinePanel('carousel_items', label='Carousel items'),
StreamFieldPanel('announcement'),
InlinePanel('related_links', label='Related links'),
]
HomePage.promote_panels = Page.promote_panels
# IndexPage
class IndexPageRelatedLink(Orderable, AbstractRelatedLink):
page = ParentalKey('IndexPage', related_name='related_links')
class IndexPage(Page, WithFeedImage, WithIntroduction):
search_fields = Page.search_fields + [
index.SearchField('intro'),
]
subpage_types = ['IndexPage', 'RichTextPage']
IndexPage.content_panels = [
FieldPanel('title', classname='full title'),
StreamFieldPanel('intro'),
InlinePanel('related_links', label='Related links'),
]
IndexPage.promote_panels = Page.promote_panels + [
ImageChooserPanel('feed_image'),
]
# RichTextPage
class RichTextPageCarouselItem(Orderable, AbstractCarouselItem):
page = ParentalKey('RichTextPage', related_name='carousel_items')
class RichTextPageRelatedLink(Orderable, AbstractRelatedLink):
page = ParentalKey('RichTextPage', related_name='related_links')
class RichTextPage(Page, WithFeedImage):
body = StreamField(CMSStreamBlock())
search_fields = Page.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
subpage_types = []
RichTextPage.content_panels = [
FieldPanel('title', classname='full title'),
InlinePanel('carousel_items', label='Carousel items'),
StreamFieldPanel('body'),
InlinePanel('related_links', label='Related links'),
]
RichTextPage.promote_panels = Page.promote_panels + [
ImageChooserPanel('feed_image'),
]
def _paginate(request, items):
# Pagination
page_number = request.GET.get('page', 1)
paginator = Paginator(items, settings.ITEMS_PER_PAGE)
try:
page = paginator.page(page_number)
except EmptyPage:
page = paginator.page(paginator.num_pages)
except PageNotAnInteger:
page = paginator.page(1)
return page
# Blogs
# BlogIndexPage
class BlogIndexPageRelatedLink(Orderable, AbstractRelatedLink):
page = ParentalKey('BlogIndexPage', related_name='related_links')
class BlogIndexPage(RoutablePageMixin, Page, WithIntroduction):
search_fields = Page.search_fields + [
index.SearchField('intro'),
]
subpage_types = ['BlogPost']
class Meta:
verbose_name = 'News Index Page'
@property
def posts(self):
# gets list of live blog posts that are descendants of this page
posts = BlogPost.objects.live().descendant_of(self)
# orders by most recent date first
posts = posts.order_by('-date')
return posts
@route(r'^$')
def all_posts(self, request):
posts = self.posts
return render(request, self.get_template(request),
{'self': self, 'posts': _paginate(request, posts)})
@route(r'^author/(?P<author>[\w ]+)/$')
def author(self, request, author=None):
if not author:
# Invalid author filter
logger.error('Invalid author filter')
return self.all_posts(request)
posts = self.posts.filter(owner__username=author)
return render(
request, self.get_template(request), {
'self': self, 'posts': _paginate(request, posts),
'filter_type': 'author', 'filter': author
}
)
@route(r'^tag/(?P<tag>[\w\- ]+)/$')
def tag(self, request, tag=None):
if not tag:
# Invalid tag filter
logger.error('Invalid tag filter')
return self.all_posts(request)
posts = self.posts.filter(tags__name=tag)
return render(
request, self.get_template(request), {
'self': self, 'posts': _paginate(request, posts),
'filter_type': 'tag', 'filter': tag
}
)
BlogIndexPage.content_panels = [
FieldPanel('title', classname='full title'),
StreamFieldPanel('intro'),
InlinePanel('related_links', label='Related links'),
]
BlogIndexPage.promote_panels = Page.promote_panels
# BlogPost
class BlogPostCarouselItem(Orderable, AbstractCarouselItem):
page = ParentalKey('BlogPost', related_name='carousel_items')
class BlogPostRelatedLink(Orderable, AbstractRelatedLink):
page = ParentalKey('BlogPost', related_name='related_links')
class BlogPostTag(TaggedItemBase):
content_object = ParentalKey('BlogPost', related_name='tagged_items')
class BlogPost(Page, WithFeedImage, WithStreamField):
tags = ClusterTaggableManager(through=BlogPostTag, blank=True)
date = models.DateField('Post date')
search_fields = Page.search_fields + [
index.SearchField('body'),
]
subpage_types = []
class Meta:
verbose_name = 'News Post'
@property
def blog_index(self):
# finds closest ancestor which is a blog index
return self.get_ancestors().type(BlogIndexPage).last()
BlogPost.content_panels = [
FieldPanel('title', classname='full title'),
FieldPanel('date'),
StreamFieldPanel('body'),
InlinePanel('carousel_items', label='Carousel items'),
InlinePanel('related_links', label='Related links'),
]
BlogPost.promote_panels = Page.promote_panels + [
ImageChooserPanel('feed_image'),
FieldPanel('tags'),
]
# Events
# EventIndexPage
class EventIndexPageRelatedLink(Orderable, AbstractRelatedLink):
page = ParentalKey('EventIndexPage', related_name='related_links')
class EventIndexPage(RoutablePageMixin, Page, WithIntroduction):
search_fields = Page.search_fields + [
index.SearchField('intro'),
]
subpage_types = ['EventPage']
subnav_items = ['live', 'symposia', 'schools', 'past']
@property
def all_events(self):
# gets list of live event pages that are descendants of this page
events = EventPage.objects.live().descendant_of(self)
events = events.order_by('-date_from')
return events
@property
def live_events(self):
# gets list of live event pages that are descendants of this page
events = EventPage.objects.live().descendant_of(self)
# filters events list to get ones that are either
# running now or start in the future
today = date.today()
events = events.filter(Q(date_from__gte=today) | Q(date_to__gte=today))
events = events.order_by('date_from')
return events
@property
def past_events(self):
# gets list of live event pages that are descendants of this page
events = self.all_events
today = date.today()
events = events.filter(Q(date_from__lte=today) | Q(date_to__lte=today))
return events
@property
def symposiums(self):
events = EventPage.objects.live().descendant_of(self).filter(
is_symposium=True)
if events:
events = events.order_by('-date_from')
return events
@property
def schools(self):
events = EventPage.objects.live().descendant_of(self).filter(
is_school=True)
if events:
events = events.order_by('-date_from')
return events
@route(r'^$', name='live_events')
def get_live_events(self, request):
events = self.live_events
return render(request, self.get_template(request),
{'self': self, 'filter_type': 'live',
'events': _paginate(request, events)})
@route(r'^past/$', name='past_events')
def get_past_events(self, request):
events = self.past_events
return render(request, self.get_template(request),
{'self': self, 'filter_type': 'past',
'events': _paginate(request, events)})
@route(r'^symposia/$', name='symposia_events')
def get_symposiums(self, request):
events = self.symposiums
return render(request, self.get_template(request),
{'self': self, 'filter_type': 'symposia',
'events': _paginate(request, events)})
@route(r'^schools/$', name='schools_events')
def get_schools(self, request):
events = self.schools
return render(request, self.get_template(request),
{'self': self, 'filter_type': 'schools',
'events': _paginate(request, events)})
@route(r'^tag/(?P<tag>[\w\- ]+)/$')
def tag(self, request, tag=None):
if not tag:
# Invalid tag filter
logger.error('Invalid tag filter')
return self.get_live_events(request)
posts = self.all_events.filter(tags__name=tag)
return render(
request, self.get_template(request), {
'self': self, 'events': _paginate(request, posts),
'filter_type': 'tag', 'filter': tag
}
)
EventIndexPage.content_panels = [
FieldPanel('title', classname='full title'),
StreamFieldPanel('intro'),
InlinePanel('related_links', label='Related links'),
]
EventIndexPage.promote_panels = Page.promote_panels
# EventPage
class EventPageTag(TaggedItemBase):
content_object = ParentalKey('EventPage', related_name='tagged_items')
class EventPageCarouselItem(Orderable, AbstractCarouselItem):
page = ParentalKey('EventPage', related_name='carousel_items')
class EventPageRelatedLink(Orderable, AbstractRelatedLink):
page = ParentalKey('EventPage', related_name='related_links')
class EventPage(Page, WithFeedImage, WithStreamField):
tags = ClusterTaggableManager(through=EventPageTag, blank=True)
is_symposium = models.BooleanField()
is_school = models.BooleanField()
date_from = models.DateField('Start date')
date_to = models.DateField(
'End date', null=True, blank=True,
help_text='Not required if event is on a single day'
)
time_from = models.TimeField('Start time', null=True, blank=True)
time_to = models.TimeField('End time', null=True, blank=True)
location = models.CharField(max_length=256)
signup_link = models.URLField(null=True, blank=True)
search_fields = Page.search_fields + [
index.SearchField('location'),
index.SearchField('body'),
]
subpage_types = []
@property
def event_index(self):
# finds closest ancestor which is an event index
return self.get_ancestors().type(EventIndexPage).last()
EventPage.content_panels = [
FieldPanel('title', classname='full title'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('is_symposium', classname='col6'),
FieldPanel('is_school', classname='col6'),
], classname='full'),
], 'Categories'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('date_from', classname='col6'),
FieldPanel('date_to', classname='col6'),
], classname='full'),
FieldRowPanel([
FieldPanel('time_from', classname='col6'),
FieldPanel('time_to', classname='col6'),
], classname='full'),
], 'Dates'),
FieldPanel('location'),
InlinePanel('carousel_items', label='Carousel items'),
StreamFieldPanel('body'),
FieldPanel('signup_link'),
InlinePanel('related_links', label='Related links'),
]
EventPage.promote_panels = Page.promote_panels + [
ImageChooserPanel('feed_image'),
FieldPanel('tags'),
]
@receiver(pre_save, sender=EventPage)
def event_page_default_date_to(sender, instance, **kwargs):
# checks the date to is empty
if not instance.date_to:
# sets date_to to the same as date_from
instance.date_to = instance.date_from
# Resources
# ResourcesIndexPage
class ResourcesIndexPageRelatedLink(Orderable, AbstractRelatedLink):
page = ParentalKey('ResourcesIndexPage', related_name='related_links')
class ResourcesIndexPage(Page, WithIntroduction):
search_fields = Page.search_fields + [
index.SearchField('intro'),
]
subpage_types = ['RichTextPage']
ResourcesIndexPage.content_panels = [
FieldPanel('title', classname='full title'),
StreamFieldPanel('intro'),
InlinePanel('related_links', label='Related links'),
]
| gpl-2.0 | -8,299,712,338,552,435,000 | 28.516899 | 79 | 0.657507 | false |
won0089/oppia | scripts/backend_tests.py | 1 | 11560 | # Copyright 2014 The Oppia 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.
"""Script for running backend tests in parallel.
This should not be run directly. Instead, navigate to the oppia/ folder and
execute:
bash scripts/run_backend_tests.sh
"""
import argparse
import datetime
import os
import re
import subprocess
import threading
import time
# DEVELOPERS: Please change this number accordingly when new tests are added
# or removed.
EXPECTED_TEST_COUNT = 621
COVERAGE_PATH = os.path.join(
os.getcwd(), '..', 'oppia_tools', 'coverage-4.0', 'coverage')
TEST_RUNNER_PATH = os.path.join(os.getcwd(), 'core', 'tests', 'gae_suite.py')
LOG_LOCK = threading.Lock()
ALL_ERRORS = []
# This should be the same as core.test_utils.LOG_LINE_PREFIX.
LOG_LINE_PREFIX = 'LOG_INFO_TEST: '
_PARSER = argparse.ArgumentParser()
_PARSER.add_argument(
'--generate_coverage_report',
help='optional; if specified, generates a coverage report',
action='store_true')
_PARSER.add_argument(
'--test_target',
help='optional dotted module name of the test(s) to run',
type=str)
_PARSER.add_argument(
'--test_path',
help='optional subdirectory path containing the test(s) to run',
type=str)
def log(message, show_time=False):
"""Logs a message to the terminal.
If show_time is True, prefixes the message with the current time.
"""
with LOG_LOCK:
if show_time:
print datetime.datetime.utcnow().strftime('%H:%M:%S'), message
else:
print message
def run_shell_cmd(exe, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
"""Runs a shell command and captures the stdout and stderr output.
If the cmd fails, raises Exception. Otherwise, returns a string containing
the concatenation of the stdout and stderr logs.
"""
p = subprocess.Popen(exe, stdout=stdout, stderr=stderr)
last_stdout_str, last_stderr_str = p.communicate()
last_stdout = last_stdout_str.split('\n')
if LOG_LINE_PREFIX in last_stdout_str:
log('')
for line in last_stdout:
if line.startswith(LOG_LINE_PREFIX):
log('INFO: %s' % line[len(LOG_LINE_PREFIX): ])
log('')
result = '%s%s' % (last_stdout_str, last_stderr_str)
if p.returncode != 0:
raise Exception('Error %s\n%s' % (p.returncode, result))
return result
class TaskThread(threading.Thread):
"""Runs a task in its own thread."""
def __init__(self, func, name=None):
super(TaskThread, self).__init__()
self.func = func
self.output = None
self.exception = None
self.name = name
self.finished = False
def run(self):
try:
self.output = self.func()
log('FINISHED %s: %.1f secs' %
(self.name, time.time() - self.start_time), show_time=True)
self.finished = True
except Exception as e:
self.exception = e
if 'KeyboardInterrupt' not in str(self.exception):
log('ERROR %s: %.1f secs' %
(self.name, time.time() - self.start_time), show_time=True)
self.finished = True
class TestingTaskSpec(object):
"""Executes a set of tests given a test class name."""
def __init__(self, test_target, generate_coverage_report):
self.test_target = test_target
self.generate_coverage_report = generate_coverage_report
def run(self):
"""Runs all tests corresponding to the given test target."""
test_target_flag = '--test_target=%s' % self.test_target
if self.generate_coverage_report:
exc_list = [
'python', COVERAGE_PATH, 'run', '-p', TEST_RUNNER_PATH,
test_target_flag]
else:
exc_list = ['python', TEST_RUNNER_PATH, test_target_flag]
return run_shell_cmd(exc_list)
def _check_all_tasks(tasks):
"""Checks the results of all tasks."""
running_tasks_data = []
for task in tasks:
if task.isAlive():
running_tasks_data.append(' %s (started %s)' % (
task.name,
time.strftime('%H:%M:%S', time.localtime(task.start_time))
))
if task.exception:
ALL_ERRORS.append(task.exception)
if running_tasks_data:
log('----------------------------------------')
log('Tasks still running:')
for task_details in running_tasks_data:
log(task_details)
def _execute_tasks(tasks, batch_size=24):
"""Starts all tasks and checks the results.
Runs no more than 'batch_size' tasks at a time.
"""
remaining_tasks = [] + tasks
currently_running_tasks = set([])
while remaining_tasks or currently_running_tasks:
if currently_running_tasks:
for task in list(currently_running_tasks):
task.join(1)
if not task.isAlive():
currently_running_tasks.remove(task)
while remaining_tasks and len(currently_running_tasks) < batch_size:
task = remaining_tasks.pop()
currently_running_tasks.add(task)
task.start()
task.start_time = time.time()
time.sleep(5)
if remaining_tasks:
log('----------------------------------------')
log('Number of unstarted tasks: %s' % len(remaining_tasks))
_check_all_tasks(tasks)
log('----------------------------------------')
def _get_all_test_targets(test_path=None):
"""Returns a list of test targets for all classes under test_path
containing tests.
"""
def _convert_to_test_target(path):
"""Remove the .py suffix and replace all slashes with periods."""
return os.path.relpath(path, os.getcwd())[:-3].replace('/', '.')
base_path = os.path.join(os.getcwd(), test_path or '')
result = []
for root in os.listdir(base_path):
if any([s in root for s in ['.git', 'third_party', 'core/tests']]):
continue
if root.endswith('_test.py'):
result.append(_convert_to_test_target(
os.path.join(base_path, root)))
for subroot, _, files in os.walk(os.path.join(base_path, root)):
for f in files:
if (f.endswith('_test.py') and
os.path.join('core', 'tests') not in subroot):
result.append(_convert_to_test_target(
os.path.join(subroot, f)))
return result
def main():
"""Run the tests."""
parsed_args = _PARSER.parse_args()
if parsed_args.test_target and parsed_args.test_path:
raise Exception('At most one of test_path and test_target '
'should be specified.')
if parsed_args.test_path and '.' in parsed_args.test_path:
raise Exception('The delimiter in test_path should be a slash (/)')
if parsed_args.test_target and '/' in parsed_args.test_target:
raise Exception('The delimiter in test_target should be a dot (.)')
if parsed_args.test_target:
all_test_targets = [parsed_args.test_target]
else:
all_test_targets = _get_all_test_targets(
test_path=parsed_args.test_path)
# Prepare tasks.
task_to_taskspec = {}
tasks = []
for test_target in all_test_targets:
test = TestingTaskSpec(
test_target, parsed_args.generate_coverage_report)
task = TaskThread(test.run, name=test_target)
task_to_taskspec[task] = test
tasks.append(task)
task_execution_failed = False
try:
_execute_tasks(tasks)
except:
task_execution_failed = True
for task in tasks:
if task.exception:
log(str(task.exception))
print ''
print '+------------------+'
print '| SUMMARY OF TESTS |'
print '+------------------+'
print ''
# Check we ran all tests as expected.
total_count = 0
total_errors = 0
total_failures = 0
for task in tasks:
spec = task_to_taskspec[task]
if not task.finished:
print 'CANCELED %s' % spec.test_target
test_count = 0
elif 'No tests were run' in str(task.exception):
print 'ERROR %s: No tests found.' % spec.test_target
test_count = 0
elif task.exception:
exc_str = str(task.exception).decode('utf-8')
print exc_str[exc_str.find('=') : exc_str.rfind('-')]
tests_failed_regex_match = re.search(
r'Test suite failed: ([0-9]+) tests run, ([0-9]+) errors, '
'([0-9]+) failures',
str(task.exception))
try:
test_count = int(tests_failed_regex_match.group(1))
errors = int(tests_failed_regex_match.group(2))
failures = int(tests_failed_regex_match.group(3))
total_errors += errors
total_failures += failures
print 'FAILED %s: %s errors, %s failures' % (
spec.test_target, errors, failures)
except AttributeError:
# There was an internal error, and the tests did not run. (The
# error message did not match `tests_failed_regex_match`.)
test_count = 0
print ''
print '------------------------------------------------------'
print ' WARNING: FAILED TO RUN TESTS.'
print ''
print ' This is most likely due to an import error.'
print '------------------------------------------------------'
else:
tests_run_regex_match = re.search(
r'Ran ([0-9]+) tests? in ([0-9\.]+)s', task.output)
test_count = int(tests_run_regex_match.group(1))
test_time = float(tests_run_regex_match.group(2))
print ('SUCCESS %s: %d tests (%.1f secs)' %
(spec.test_target, test_count, test_time))
total_count += test_count
print ''
if total_count == 0:
raise Exception('WARNING: No tests were run.')
elif (parsed_args.test_path is None and parsed_args.test_target is None
and total_count != EXPECTED_TEST_COUNT):
raise Exception(
'ERROR: Expected %s tests to be run, not %s.' %
(EXPECTED_TEST_COUNT, total_count))
else:
print 'Ran %s test%s in %s test class%s.' % (
total_count, '' if total_count == 1 else 's',
len(tasks), '' if len(tasks) == 1 else 'es')
if total_errors or total_failures:
print '(%s ERRORS, %s FAILURES)' % (total_errors, total_failures)
else:
print 'All tests passed.'
if task_execution_failed:
raise Exception('Task execution failed.')
elif total_errors or total_failures:
raise Exception(
'%s errors, %s failures' % (total_errors, total_failures))
if __name__ == '__main__':
main()
| apache-2.0 | -3,055,404,723,049,454,600 | 33.302671 | 79 | 0.57154 | false |
DigitalCampus/django-nurhi-oppia | oppia/gamification/models.py | 1 | 2404 | # oppia/gamification/models.py
import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from oppia.models import Course, Activity, Media
from oppia.quiz.models import Quiz
class CourseGamificationEvent(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
created_date = models.DateTimeField('date created', default=timezone.now)
event = models.CharField(max_length=100)
points = models.IntegerField()
class Meta:
verbose_name = _(u'Course Gamification Event')
verbose_name_plural = _(u'Course Gamification Events')
def __unicode__(self):
return self.event
class ActivityGamificationEvent(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
activity = models.ForeignKey(Activity, on_delete=models.CASCADE)
created_date = models.DateTimeField('date created', default=timezone.now)
event = models.CharField(max_length=100)
points = models.IntegerField()
class Meta:
verbose_name = _(u'Activity Gamification Event')
verbose_name_plural = _(u'Activity Gamification Events')
def __unicode__(self):
return self.event
class MediaGamificationEvent(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
media = models.ForeignKey(Media, on_delete=models.CASCADE)
created_date = models.DateTimeField('date created', default=timezone.now)
event = models.CharField(max_length=100)
points = models.IntegerField()
class Meta:
verbose_name = _(u'Media Gamification Event')
verbose_name_plural = _(u'Media Gamification Events')
def __unicode__(self):
return self.event
class QuizGamificationEvent(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
created_date = models.DateTimeField('date created', default=timezone.now)
event = models.CharField(max_length=100)
points = models.IntegerField()
class Meta:
verbose_name = _(u'Quiz Gamification Event')
verbose_name_plural = _(u'Quiz Gamification Events')
def __unicode__(self):
return self.event
| gpl-3.0 | 5,930,698,250,534,488,000 | 32.859155 | 77 | 0.715058 | false |
stephaneAG/Python_tests | pyxhook/stephaneAG_K2000Kit_Module.py | 1 | 4365 | # K2000 KIT Python Module
# to be used in conjonction with the arduinoMicroShiftRegisterTest(s), to produce effect(s) such as K2000 KIT
import time
from collections import deque # used to cycle/rotate the leds deck pattern to be sent over serial to the uC/Ar
# == debug tests ==
'''
larger_list = [0,'A','B','C',1, 1,'F','G', 'H', 0]
#print larger_list
smaller_list = larger_list[1:len(larger_list)-1]
#print smaller_list
deck = deque( smaller_list
#print deck
deck.rotate(1)
#print deck
deck.rotate(-1) # rotate by one to the left
#print deck
'''
config = {
'large_pattern': '0000000000',
'actual_pattern': '00011000',
'direction': 1,
'position': 4,
'deck_len': 2
#'pattern_len': len(config['actual_pattern'])
}
def loopOverConfig():
if config['direction'] == 1:
print 'direction => RIGHT'
deckEndIndex = config['position'] + config['deck_len'] - 1
if deckEndIndex < len(config['large_pattern']):
# can go right
print 'free space on right => TRUE'
large_pattern = config['large_pattern'])
print 'large pattern as list => '
else:
# cannot go right
print 'free space on right => FALSE'
elif if config['direction'] == 0:
print 'direction => LEFT'
if config['position'] > 0:
# can go left
print 'free space on left => TRUE'
else:
# cannot go left
print 'free space on left => FALSE'
# == sketch ==
larger_pattern = '0000000000'
pattern = '00011000'
start_direction = 1 # right
start_position = 4 # index of 1st led of the deck
deck_len = 2 # number of leds on at the same time
current_direction = 1 # 1 = right, 0 = left
current_position = 4
current_pattern = '00000000'
# dirty helper function
def loopK200Kit():
global current_direction
global current_position
global larger_pattern
global current_pattern
global deck_len
# could be done: check the mode & its options ( .. )
# check the direction we're set to go to
if current_direction == 1: # going right
print 'going right'
if current_position + deck_len - 1 < len(larger_pattern):
print 'still free space on the right ..'
large_pattern_list = str(larger_pattern)
# strip the first & last elements of the list
sized_pattern = large_pattern_list[1:len(large_pattern_list)-1]
# convert it to a deque
deck = deque( sized_pattern )
deck.rotate(1)
# increment the current position
current_position += 1
# get back current pattern list from deque
current_pattern_list = list(deque(deck))
# write the current pattern as string, not list
current_pattern = ''.join(current_pattern_list)
# write the updated larger pattern
large_pattern = current_pattern_list
large_pattern[:0] = '0';
large_pattern[len(large_pattern):] = '0'
larger_pattern = str( larger_pattern )
# display the current pattern
print 'pattern: ', current_pattern, ' position: ', current_position
else:
print 'no more free space on the right ..'
current_direction = 0
#return
elif current_direction == 0: #going left
print 'going left'
if current_position > 0:
print 'still free space on the left ..'
large_pattern_list = larger_pattern.split()
# strip the first & last elements of the list
sized_pattern = large_pattern_list[1:len(large_pattern_list)-1]
# convert it to a deque
deck = deque( sized_pattern )
deck.rotate(-1)
# decrement the current position
current_position -= 1
# get back current pattern list from deque
current_pattern_list = list(deque(deck))
# write the current pattern as string, not list
current_pattern = ''.join(current_pattern_list)
# write the updated larger pattern
large_pattern = current_pattern_list
large_pattern[:0] = '0';
large_pattern[len(large_pattern):] = '0'
larger_pattern = str( larger_pattern )
# display the current pattern
print 'pattern: ', current_pattern, ' position: ', current_position
else:
print 'no more free space on the left ..'
current_direction = 1
#return
# infinite loop
while 1 == 1:
loopK200Kit()
time.sleep(2)
print 'the program ended'
| mit | 2,876,575,010,131,056,600 | 28.493243 | 110 | 0.631386 | false |
devartis/django-validated-file | testing/forms.py | 2 | 1142 | from django import forms
from models import TestModel, TestModelNoValidate, TestElement
from validatedfile.fields import QuotaValidator
class TestModelForm(forms.ModelForm):
class Meta:
model = TestModel
class TestModelNoValidateForm(forms.ModelForm):
class Meta:
model = TestModelNoValidate
class TestElementForm(forms.ModelForm):
the_file = forms.FileField(required=False,
validators=[QuotaValidator(max_usage=10000)])
class Meta:
model = TestElement
fields = ['the_file']
def __init__(self, container, *args, **kwargs):
super(TestElementForm, self).__init__(*args, **kwargs)
self.container = container
self.fields['the_file'].validators[0].update_quota(
items=self.container.test_elements.all(),
attr_name='the_file',
)
def exceeds_quota(self):
return self.fields['the_file'].validators[0].quota.exceeds()
def save(self, *args, **kwargs):
element = super(TestElementForm, self).save(commit=False)
element.container = self.container
element.save()
| bsd-3-clause | -1,506,645,572,364,168,700 | 26.853659 | 76 | 0.648862 | false |
cryvate/project-euler | project_euler/library/sequences.py | 1 | 1972 | from itertools import count
from typing import Callable, Iterable, List
from .number_theory.primes import primes_sequence # noqa: F401
def fibonacci_sequence() -> Iterable[int]:
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def collatz_sequence(n: int=13) -> Iterable[int]:
while n > 1:
yield n
if n % 2 == 0:
n //= 2
else:
n *= 3
n += 1
yield 1
def create_polynomial_sequence(coefficients: List[int]) -> \
Callable[[], Iterable[int]]:
# do not create copy of list: can change on the fly to provide flexibility
def polynomial_sequence(start: int=0) -> Iterable[int]:
value = 0
for n in count():
if n >= start:
yield value
power = 1
for coefficient in coefficients:
value += coefficient * power
power *= n
return polynomial_sequence
triangle_sequence = create_polynomial_sequence([1, 1])
square_sequence = create_polynomial_sequence([1, 2])
pentagonal_sequence = create_polynomial_sequence([1, 3])
negative_pentagonal_sequence = create_polynomial_sequence([2, 3])
hexagonal_sequence = create_polynomial_sequence([1, 4])
heptagonal_sequence = create_polynomial_sequence([1, 5])
octagonal_sequence = create_polynomial_sequence([1, 6])
cube_sequence = create_polynomial_sequence([1, 3, 3])
def find_intersection_interval(sequence: Iterable[int],
begin: int=None,
end: int=None,
breaking: bool=True) -> \
Iterable[int]:
for value in sequence:
if end is not None and value >= end:
if breaking:
break
else:
continue # pragma: no cover
# peephole optimizer says not covered, but it is
if begin is not None and value >= begin:
yield value
| mit | 5,979,713,112,935,393,000 | 26.013699 | 78 | 0.567951 | false |
jeremiedecock/snippets | python/pillow/mandelbrot/mandelbrot.py | 1 | 2239 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""A Mandelbrot set demo"""
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import numpy as np
from PIL import Image
REAL_RANGE = np.arange(-2.2, 0.8, 0.01).tolist()
IMAG_RANGE = np.arange(-1.2, 1.2, 0.01).tolist()
EPSILON_MAX = 2.
NUM_IT_MAX = 255
Z_INIT = complex(0, 0)
def mandelbrot(x, y):
it = 0
z = Z_INIT
c = complex(x, y)
# Rem: abs(z) = |z| = math.sqrt(pow(z.imag,2) + pow(z.real,2))
while it < NUM_IT_MAX and abs(z) <= EPSILON_MAX:
z = pow(z, 2) + c
it += 1
# To print all levels
return it
## To print only the level N
#if it < N:
# return 1
#else:
# return 0
def main():
"""Main function"""
# Reverse the y axis as (0,0) is the top left corner in PIL
# (even if the difference is not visible for the Mandelbrot set...)
IMAG_RANGE.reverse()
data = [255 - mandelbrot(x, y) for y in IMAG_RANGE for x in REAL_RANGE]
# Make the image
img = Image.new("L", (len(REAL_RANGE), len(IMAG_RANGE)))
img.putdata(data)
# Save the image
img.save("mandelbrot.png")
if __name__ == '__main__':
main()
| mit | 7,023,459,584,781,753,000 | 29.22973 | 79 | 0.670988 | false |
RedhawkSDR/rtl-demo-app | server/_utils/audio.py | 1 | 3110 | #
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of REDHAWK server.
#
# REDHAWK server 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 3 of the License, or (at your option) any
# later version.
#
# REDHAWK server is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
import struct
import numpy
def wav_hdr(num_channels, sample_rate, sample_width):
'''
Returns a string that is a valid WAVE header. Useful for web streams/sockets.
:param num_channels: 1 = Mono, 2 = Stereo
:param sample_rate:
:param sample_width: bytes per sample, ie 16bit PCM = 2
:return:
'''
chunk_hdr = struct.pack('4si4s',
'RIFF',
0, # Chunk Size
'WAVE')
# fmt chunk
byte_rate = sample_rate * sample_width * num_channels
block_align = num_channels * sample_width
bits_per_sample = sample_width * 8
format_chunk = struct.pack('4sihHIIHH',
'fmt ',
16, # Fmt Sub Chunk Size
1, # AudioFormat (1 = PCM)
num_channels,
sample_rate,
byte_rate,
block_align,
bits_per_sample)
output = chunk_hdr + format_chunk + 'data'
return output
def pcm2wav(data, num_channels, sample_rate):
'''
Converts PCM to Wave format. Converts PCM to 16-bit
:param data:
:param num_channels: 1 = Mono, 2 = Stereo
:param sample_rate:
:return:
'''
# TODO: Handle different data formats. Current implementation just
# casts. Need to handle the more standard normalized floats
sample_width = 2
pcm_data = numpy.array(data).astype('int16')
chunk_hdr = struct.pack('4si4s',
'RIFF',
36 + pcm_data.nbytes, # Chunk Size
'WAVE')
# fmt chunk
byte_rate = sample_rate * sample_width * num_channels
block_align = num_channels * sample_width
bits_per_sample = sample_width * 8
format_chunk = struct.pack('4sihHIIHH',
'fmt ',
16, # Fmt Sub Chunk Size
1, # AudioFormat (1 = PCM)
num_channels,
sample_rate,
byte_rate,
block_align,
bits_per_sample)
output = chunk_hdr + format_chunk + 'data' + pcm_data.tostring()
return output | lgpl-3.0 | -3,399,194,653,128,419,000 | 33.186813 | 81 | 0.56881 | false |
bzamecnik/sms-tools | lectures/04-STFT/plots-code/time-freq-compromise.py | 1 | 1036 | # matplotlib without any blocking GUI
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from smst.utils import audio
from smst.models import stft
(fs, x) = audio.read_wav('../../../sounds/piano.wav')
plt.figure(1, figsize=(9.5, 6))
w = np.hamming(256)
N = 256
H = 128
mX1, pX1 = stft.from_audio(x, w, N, H)
plt.subplot(211)
numFrames = int(mX1.shape[0])
frmTime = H * np.arange(numFrames) / float(fs)
binFreq = np.arange(mX1.shape[1]) * float(fs) / N
plt.pcolormesh(frmTime, binFreq, np.transpose(mX1))
plt.title('mX (piano.wav), M=256, N=256, H=128')
plt.autoscale(tight=True)
w = np.hamming(1024)
N = 1024
H = 128
mX2, pX2 = stft.from_audio(x, w, N, H)
plt.subplot(212)
numFrames = int(mX2.shape[0])
frmTime = H * np.arange(numFrames) / float(fs)
binFreq = np.arange(mX2.shape[1]) * float(fs) / N
plt.pcolormesh(frmTime, binFreq, np.transpose(mX2))
plt.title('mX (piano.wav), M=1024, N=1024, H=128')
plt.autoscale(tight=True)
plt.tight_layout()
plt.savefig('time-freq-compromise.png')
| agpl-3.0 | -8,702,875,251,723,081,000 | 24.268293 | 53 | 0.692085 | false |
JelteF/PyLaTeX | pylatex/document.py | 1 | 14074 | # -*- coding: utf-8 -*-
"""
This module implements the class that deals with the full document.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
import os
import sys
import subprocess
import errno
from .base_classes import Environment, Command, Container, LatexObject, \
UnsafeCommand, SpecialArguments
from .package import Package
from .errors import CompilerError
from .utils import dumps_list, rm_temp_dir, NoEscape
import pylatex.config as cf
class Document(Environment):
r"""
A class that contains a full LaTeX document.
If needed, you can append stuff to the preamble or the packages.
For instance, if you need to use ``\maketitle`` you can add the title,
author and date commands to the preamble to make it work.
"""
def __init__(self, default_filepath='default_filepath', *,
documentclass='article', document_options=None, fontenc='T1',
inputenc='utf8', font_size="normalsize", lmodern=True,
textcomp=True, microtype=None, page_numbers=True, indent=None,
geometry_options=None, data=None):
r"""
Args
----
default_filepath: str
The default path to save files.
documentclass: str or `~.Command`
The LaTeX class of the document.
document_options: str or `list`
The options to supply to the documentclass
fontenc: str
The option for the fontenc package. If it is `None`, the fontenc
package will not be loaded at all.
inputenc: str
The option for the inputenc package. If it is `None`, the inputenc
package will not be loaded at all.
font_size: str
The font size to declare as normalsize
lmodern: bool
Use the Latin Modern font. This is a font that contains more glyphs
than the standard LaTeX font.
textcomp: bool
Adds even more glyphs, for instance the Euro (€) sign.
page_numbers: bool
Adds the ability to add the last page to the document.
indent: bool
Determines whether or not the document requires indentation. If it
is `None` it will use the value from the active config. Which is
`True` by default.
geometry_options: dict
The options to supply to the geometry package
data: list
Initial content of the document.
"""
self.default_filepath = default_filepath
if isinstance(documentclass, Command):
self.documentclass = documentclass
else:
self.documentclass = Command('documentclass',
arguments=documentclass,
options=document_options)
if indent is None:
indent = cf.active.indent
if microtype is None:
microtype = cf.active.microtype
# These variables are used by the __repr__ method
self._fontenc = fontenc
self._inputenc = inputenc
self._lmodern = lmodern
self._indent = indent
self._microtype = microtype
packages = []
if fontenc is not None:
packages.append(Package('fontenc', options=fontenc))
if inputenc is not None:
packages.append(Package('inputenc', options=inputenc))
if lmodern:
packages.append(Package('lmodern'))
if textcomp:
packages.append(Package('textcomp'))
if page_numbers:
packages.append(Package('lastpage'))
if not indent:
packages.append(Package('parskip'))
if microtype:
packages.append(Package('microtype'))
if geometry_options is not None:
packages.append(Package('geometry'))
# Make sure we don't add this options command for an empty list,
# because that breaks.
if geometry_options:
packages.append(Command(
'geometry',
arguments=SpecialArguments(geometry_options),
))
super().__init__(data=data)
# Usually the name is the class name, but if we create our own
# document class, \begin{document} gets messed up.
self._latex_name = 'document'
self.packages |= packages
self.variables = []
self.preamble = []
if not page_numbers:
self.change_document_style("empty")
# No colors have been added to the document yet
self.color = False
self.meta_data = False
self.append(Command(command=font_size))
def _propagate_packages(self):
r"""Propogate packages.
Make sure that all the packages included in the previous containers
are part of the full list of packages.
"""
super()._propagate_packages()
for item in (self.preamble):
if isinstance(item, LatexObject):
if isinstance(item, Container):
item._propagate_packages()
for p in item.packages:
self.packages.add(p)
def dumps(self):
"""Represent the document as a string in LaTeX syntax.
Returns
-------
str
"""
head = self.documentclass.dumps() + '%\n'
head += self.dumps_packages() + '%\n'
head += dumps_list(self.variables) + '%\n'
head += dumps_list(self.preamble) + '%\n'
return head + '%\n' + super().dumps()
def generate_tex(self, filepath=None):
"""Generate a .tex file for the document.
Args
----
filepath: str
The name of the file (without .tex), if this is not supplied the
default filepath attribute is used as the path.
"""
super().generate_tex(self._select_filepath(filepath))
def generate_pdf(self, filepath=None, *, clean=True, clean_tex=True,
compiler=None, compiler_args=None, silent=True):
"""Generate a pdf file from the document.
Args
----
filepath: str
The name of the file (without .pdf), if it is `None` the
``default_filepath`` attribute will be used.
clean: bool
Whether non-pdf files created that are created during compilation
should be removed.
clean_tex: bool
Also remove the generated tex file.
compiler: `str` or `None`
The name of the LaTeX compiler to use. If it is None, PyLaTeX will
choose a fitting one on its own. Starting with ``latexmk`` and then
``pdflatex``.
compiler_args: `list` or `None`
Extra arguments that should be passed to the LaTeX compiler. If
this is None it defaults to an empty list.
silent: bool
Whether to hide compiler output
"""
if compiler_args is None:
compiler_args = []
# In case of newer python with the use of the cwd parameter
# one can avoid to physically change the directory
# to the destination folder
python_cwd_available = sys.version_info >= (3, 6)
filepath = self._select_filepath(filepath)
if not os.path.basename(filepath):
filepath = os.path.join(os.path.abspath(filepath),
'default_basename')
else:
filepath = os.path.abspath(filepath)
cur_dir = os.getcwd()
dest_dir = os.path.dirname(filepath)
if not python_cwd_available:
os.chdir(dest_dir)
self.generate_tex(filepath)
if compiler is not None:
compilers = ((compiler, []),)
else:
latexmk_args = ['--pdf']
compilers = (
('latexmk', latexmk_args),
('pdflatex', [])
)
main_arguments = ['--interaction=nonstopmode', filepath + '.tex']
check_output_kwargs = {}
if python_cwd_available:
check_output_kwargs = {'cwd': dest_dir}
os_error = None
for compiler, arguments in compilers:
command = [compiler] + arguments + compiler_args + main_arguments
try:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT,
**check_output_kwargs)
except (OSError, IOError) as e:
# Use FileNotFoundError when python 2 is dropped
os_error = e
if os_error.errno == errno.ENOENT:
# If compiler does not exist, try next in the list
continue
raise
except subprocess.CalledProcessError as e:
# For all other errors print the output and raise the error
print(e.output.decode())
raise
else:
if not silent:
print(output.decode())
if clean:
try:
# Try latexmk cleaning first
subprocess.check_output(['latexmk', '-c', filepath],
stderr=subprocess.STDOUT,
**check_output_kwargs)
except (OSError, IOError, subprocess.CalledProcessError):
# Otherwise just remove some file extensions.
extensions = ['aux', 'log', 'out', 'fls',
'fdb_latexmk']
for ext in extensions:
try:
os.remove(filepath + '.' + ext)
except (OSError, IOError) as e:
# Use FileNotFoundError when python 2 is dropped
if e.errno != errno.ENOENT:
raise
rm_temp_dir()
if clean_tex:
os.remove(filepath + '.tex') # Remove generated tex file
# Compilation has finished, so no further compilers have to be
# tried
break
else:
# Notify user that none of the compilers worked.
raise(CompilerError(
'No LaTex compiler was found\n'
'Either specify a LaTex compiler '
'or make sure you have latexmk or pdfLaTex installed.'
))
if not python_cwd_available:
os.chdir(cur_dir)
def _select_filepath(self, filepath):
"""Make a choice between ``filepath`` and ``self.default_filepath``.
Args
----
filepath: str
the filepath to be compared with ``self.default_filepath``
Returns
-------
str
The selected filepath
"""
if filepath is None:
return self.default_filepath
else:
if os.path.basename(filepath) == '':
filepath = os.path.join(filepath, os.path.basename(
self.default_filepath))
return filepath
def change_page_style(self, style):
r"""Alternate page styles of the current page.
Args
----
style: str
value to set for the page style of the current page
"""
self.append(Command("thispagestyle", arguments=style))
def change_document_style(self, style):
r"""Alternate page style for the entire document.
Args
----
style: str
value to set for the document style
"""
self.append(Command("pagestyle", arguments=style))
def add_color(self, name, model, description):
r"""Add a color that can be used throughout the document.
Args
----
name: str
Name to set for the color
model: str
The color model to use when defining the color
description: str
The values to use to define the color
"""
if self.color is False:
self.packages.append(Package("color"))
self.color = True
self.preamble.append(Command("definecolor", arguments=[name,
model,
description]))
def change_length(self, parameter, value):
r"""Change the length of a certain parameter to a certain value.
Args
----
parameter: str
The name of the parameter to change the length for
value: str
The value to set the parameter to
"""
self.preamble.append(UnsafeCommand('setlength',
arguments=[parameter, value]))
def set_variable(self, name, value):
r"""Add a variable which can be used inside the document.
Variables are defined before the preamble. If a variable with that name
has already been set, the new value will override it for future uses.
This is done by appending ``\renewcommand`` to the document.
Args
----
name: str
The name to set for the variable
value: str
The value to set for the variable
"""
name_arg = "\\" + name
variable_exists = False
for variable in self.variables:
if name_arg == variable.arguments._positional_args[0]:
variable_exists = True
break
if variable_exists:
renew = Command(command="renewcommand",
arguments=[NoEscape(name_arg), value])
self.append(renew)
else:
new = Command(command="newcommand",
arguments=[NoEscape(name_arg), value])
self.variables.append(new)
| mit | -4,159,063,675,102,418,000 | 32.826923 | 79 | 0.541146 | false |
haogefeifei/OdooQuant | source/addons/stock_robot/easytrader/yhtrader.py | 1 | 10923 | # coding: utf-8
from __future__ import division
import json
import os
import random
import re
import requests
from . import helpers
from .webtrader import WebTrader, NotLoginError
log = helpers.get_logger(__file__)
VERIFY_CODE_POS = 0
TRADE_MARKET = 1
HOLDER_NAME = 0
class YHTrader(WebTrader):
config_path = os.path.dirname(__file__) + '/config/yh.json'
def __init__(self):
super(YHTrader, self).__init__()
self.cookie = None
self.account_config = None
self.s = None
self.exchange_stock_account = dict()
def login(self, throw=False):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
}
if self.s is not None:
self.s.get(self.config['logout_api'])
self.s = requests.session()
self.s.headers.update(headers)
data = self.s.get(self.config['login_page'])
# 查找验证码
search_result = re.search(r'src=\"verifyCodeImage.jsp\?rd=([0-9]{4})\"', data.text)
if not search_result:
log.debug("Can not find verify code, stop login")
return False
verify_code = search_result.groups()[VERIFY_CODE_POS]
if not verify_code:
return False
login_status, result = self.post_login_data(verify_code)
if login_status is False and throw:
raise NotLoginError(result)
exchangeinfo = list((self.do(dict(self.config['account4stock']))))
if len(exchangeinfo) >= 2:
for i in range(2):
if exchangeinfo[i][TRADE_MARKET]['交易市场'] == '深A':
self.exchange_stock_account['0'] = exchangeinfo[i][HOLDER_NAME]['股东代码'][0:10]
else:
self.exchange_stock_account['1'] = exchangeinfo[i][HOLDER_NAME]['股东代码'][0:10]
return login_status
def post_login_data(self, verify_code):
login_params = dict(
self.config['login'],
mac=helpers.get_mac(),
clientip='',
inputaccount=self.account_config['inputaccount'],
trdpwd=self.account_config['trdpwd'],
checkword=verify_code
)
log.debug('login params: %s' % login_params)
login_response = self.s.post(self.config['login_api'], params=login_params)
log.debug('login response: %s' % login_response.text)
if login_response.text.find('success') != -1:
return True, None
return False, login_response.text
@property
def token(self):
return self.cookie['JSESSIONID']
@token.setter
def token(self, token):
self.cookie = dict(JSESSIONID=token)
self.keepalive()
def cancel_entrust(self, entrust_no, stock_code):
"""撤单
:param entrust_no: 委托单号
:param stock_code: 股票代码"""
need_info = self.__get_trade_need_info(stock_code)
cancel_params = dict(
self.config['cancel_entrust'],
orderSno=entrust_no,
secuid=need_info['stock_account']
)
cancel_response = self.s.post(self.config['trade_api'], params=cancel_params)
log.debug('cancel trust: %s' % cancel_response.text)
return True
# TODO: 实现买入卖出的各种委托类型
def buy(self, stock_code, price, amount=0, volume=0, entrust_prop=0):
"""买入股票
:param stock_code: 股票代码
:param price: 买入价格
:param amount: 买入股数
:param volume: 买入总金额 由 volume / price 取整, 若指定 price 则此参数无效
:param entrust_prop: 委托类型,暂未实现,默认为限价委托
"""
params = dict(
self.config['buy'],
bsflag='0B', # 买入0B 卖出0S
qty=amount if amount else volume // price // 100 * 100
)
return self.__trade(stock_code, price, entrust_prop=entrust_prop, other=params)
def sell(self, stock_code, price, amount=0, volume=0, entrust_prop=0):
"""卖出股票
:param stock_code: 股票代码
:param price: 卖出价格
:param amount: 卖出股数
:param volume: 卖出总金额 由 volume / price 取整, 若指定 amount 则此参数无效
:param entrust_prop: 委托类型,暂未实现,默认为限价委托
"""
params = dict(
self.config['sell'],
bsflag='0S', # 买入0B 卖出0S
qty=amount if amount else volume // price
)
return self.__trade(stock_code, price, entrust_prop=entrust_prop, other=params)
def fundpurchase(self, stock_code, amount=0):
"""基金申购
:param stock_code: 基金代码
:param amount: 申购份额
"""
params = dict(
self.config['fundpurchase'],
price=1, # 价格默认为1
qty=amount
)
return self.__tradefund(stock_code, other=params)
def fundredemption(self, stock_code, amount=0):
"""基金赎回
:param stock_code: 基金代码
:param amount: 赎回份额
"""
params = dict(
self.config['fundredemption'],
price=1, # 价格默认为1
qty=amount
)
return self.__tradefund(stock_code, other=params)
def fundsubscribe(self, stock_code, amount=0):
"""基金认购
:param stock_code: 基金代码
:param amount: 认购份额
"""
params = dict(
self.config['fundsubscribe'],
price=1, # 价格默认为1
qty=amount
)
return self.__tradefund(stock_code, other=params)
def fundsplit(self, stock_code, amount=0):
"""基金分拆
:param stock_code: 母份额基金代码
:param amount: 分拆份额
"""
params = dict(
self.config['fundsplit'],
qty=amount
)
return self.__tradefund(stock_code, other=params)
def fundmerge(self, stock_code, amount=0):
"""基金合并
:param stock_code: 母份额基金代码
:param amount: 合并份额
"""
params = dict(
self.config['fundmerge'],
qty=amount
)
return self.__tradefund(stock_code, other=params)
def __tradefund(self, stock_code, other):
# 检查是否已经掉线
if not self.heart_thread.is_alive():
check_data = self.get_balance()
if type(check_data) == dict:
return check_data
need_info = self.__get_trade_need_info(stock_code)
trade_params = dict(
other,
stockCode=stock_code,
market=need_info['exchange_type'],
secuid=need_info['stock_account']
)
trade_response = self.s.post(self.config['trade_api'], params=trade_params)
log.debug('trade response: %s' % trade_response.text)
return True
def __trade(self, stock_code, price, entrust_prop, other):
# 检查是否已经掉线
if not self.heart_thread.is_alive():
check_data = self.get_balance()
if type(check_data) == dict:
return check_data
need_info = self.__get_trade_need_info(stock_code)
trade_params = dict(
other,
stockCode=stock_code,
price=price,
market=need_info['exchange_type'],
secuid=need_info['stock_account']
)
trade_response = self.s.post(self.config['trade_api'], params=trade_params)
log.debug('trade response: %s' % trade_response.text)
return trade_response.text
def __get_trade_need_info(self, stock_code):
"""获取股票对应的证券市场和帐号"""
# 获取股票对应的证券市场
sh_exchange_type = '1'
sz_exchange_type = '0'
exchange_type = sh_exchange_type if helpers.get_stock_type(stock_code) == 'sh' else sz_exchange_type
return dict(
exchange_type=exchange_type,
stock_account=self.exchange_stock_account[exchange_type]
)
def create_basic_params(self):
basic_params = dict(
CSRF_Token='undefined',
timestamp=random.random(),
)
return basic_params
def request(self, params):
url = self.trade_prefix + params['service_jsp']
r = self.s.get(url, cookies=self.cookie)
if params['service_jsp'] == '/trade/webtrade/stock/stock_zjgf_query.jsp':
if params['service_type'] == 2:
rptext = r.text[0:r.text.find('操作')]
return rptext
else:
rbtext = r.text[r.text.find('操作'):]
rbtext += 'yhposition'
return rbtext
else:
return r.text
def format_response_data(self, data):
# 需要对于银河持仓情况特殊处理
if data.find('yhposition') != -1:
search_result_name = re.findall(r'<td nowrap=\"nowrap\" class=\"head(?:\w{0,5})\">(.*)</td>', data)
search_result_content = re.findall(r'<td nowrap=\"nowrap\" >(.*)</td>', data)
search_result_name.remove('参考成本价')
else:
# 获取原始data的html源码并且解析得到一个可读json格式
search_result_name = re.findall(r'<td nowrap=\"nowrap\" class=\"head(?:\w{0,5})\">(.*)</td>', data)
search_result_content = re.findall(r'<td nowrap=\"nowrap\">(.*) </td>', data)
columnlen = len(search_result_name)
if columnlen == 0 or len(search_result_content) % columnlen != 0:
log.error("Can not fetch balance info")
retdata = json.dumps(search_result_name)
retjsonobj = json.loads(retdata)
else:
rowlen = len(search_result_content) // columnlen
retdata = list()
for i in range(rowlen):
retrowdata = list()
for j in range(columnlen):
retdict = dict()
retdict[search_result_name[j]] = search_result_content[i * columnlen + j]
retrowdata.append(retdict)
retdata.append(retrowdata)
retlist = json.dumps(retdata)
retjsonobj = json.loads(retlist)
return retjsonobj
def fix_error_data(self, data):
return data
def check_login_status(self, return_data):
pass
def check_account_live(self, response):
if hasattr(response, 'get') and response.get('error_no') == '-1':
self.heart_active = False
| gpl-3.0 | -5,166,581,767,201,438,000 | 33.424749 | 111 | 0.546779 | false |
shoopio/shoop | shuup/admin/views/search.py | 2 | 1878 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2019, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from itertools import chain
from django.http.response import JsonResponse
from django.views.generic import View
from shuup.admin.base import SearchResult
from shuup.admin.module_registry import get_modules
from shuup.admin.utils.permissions import get_missing_permissions
from shuup.admin.utils.search import FuzzyMatcher
def get_search_results(request, query):
fuzzer = FuzzyMatcher(query)
normal_results = []
menu_entry_results = []
for module in get_modules():
if get_missing_permissions(request.user, module.get_required_permissions()):
continue
normal_results.extend(module.get_search_results(request, query) or ())
for menu_entry in module.get_menu_entries(request) or ():
texts = (menu_entry.get_search_query_texts() or ())
if any(fuzzer.test(text) for text in texts):
menu_entry_results.append(SearchResult(
text=menu_entry.text,
url=menu_entry.url,
icon=menu_entry.icon,
category=menu_entry.category,
relevance=90,
is_action=True
))
results = sorted(
chain(normal_results, menu_entry_results),
key=lambda r: r.relevance,
reverse=True
)
return results
class SearchView(View):
def get(self, request, *args, **kwargs):
query = request.GET.get("q")
if query:
results = get_search_results(request, query)
else:
results = []
return JsonResponse({"results": [r.to_json() for r in results]})
| agpl-3.0 | 4,093,824,704,880,380,000 | 33.777778 | 84 | 0.629393 | false |
OpenFlocks/snippy_the_sheep | develop/software/tests/test_dc_motors.py | 1 | 1711 | #!/usr/bin/python
import ConfigParser
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
cfg = ConfigParser.ConfigParser()
cfg.read("../config_rpi_1_model_b.ini")
motor_1_speed_pin = int(cfg.get('motor_pins', 'motor_1_speed_pin'))
motor_1_direction_pin = int(cfg.get('motor_pins', 'motor_1_direction_pin'))
motor_2_speed_pin = int(cfg.get('motor_pins', 'motor_2_speed_pin'))
motor_2_direction_pin = int(cfg.get('motor_pins', 'motor_2_direction_pin'))
GPIO.setup(motor_1_speed_pin, GPIO.OUT)
GPIO.setup(motor_1_direction_pin, GPIO.OUT)
GPIO.setup(motor_2_speed_pin, GPIO.OUT)
GPIO.setup(motor_2_direction_pin, GPIO.OUT)
def forward():
GPIO.output(motor_1_direction_pin, GPIO.LOW) # 0 == fwd, 1 == rev.
GPIO.output(motor_1_speed_pin, 127) # 0 == stop, 255 == fastest.
GPIO.output(motor_2_direction_pin, GPIO.LOW) # 0 == fwd, 1 == rev.
GPIO.output(motor_2_speed_pin, 127) # 0 == stop, 255 == fastest.
def reverse():
GPIO.output(motor_1_direction_pin, GPIO.HIGH) # 0 == fwd, 1 == rev.
GPIO.output(motor_1_speed_pin, 127) # 0 == stop, 255 == fastest.
GPIO.output(motor_2_direction_pin, GPIO.HIGH) # 0 == fwd, 1 == rev.
GPIO.output(motor_2_speed_pin, 127) # 0 == stop, 255 == fastest.
def stop():
GPIO.output(motor_1_direction_pin, GPIO.LOW) # 0 == fwd, 1 == rev.
GPIO.output(motor_1_speed_pin, 0) # 0 == stop, 255 == fastest.
GPIO.output(motor_2_direction_pin, GPIO.LOW) # 0 == fwd, 1 == rev.
GPIO.output(motor_2_speed_pin, 0) # 0 == stop, 255 == fastest.
while True:
cmd = raw_input("Enter f (forward) or r (reverse) or s (stop): ")
direction = cmd[0]
if direction == "f":
forward()
if direction == "r":
reverse()
if direction == "s":
stop()
| bsd-3-clause | -4,239,789,758,413,233,700 | 33.22 | 75 | 0.662186 | false |
mrjackv/bitsc | modules/temperature_sensor.py | 1 | 5063 | """
Copyright 2016 Raffaele Di Campli
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
#module for reading and managing temperature sensors
import paho.mqtt.client as mqtt_client
from bitsc_common import *
from bitsc_common.conf import conf_dict
import wiringpi
import logging, time, json
logger = logging.getLogger()
temps = []
if __name__ == "__main__":
init()
def init():
"intializes the module"
logger.info("Temperature module loaded")
client = mqtt_client.Client(id="temperature_sensor",clean_session=False)
client.username_pw_set(conf_dict['MQTT']['sensor_usr_rw'],
conf_dict['MQTT']['sensor_pw_rw'])
client.on_connect = on_connect
client.on_message = on_message
client.connect(conf_dict['MQTT']['ip'], int(conf_dict['MQTT']['port']))
"mqtt's message dispatcher"
client.loop_start()
#i2cdetect -y 1 to get the device id
if wiringpi.wiringPiI2CSetup(0x2) == -1:
logger.error("Error while initializing I2C communication")
sensor = TempSensor(read_i2c)
while true:
"this main loop should be moved in an indipendent function somehow"
sensor.update()
temps = sensor.get_data()
logger.debug(sensor.get_data())
client.publish("sede/sensors/{}/temperature".format(sensor.name),temps["value"]["temperature"], retain=True)
client.publish("sede/sensors/{}/humidity".format(sensor.name),temps["value"]["humidity"], retain=True)
time.sleep(60*5)#every 5 minutes updates the sensor
def read_i2c():
"Reads data from a I2C bus with the specified address on the specified bus"
wiringpi.wiringPiI2CWrite(0x2,0xF3)#sends read temperature command (no hold)
temp = wiringpi.wiringPiI2CRead(0x2)
temp = -46.85+175.72*temp/2**16 #normalizes the value according to the HTU21D GY21 datasheet
wiringpi.wiringPiI2CWrite(0x2,0xF5) #sends read humidity command (no hold)
humidity = wiringpi.wiringPiI2CRead(0x2)
humidity = -6+125*humidity/2**16 #normalizes humidity
return {"temperature":temp,"humidity":humidity}
def on_connect(client, userdata, flags, rc):
"mqtt callback"
if not rc:
logger.info("Temperature module connected with result code:{}".format(rc))
#client.subscribe("sede/sensors//temperature") #must implement into a config
else:
logger.error("Connection failed with RC {}".format(rc))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
"mqtt's callback"
parsed_msg = json.loads(msg)
if parsed_msg["id"] == "temperature_sensor":
""" if parsed_msg["cmd"] == "get_temps":
client.publish("sede/sensors//temperature",temps,retain=True)#must implement into a config"""
logger.debug("Temperature sensor received {}".format(parsed_msg))
class TempSensorMan():
"simple class used for managing the temperature sensors"
def __init__(self ):
self.sensors = set()
def register_sensor(self,sensor):
logger.info("Sensor: %s registered", sensor.name)
if not self.sensors.add(sensor):
logger.warning("Duplicated temperature sensor entry: ignoring")
def unregister_sensor(self,name):
for sensor in self.sensors:
if sensor.name == name:
self.sensors.remove(sensor)
def get_data(self):
logger.info("Getting temperature sensor's data");
data = []
for sensor in self.sensors:
data.append(sensor.getData())
return data
def update_sensors(self):
logger.info("Updating temperature sensors' data ...")
for sensor in self.sensors:
sensor.update()
class TempSensor():
def __init__(self,data_source,name="Temperature Sensor",unit="C"):
"data_source must be a function that returns the sensors data"
self.unit = unit
self.name = name
self.value = []
self.data_source = data_source
self.accepted_units = set(['C','F','K'])
def get_data(self):
"fetches the data from the physical sensor through the specified data source (function)"
data = {
"name":self.name,
"value":self.value,
"unit":self.unit
}
return data
def set_unit(self,unit):
"unit must be C, K or F"
if unit in self.accepted_units:
self.unit = unit
def update(self):
"updates the sensor's value"
self.value = self.data_source()
logger.info("Temperature Sensor: %s updated", self.name)
| apache-2.0 | -4,475,417,336,419,897,300 | 35.42446 | 116 | 0.663046 | false |
TylerTemp/tomorrow | lib/hdlr/jolla/article.py | 1 | 2576 | import tornado.web
import tornado.escape
import logging
import base64
try:
from urllib.parse import unquote, quote, urlsplit
except ImportError:
from urllib import quote
from urlparse import unquote, urlsplit
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
import pymongo
from .base import BaseHandler
from lib.db.jolla import Article, Author, User, Redirect, Comment
from lib.tool.timetool import w3c_datetime_full, timestamp_readable
try:
import hashlib
except ImportError:
import md5
def str_to_md5_str(content):
return base64.urlsafe_b64encode(md5.new(content.encode('utf-8')).digest())
else:
def str_to_md5_str(content):
return base64.urlsafe_b64encode(hashlib.md5(content.encode('utf-8')).digest())
class ArticleHandler(BaseHandler):
logger = logging.getLogger('jolla.article')
def get(self, slug):
slug = unquote(slug)
red = Redirect(slug)
if red:
return self.redirect('/%s/' % red.target, red.permanent)
lang = self.locale.code[:2].lower()
article = Article(slug, lang)
if not article:
raise tornado.web.HTTPError(404, "article %s not found" % slug)
if not article.lang_fit():
article.lang = article.other_lang()
author = self.get_author(article)
source = self.get_source(article)
comments = self.get_comments(article)
return self.render(
'jolla/article.html',
article=article,
comments=comments,
author=author,
source=source,
md2html=self.md2html,
escape=tornado.escape.xhtml_escape,
make_source=self.make_source,
F_w3c_datetime_full=w3c_datetime_full,
F_timestamp_readable=timestamp_readable,
)
def get_author(self, article):
author = User(article.author, article.lang)
return author
def get_source(self, article):
source = article.source
if source:
author = source['author']
source['author'] = Author(author)
return source
def get_comments(self, article):
article_id = article._id
sort = (
('create_time', pymongo.DESCENDING),
)
comments = Comment.find({'article_id': article_id}, _sort=sort)
for comment in comments:
comment.update({
'avatar_slug': str_to_md5_str(comment.ip),
})
yield comment
| gpl-3.0 | 6,466,615,259,091,580,000 | 26.404255 | 86 | 0.619565 | false |
hammerlab/kubeface | kubeface/stringable.py | 1 | 4353 | import collections
import string
from os.path import commonprefix
import parse
FORMATTER = string.Formatter()
class Stringable(object):
def __init__(self, name, template, valid_values={}):
self.template_pieces = []
self.field_names = []
parsed = FORMATTER.parse(template)
for (literal_text, field_name, format_spec, conversion) in parsed:
assert not conversion
self.template_pieces.append((literal_text, field_name))
if field_name not in self.field_names:
self.field_names.append(field_name)
self.name = name
self.template = template
self.compiled_template = parse.compile(template)
self.tuple_class = collections.namedtuple(
self.name,
list(self.field_names))
self.valid_values = dict(valid_values)
for key in self.valid_values:
assert key in self.field_names
def make_tuple(self, string_value=None, **kwargs):
if string_value is not None:
assert not kwargs
parsed = self.compiled_template.parse(string_value)
if parsed is None:
raise ValueError(
"Stringable [%s]: Couldn't parse '%s' according to "
"template '%s'" % (
self.name, string_value, self.template))
assert not parsed.fixed
fields_dict = parsed.named
else:
fields_dict = kwargs
self.check_fields(**fields_dict)
return self.tuple_class(**fields_dict)
def check_fields(self, **fields_dict):
assert set(fields_dict) == set(self.field_names), (
"%s: passed fields %s != expected fields %s" % (
self.name, set(fields_dict), set(self.field_names)))
for (key, values) in self.valid_values.items():
if fields_dict[key] not in values:
raise RuntimeError(
"Invalid value %s='%s', must be one of %s." % (
key, fields_dict[key], ', '.join(values)))
def make_string(self, tpl=None, **fields_dict):
if tpl is not None:
assert not fields_dict
fields_dict = tpl._asdict()
self.check_fields(**fields_dict)
return self.template.format(**fields_dict)
def prefix(self, **fields_dict):
(prefix,) = self.prefixes(**fields_dict)
return prefix
def prefixes(self, max_prefixes=1, **fields_dict):
for (key, value) in fields_dict.items():
assert key in self.field_names, key
assert value is None or isinstance(value, list), type(value)
def make_prefixes(
template_pieces,
max_prefixes=max_prefixes,
fields_dict=fields_dict):
result = [[]]
if not template_pieces:
return result
(literal, field_name) = template_pieces[0]
if literal:
for piece in result:
piece.append(literal)
values = fields_dict.get(field_name)
if values is None:
values = self.valid_values.get(field_name)
if values is not None:
if len(result) * len(values) > max_prefixes:
common_prefix = commonprefix(values)
for piece in result:
piece.append(common_prefix)
else:
new_result = []
for value in values:
new_fields_dict = dict(fields_dict)
new_fields_dict[field_name] = [value]
rest = make_prefixes(
template_pieces[1:],
max_prefixes=max_prefixes / (
len(result) * len(values)),
fields_dict=new_fields_dict)
for some_rest in rest:
new_result.extend(
[x + [value] + some_rest for x in result])
result = new_result
return result
prefix_components = make_prefixes(self.template_pieces)
assert len(prefix_components) <= max_prefixes
return [''.join(x) for x in prefix_components]
| apache-2.0 | -6,636,093,332,887,671,000 | 37.522124 | 74 | 0.525155 | false |
ggear/cloudera-framework | cloudera-framework-assembly/src/main/assembly/root/lib/manager/python/benchmark.py | 1 | 13527 | #!/usr/local/bin/python -u
'''
Provide a Cloudera Manager benchmark pipeline
Usage: %s [options]
Options:
-h --help Show help
--user=<cloudera-user> The Cloudera services user
Defaults to 'admin'
--password=<cloudera-password> The Cloudera services password
Defaults to 'admin'
--man_host=<manager-host> Specify a Cloudera Manager Server host
Defaults to 'localhost'
--man_port=<manager-port> Override the default Cloudera Manager Server port
Defaults to '7180'
--nav_host=<navigator-host> Specify a Cloudera Navigator Server host
Defaults to 'localhost'
--nav_port=<navigator-port> Override the default Cloudera Navigator Server port
Defaults to '7187'
--app_name=<app-name> The application name
Required, defaults to None
--app_version=<app-version> The application version
Required, defaults to None
--app_time=<app-time-seconds> The application duration time in seconds
Required, defaults to None
--app_start=<app-start-epoch-seconds> The application start epoch in seconds
Required, defaults to None
--app_end=<app-end-epoch-seconds> The application end epoch in seconds
Required, defaults to None
--app_dashboard=<app-dashboard-file> The application dashboard file
Required, defaults to None
'''
import datetime
import getopt
import inspect
import json
import logging
import sys
import textwrap
import urllib
import requests
from cm_api.api_client import ApiResource, ApiException
from cm_api.endpoints.dashboards import ApiDashboard, create_dashboards
from tabulate import tabulate
LOG = logging.getLogger(__name__)
NAV_API_VERSION = 9
MAN_API_VERSION = 13 # Do not use api_client.API_CURRENT_VERSION, it is often +1 current production version
def update_metadata(user, password, nav_host, nav_port, app_namespace, property_namespace, properties, app_report_only):
requests.post(nav_uri(nav_host, nav_port, 'models/namespaces'), \
auth=(user, password), data='{"name":"' + property_namespace + '","description":"' + property_namespace + ' Metadata"}')
for property in properties:
requests.post(nav_uri(nav_host, nav_port, 'models/namespaces/' + property_namespace + '/properties'), \
auth=(user, password), data='{"name":"' + property['name'] + '","description":"' + property[
'description'] + '","namespace":"' + property_namespace + '","multiValued":true,"type":"TEXT"}')
requests.post(nav_uri(nav_host, nav_port, 'models/packages/nav/classes/hv_database/properties'), \
auth=(user, password), data='[{"name":"' + property['name'] + '","namespace":"' + property_namespace + '"}]')
app_database = ''
try:
app_database = requests.get(nav_uri(nav_host, nav_port, 'entities/?query=' + app_namespace +
'%20%26%26%20type%3Adatabase&limit=1&offset=0'), \
auth=(user, password)).json()[0]['identity']
except IndexError:
pass
if not app_database == '':
try:
property_values = requests.get(nav_uri(nav_host, nav_port, 'entities/' + app_database), \
auth=(user, password)).json()['customProperties'][property_namespace]
except KeyError:
property_values = {}
for property in properties:
for property_name in property['value']:
if property_name in property_values:
property_values[property_name] = property_values[property_name] + property['value'][property_name]
else:
property_values[property_name] = property['value'][property_name]
if not app_report_only:
requests.put(nav_uri(nav_host, nav_port, 'entities/' + app_database), \
auth=(user, password),
data='{"customProperties":{"' + property_namespace + '":' + json.dumps(property_values) + '}}')
app_properties = {'database': app_database, 'properties': []}
app_entities = requests.get(
nav_uri(nav_host, nav_port, 'entities/?query=' + app_namespace.split('_')[0] +
'*%20%26%26%20type%3Adatabase&limit=9999&offset=0'), \
auth=(user, password)).json()
for app_entities_properties in app_entities:
try:
app_properties['properties'].append(app_entities_properties['customProperties'][property_namespace])
except TypeError:
pass
except KeyError:
pass
return app_properties
def nav_uri(nav_host, nav_port, path):
return 'http://' + nav_host + ':' + str(nav_port) + '/api/v' + str(NAV_API_VERSION) + '/' + path
def compress_bins(bins, normalising_factor):
bins_num = 0
bins_sum = 0
for bin in bins:
bins_num += 1
bins_sum += bin.value / normalising_factor
if bins_num == 0:
return 0
return int(bins_sum / bins_num)
def do_call(user, password, man_host, man_port, nav_host, nav_port, app_name, app_version, app_namespace, app_time, app_start, app_end,
app_dashboard,
app_report_only):
cpu = 0
hdfs = 0
network = 0
if app_report_only:
app_start = '0'
app_end = '0'
dashboard_name = 'Release (' + app_namespace + ')'
if not app_report_only:
api = ApiResource(man_host, man_port, user, password, False, MAN_API_VERSION)
with open(app_dashboard, 'r') as dashboard_data_file:
dashboard_data = dashboard_data_file.read()
try:
create_dashboards(api, [ApiDashboard(api, dashboard_name, dashboard_data)])
except ApiException:
pass
for view_plot in json.loads(dashboard_data)['viewPlots']:
for key, value in view_plot['plot'].items():
if key == 'tsquery':
for time_series in \
api.query_timeseries(value, datetime.datetime.fromtimestamp(float(app_start)),
datetime.datetime.fromtimestamp(float(app_end)))[
0].timeSeries:
if time_series.metadata.metricName == 'cpu_percent_across_hosts':
cpu = compress_bins(time_series.data, 1)
if time_series.metadata.metricName == 'total_bytes_read_rate_across_datanodes':
hdfs += compress_bins(time_series.data, 100000)
if time_series.metadata.metricName == 'total_bytes_written_rate_across_datanodes':
hdfs += compress_bins(time_series.data, 100000)
if time_series.metadata.metricName == 'total_bytes_receive_rate_across_network_interfaces':
network += compress_bins(time_series.data, 100000)
if time_series.metadata.metricName == 'total_bytes_transmit_rate_across_network_interfaces':
network += compress_bins(time_series.data, 100000)
properties = [ \
{'name': 'Name', 'description': 'Application name', 'value': {'Name': [app_name]}}, \
{'name': 'Version', 'description': 'Application version', 'value': {'Version': [app_version]}}, \
{'name': 'Run', 'description': 'Run time', 'value': {'Run': [app_time]}}, \
{'name': 'Start', 'description': 'Start time', 'value': {'Start': [app_start + '000']}}, \
{'name': 'Finish', 'description': 'Finish time', 'value': {'Finish': [app_end + '000']}}, \
{'name': 'CPU', 'description': 'Relative CPU usage during benchmark', 'value': {'CPU': [str(cpu)]}}, \
{'name': 'HDFS', 'description': 'Relative HDFS usage during benchmark', 'value': {'HDFS': [str(hdfs)]}}, \
{'name': 'Network', 'description': 'Relative Network usage during benchmark', 'value': {'Network': [str(network)]}} \
]
app_properties = update_metadata(user, password, nav_host, nav_port, app_namespace, 'Benchmark', properties, app_report_only)
app_table_comparison = '{:<15} |{:>15} |{:>15} |{:>15} |{:>15} |{:>15} |{:>15}|'
app_table = [['Application', app_name + '-' + app_version]]
if not app_report_only:
app_table.append(['Run', app_time + 's (' + str((int(app_time) / 60)) + 'm)'])
app_table.append(
['Start', datetime.datetime.fromtimestamp(float(app_start)).strftime('%Y-%m-%d %H:%M:%S') + ' (' + app_start + '000)'])
app_table.append(
['Finish', datetime.datetime.fromtimestamp(float(app_end)).strftime('%Y-%m-%d %H:%M:%S') + ' (' + app_end + '000)'])
if app_properties['database']:
app_table.append(['Metadata', 'http://localhost:7187/?view=detailsView&id=' + app_properties['database']])
app_dashbaord_uri = 'http://localhost:7180/cmf/views/view?viewName=' + urllib.quote_plus(dashboard_name)
if app_report_only:
app_table.append(['Dashboard', app_dashbaord_uri])
else:
app_table.append(['Dashboard', app_dashbaord_uri + '#startTime=' + app_start + '000&endTime=' + app_end + '000'])
app_table.append(['Comparison', app_table_comparison.format('Version', 'Start', 'Finish', 'Run', 'CPU', 'HDFS', 'Network')])
for properties_value in app_properties['properties']:
app_table.append([None, app_table_comparison.format(', '.join(properties_value['Version']), ', '.join(properties_value['Start']),
', '.join(properties_value['Finish']), ', '.join(properties_value['Run']),
', '.join(properties_value['CPU']), ', '.join(properties_value['HDFS']),
', '.join(properties_value['Network']))])
print tabulate(app_table, tablefmt='grid')
def usage():
doc = inspect.getmodule(usage).__doc__
print >> sys.stderr, textwrap.dedent(doc % (sys.argv[0],))
def setup_logging(level):
logging.basicConfig()
logging.getLogger().setLevel(level)
logging.getLogger("requests").setLevel(logging.WARNING)
def main(argv):
setup_logging(logging.INFO)
user = 'admin'
password = 'admin'
man_host = 'localhost'
man_port = 7180
nav_host = 'localhost'
nav_port = 7187
app_name = None
app_version = None
app_namespace = None
app_time = None
app_start = None
app_end = None
app_dashboard = None
app_report_only = False
try:
opts, args = getopt.getopt(sys.argv[1:], 'h',
['help', 'user=', 'password=', 'man_host=', 'man_port=', 'nav_host=', 'nav_port=', 'app_name=',
'app_version=', 'app_namespace=', 'app_time=', 'app_start=', 'app_end=', 'app_dashboard=',
'app_report_only='])
except getopt.GetoptError, err:
print >> sys.stderr, err
usage()
return -1
for option, value in opts:
if option in ('-h', '--help'):
usage()
return -1
elif option in ('--user'):
user = value
elif option in ('--password'):
password = value
elif option in ('--man_host'):
man_host = value
elif option in ('--man_port'):
man_port = value
elif option in ('--nav_host'):
nav_host = value
elif option in ('--nav_port'):
nav_port = value
elif option in ('--app_name'):
app_name = value
elif option in ('--app_version'):
app_version = value
elif option in ('--app_namespace'):
app_namespace = value
elif option in ('--app_time'):
app_time = value
elif option in ('--app_start'):
app_start = value
elif option in ('--app_end'):
app_end = value
elif option in ('--app_dashboard'):
app_dashboard = value
elif option in ('--app_report_only'):
if value.upper() == 'TRUE':
app_report_only = True
else:
print >> sys.stderr, 'Unknown option or flag: ' + option
usage()
return -1
if app_name is None or app_version is None or app_namespace is None or app_time is None or app_start is None or app_end is None or \
app_dashboard is None:
print >> sys.stderr, \
'Required parameters [app_name, app_version, app_namespace, app_time, app_start, app_end, app_dashboard]' + \
' not passed on command line'
usage()
return -1
do_call(user, password, man_host, man_port, nav_host, nav_port, app_name, app_version, app_namespace, app_time, app_start, app_end,
app_dashboard,
app_report_only)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
| apache-2.0 | -2,847,525,859,407,920,600 | 48.731618 | 138 | 0.550602 | false |
cecton/meldnafen | meldnafen/app.py | 1 | 2961 | import os
import sdl2
import sdl2ui
from sdl2ui.mixer import Mixer
import sdl2ui.mixins
from sdl2ui.debugger import Debugger
from sdl2ui.joystick import JoystickManager
import meldnafen
from meldnafen.joystick import MenuJoystick
from meldnafen.mixins.bgm import BgmMixin
from meldnafen.mixins.controls import ControlsMixin
from meldnafen.mixins.emulator import EmulatorMixin
class Meldnafen(
sdl2ui.App, sdl2ui.mixins.ImmutableMixin,
BgmMixin, EmulatorMixin, ControlsMixin):
name = "Meldnafen"
@property
def x(self):
return int((self.app.viewport.w - 256) / 2 + self.settings['border'])
@property
def y(self):
return int((self.app.viewport.h - 224) / 2 + self.settings['border'])
@property
def settings(self):
return self.state['settings']
def startup(self):
if self.settings.get('startup'):
for command in self.settings['startup']:
os.system(command)
def init(self):
self.set_state({
'settings': self.props['settings'].copy(),
})
self.keyboard_mapping = {
sdl2.SDL_SCANCODE_Q: self.app.quit,
sdl2.SDL_SCANCODE_D: self.toggle_debug_mode,
}
self.startup()
sdl2.SDL_ShowCursor(sdl2.SDL_FALSE)
sdl2.SDL_SetHint(sdl2.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, b"1")
self.load_resource('font-12', 'font-12.png')
self.resources['font-12'].make_font(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?("
")[]<>~-_+@:/'., ")
self.debugger = self.add_component(Debugger,
x=self.x - 8,
y=self.y - 8)
self.joystick_manager = self.add_component(JoystickManager)
self.joystick = self.add_component(MenuJoystick,
manager=self.joystick_manager,
index=0,
on_joystick_added=self.menu_joystick_added,
on_joystick_removed=self.menu_joystick_removed)
self.register_event_handler(sdl2.SDL_KEYDOWN, self.keypress)
def activate(self):
if self.settings['debug']:
self.debugger.enable()
def quit(self, exception=None):
if not isinstance(exception, Exception):
try:
meldnafen.write_config(self.settings)
except Exception:
self.logger.error("Could not save configuration")
else:
self.logger.debug("Configuration saved")
sdl2ui.App.quit(self)
def keypress(self, event):
if event.key.keysym.scancode in self.keyboard_mapping:
self.keyboard_mapping[event.key.keysym.scancode]()
def toggle_debug_mode(self):
self.debugger.toggle()
def lock(self):
self.emulators[self.state['emulator']].disable()
self.joystick.disable()
def unlock(self):
self.emulators[self.state['emulator']].enable()
self.joystick.enable()
| mit | -5,477,925,171,610,419,000 | 31.184783 | 79 | 0.627828 | false |
twisted-infra/twisted-trac-plugins | twisted_trac_plugins/ticket_reporter.py | 1 | 2598 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
import subprocess
from trac.core import Component, implements
from trac.ticket.api import ITicketChangeListener
class IRCTicketObserver(Component):
implements(ITicketChangeListener)
def ticket_created(self, ticket):
subprocess.call([
self.config.get('ticket-reporter', 'ticket_executable'),
self.config.get('ticket-reporter', 'tracker_location'),
str(ticket.id),
ticket.values['reporter'],
ticket.values['type'],
ticket.values['component'],
ticket.values['summary']])
def ticket_changed(self, ticket, comment, author, old_values):
messages = []
old = old_values.get('keywords', None)
if old is not None:
new = ticket.values['keywords']
if 'review' in old and 'review' not in new:
# It was up for review, now it isn't
messages.append('%(author)s reviewed <https://tm.tl/#%(ticket)d> - %(summary)s (%(assignee)s)')
elif 'review' in new and 'review' not in old:
# It is up for review, and it wasn't before
messages.append('%(author)s submitted <https://tm.tl/#%(ticket)d> - %(summary)s (%(assignee)s) for review')
old = old_values.get('status', None)
if old is not None:
new = ticket.values['status']
if old != 'closed' and new == 'closed':
# It wasn't closed, now it is.
messages.append('%(author)s closed <https://tm.tl/#%(ticket)d> - %(summary)s')
elif old == 'closed' and new != 'closed':
# It was closed, now it isn't.
messages.append('%(author)s re-opened <https://tm.tl/#%(ticket)d> - %(summary)s')
if messages is not None:
assignee = 'unassigned'
if ticket.values['owner']:
assignee = 'assigned to ' + ticket.values['owner']
executable = self.config.get('ticket-reporter', 'message_executable')
channels = self.config.get('ticket-reporter', 'report_channels').split(',')
message = '. '.join([
m % {'author': author,
'ticket': ticket.id,
'assignee': assignee,
'summary': ticket.values['summary']}
for m in messages])
for channel in channels:
subprocess.call([executable, channel, message])
def ticket_deleted(self, ticket):
pass
| mit | -6,608,386,113,944,275,000 | 41.590164 | 123 | 0.550808 | false |
YujiAzama/python-soracomclient | soracomclient/v1_0/auth.py | 1 | 1849 | # Copyright 2016 Yuji Azama
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
from soracomclient.client import ClientBase
class Auth(ClientBase):
path = "/auth"
def __init__(self, email, password, api_key=None, operator_id=None,
token=None, timeout=86400):
super(Auth, self).__init__(api_key, token)
self._auth = {'email': email,
'password': password,
'timeout': timeout}
if api_key is None:
self._auth = self.auth(self._auth)
else:
self._auth['apiKey'] = api_key
self._auth['operatorId'] = operator_id
self._auth['token'] = token
@property
def email(self):
return self._auth['email']
@property
def password(self):
return self._auth['password']
@property
def api_key(self):
return self._auth['apiKey']
@property
def operator_id(self):
return self._auth['operatorId']
@property
def token(self):
return self._auth['token']
def auth(self, auth):
body = {'email': auth['email'],
'password': auth['password'],
'tokenTimeoutSeconds': auth['timeout']}
status, response = self.post(self.path, body=body)
auth.update(response)
return auth
| apache-2.0 | -2,762,002,205,923,851,000 | 27.890625 | 74 | 0.6106 | false |
maas/maas | src/maasserver/models/tests/test_filesystem.py | 1 | 18819 | # Copyright 2015-2019 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests for `Filesystem`."""
from copy import copy
from itertools import chain, combinations
import re
from uuid import uuid4
from django.core.exceptions import ValidationError
from testscenarios import multiply_scenarios
from testtools import ExpectedException
from testtools.matchers import Equals, Is, IsInstance, MatchesStructure
from maasserver.enum import (
FILESYSTEM_FORMAT_TYPE_CHOICES_DICT,
FILESYSTEM_GROUP_TYPE,
FILESYSTEM_TYPE,
)
from maasserver.models.filesystem import Filesystem
from maasserver.models.filesystemgroup import RAID
from maasserver.testing.factory import factory
from maasserver.testing.testcase import MAASServerTestCase
class TestFilesystemManager(MAASServerTestCase):
"""Tests for the `FilesystemManager`."""
def test_filter_by_node(self):
node = factory.make_Node()
boot_bd = node.blockdevice_set.first()
root_partition = boot_bd.partitiontable_set.first().partitions.first()
root_fs = root_partition.filesystem_set.first()
block_device = factory.make_PhysicalBlockDevice(node=node)
bd_for_partitions = factory.make_PhysicalBlockDevice(node=node)
partition_table = factory.make_PartitionTable(
block_device=bd_for_partitions
)
partition = factory.make_Partition(partition_table=partition_table)
filesystem_on_bd = factory.make_Filesystem(block_device=block_device)
filesystem_on_partition = factory.make_Filesystem(partition=partition)
filesystem_on_node = factory.make_Filesystem(node=node)
self.assertItemsEqual(
[
root_fs,
filesystem_on_bd,
filesystem_on_partition,
filesystem_on_node,
],
Filesystem.objects.filter_by_node(node),
)
class TestFilesystem(MAASServerTestCase):
"""Tests for the `Filesystem` model."""
def test_get_node_returns_partition_node(self):
partition = factory.make_Partition()
fs = factory.make_Filesystem(partition=partition)
self.assertEqual(fs.partition.get_node(), fs.get_node())
def test_get_node_returns_block_device_node(self):
block_device = factory.make_PhysicalBlockDevice()
fs = factory.make_Filesystem(block_device=block_device)
self.assertEqual(fs.block_device.node, fs.get_node())
def test_get_node_returns_special_filesystem_node(self):
machine = factory.make_Node()
fs = factory.make_Filesystem(node=machine)
self.assertEqual(machine, fs.get_node())
def test_get_node_returns_None_when_no_substrate(self):
fs = Filesystem()
self.assertIsNone(fs.get_node())
def test_get_physical_block_devices_single(self):
node = factory.make_Node()
block_device = factory.make_PhysicalBlockDevice(node=node)
filesystem = factory.make_Filesystem(
fstype=FILESYSTEM_TYPE.LVM_PV, block_device=block_device
)
self.assertEqual(
filesystem.get_physical_block_devices(), [block_device]
)
def test_get_physical_block_devices_multiple(self):
node = factory.make_Node()
block_devices = [
factory.make_PhysicalBlockDevice(node=node) for _ in range(3)
]
filesystems = [
factory.make_Filesystem(
fstype=FILESYSTEM_TYPE.LVM_PV, block_device=block_device
)
for block_device in block_devices
]
fsgroup = factory.make_FilesystemGroup(
node=node,
filesystems=filesystems,
group_type=FILESYSTEM_GROUP_TYPE.LVM_VG,
)
virtual_block_device = factory.make_VirtualBlockDevice(
filesystem_group=fsgroup
)
filesystem = factory.make_Filesystem(
fstype=FILESYSTEM_TYPE.LVM_PV, block_device=virtual_block_device
)
self.assertEqual(
filesystem.get_physical_block_devices(), block_devices
)
def test_get_physical_block_device_raid_on_part(self):
# Regression test for LP:1849580
node = factory.make_Node(with_boot_disk=False)
block_devices = []
partitions = []
for _ in range(2):
block_device = factory.make_PhysicalBlockDevice(node=node)
block_devices.append(block_device)
pt = factory.make_PartitionTable(block_device=block_device)
partitions.append(
factory.make_Partition(
partition_table=pt, size=pt.get_available_size()
)
)
fs_group = RAID.objects.create_raid(
level=FILESYSTEM_GROUP_TYPE.RAID_1, partitions=partitions
)
fs = factory.make_Filesystem(block_device=fs_group.virtual_device)
self.assertItemsEqual(fs.get_physical_block_devices(), block_devices)
def test_get_size_returns_partition_size(self):
partition = factory.make_Partition()
fs = factory.make_Filesystem(partition=partition)
self.assertEqual(fs.partition.size, fs.get_size())
def test_get_size_returns_block_device_size(self):
block_device = factory.make_PhysicalBlockDevice()
fs = factory.make_Filesystem(block_device=block_device)
self.assertEqual(fs.block_device.size, fs.get_size())
def test_get_size_returns_0_when_partition_and_block_device_None(self):
fs = Filesystem()
self.assertEqual(0, fs.get_size())
def test_get_block_size_returns_partition_block_size(self):
partition = factory.make_Partition()
fs = factory.make_Filesystem(partition=partition)
self.assertEqual(fs.partition.get_block_size(), fs.get_block_size())
def test_get_block_size_returns_block_device_block_size(self):
block_device = factory.make_PhysicalBlockDevice()
fs = factory.make_Filesystem(block_device=block_device)
self.assertEqual(fs.block_device.block_size, fs.get_block_size())
def test_get_block_size_returns_0_when_partition_and_device_None(self):
fs = Filesystem()
self.assertEqual(0, fs.get_block_size())
def test_cannot_save_storage_backed_filesystem_if_storage_missing(self):
fs = Filesystem()
error = self.assertRaises(ValidationError, fs.save)
self.assertThat(
error.messages,
Equals(["One of partition or block device must be specified."]),
)
def test_cannot_save_host_backed_filesystem_if_node_missing(self):
for fstype in Filesystem.TYPES - Filesystem.TYPES_REQUIRING_STORAGE:
fs = Filesystem(fstype=fstype)
error = self.assertRaises(ValidationError, fs.save)
self.expectThat(
error.messages,
Equals(["A node must be specified."]),
"using " + fstype,
)
def test_cannot_save_filesystem_if_too_much_storage(self):
substrate_factories = {
"block_device": factory.make_BlockDevice,
"partition": factory.make_Partition,
"node": factory.make_Node,
}
substrate_combos = chain(
combinations(substrate_factories, 2),
combinations(substrate_factories, 3),
)
for substrates in substrate_combos:
fs = Filesystem(
**{
substrate: substrate_factories[substrate]()
for substrate in substrates
}
)
error = self.assertRaises(ValidationError, fs.save)
self.expectThat(
error.messages,
Equals(
[
"Only one of partition, block device, "
"or node can be specified."
]
),
"using " + ", ".join(substrates),
)
def test_save_doesnt_overwrite_uuid(self):
uuid = uuid4()
fs = factory.make_Filesystem(uuid=uuid)
self.assertEqual("%s" % uuid, fs.uuid)
def test_get_parent_returns_block_device(self):
block_device = factory.make_PhysicalBlockDevice()
filesystem = factory.make_Filesystem(block_device=block_device)
self.assertEqual(block_device, filesystem.get_parent())
def test_get_parent_returns_partition(self):
partition = factory.make_Partition()
filesystem = factory.make_Filesystem(partition=partition)
self.assertEqual(partition, filesystem.get_parent())
def test_get_parent_returns_special_filesystem_node(self):
machine = factory.make_Node()
filesystem = factory.make_Filesystem(node=machine)
self.assertEqual(machine, filesystem.get_parent())
def test_cannot_create_filesystem_directly_on_boot_disk(self):
node = factory.make_Node(with_boot_disk=False)
boot_disk = factory.make_PhysicalBlockDevice(node=node)
with ExpectedException(
ValidationError,
re.escape(
"{'__all__': ['Cannot place filesystem directly on the "
"boot disk. Create a partition on the boot disk first "
"and then format the partition.']}"
),
):
factory.make_Filesystem(block_device=boot_disk)
def test_can_create_filesystem_on_partition_on_boot_disk(self):
node = factory.make_Node(with_boot_disk=False)
boot_disk = factory.make_PhysicalBlockDevice(node=node)
partition_table = factory.make_PartitionTable(block_device=boot_disk)
partition = factory.make_Partition(partition_table=partition_table)
# Test is that an error is not raised.
factory.make_Filesystem(partition=partition)
def test_unique_on_partition_and_acquired(self):
# For any given partition, at most one unacquired and one acquired
# filesystem record may exist.
partition = factory.make_Partition()
filesystem = factory.make_Filesystem(partition=partition)
self.assertIsNone(filesystem.block_device)
# XXX: Why no Filesystem.acquire() method?
filesystem_acquired = copy(filesystem)
filesystem_acquired.id = None # Force INSERT.
filesystem_acquired.acquired = True
filesystem_acquired.save()
# Create a duplicate.
filesystem_dupe = copy(filesystem)
filesystem_dupe.id = None # Force INSERT.
error_messages_expected = Equals(
["Filesystem with this Partition and Acquired already exists."]
)
# Saving an unacquired duplicate fails.
filesystem_dupe.acquired = False
error = self.assertRaises(ValidationError, filesystem_dupe.save)
self.assertThat(error.messages, error_messages_expected)
# Saving an acquired duplicate fails.
filesystem_dupe.acquired = True
error = self.assertRaises(ValidationError, filesystem_dupe.save)
self.assertThat(error.messages, error_messages_expected)
def test_unique_on_block_device_and_acquired(self):
# For any given block device, at most one unacquired and one acquired
# filesystem record may exist.
block_device = factory.make_BlockDevice()
filesystem = factory.make_Filesystem(block_device=block_device)
self.assertIsNone(filesystem.partition)
# XXX: Why no Filesystem.acquire() method?
filesystem_acquired = copy(filesystem)
filesystem_acquired.id = None # Force INSERT.
filesystem_acquired.acquired = True
filesystem_acquired.save()
# Create a duplicate.
filesystem_dupe = copy(filesystem)
filesystem_dupe.id = None # Force INSERT.
error_messages_expected = Equals(
["Filesystem with this Block device and Acquired already exists."]
)
# Saving an unacquired duplicate fails.
filesystem_dupe.acquired = False
error = self.assertRaises(ValidationError, filesystem_dupe.save)
self.assertThat(error.messages, error_messages_expected)
# Saving an acquired duplicate fails.
filesystem_dupe.acquired = True
error = self.assertRaises(ValidationError, filesystem_dupe.save)
self.assertThat(error.messages, error_messages_expected)
class TestFilesystemMountableTypes(MAASServerTestCase):
"""Tests the `Filesystem` model with mountable filesystems."""
scenarios_fstypes_with_storage = tuple(
(displayname, {"fstype": name})
for name, displayname in FILESYSTEM_FORMAT_TYPE_CHOICES_DICT.items()
if name in Filesystem.TYPES_REQUIRING_STORAGE
)
scenarios_fstypes_without_storage = tuple(
(displayname, {"fstype": name})
for name, displayname in FILESYSTEM_FORMAT_TYPE_CHOICES_DICT.items()
if name not in Filesystem.TYPES_REQUIRING_STORAGE
)
scenarios_substrate_storage = (
(
"partition",
{
"make_substrate": lambda: {
"partition": factory.make_Partition()
},
"can_be_unmounted": True,
},
),
(
"block-device",
{
"make_substrate": lambda: {
"block_device": factory.make_PhysicalBlockDevice()
},
"can_be_unmounted": True,
},
),
)
scenarios_substrate_node = (
(
"node",
{
"make_substrate": lambda: {"node": factory.make_Node()},
"can_be_unmounted": False,
},
),
)
scenarios = [
*multiply_scenarios(
scenarios_fstypes_with_storage, scenarios_substrate_storage
),
*multiply_scenarios(
scenarios_fstypes_without_storage, scenarios_substrate_node
),
]
def test_can_create_mountable_filesystem(self):
substrate = self.make_substrate()
filesystem = factory.make_Filesystem(fstype=self.fstype, **substrate)
self.assertThat(filesystem, IsInstance(Filesystem))
self.assertThat(filesystem.fstype, Equals(self.fstype))
self.assertThat(filesystem.is_mountable, Is(True))
self.assertThat(filesystem, MatchesStructure.byEquality(**substrate))
def test_cannot_mount_two_filesystems_at_same_point(self):
substrate = self.make_substrate()
filesystem1 = factory.make_Filesystem(fstype=self.fstype, **substrate)
filesystem2 = factory.make_Filesystem(node=filesystem1.get_node())
mount_point = factory.make_absolute_path()
filesystem1.mount_point = mount_point
filesystem1.save()
filesystem2.mount_point = mount_point
# Filesystems that can be mounted at a directory complain when mounted
# at the same directory as another filesystem.
if filesystem1.uses_mount_point:
error = self.assertRaises(ValidationError, filesystem2.save)
self.assertThat(
error.messages,
Equals(
[
"Another filesystem is already mounted at %s."
% mount_point
]
),
)
else:
self.assertThat(filesystem2.save(), Is(None))
def test_can_mount_unacquired_and_acquired_filesystem_at_same_point(self):
substrate = self.make_substrate()
filesystem = factory.make_Filesystem(fstype=self.fstype, **substrate)
filesystem.id = None
filesystem.acquired = True
self.assertThat(filesystem.save(), Is(None))
def test_mount_point_is_none_for_filesystems_that_do_not_use_one(self):
substrate = self.make_substrate()
mount_point = factory.make_name("mount-point")
filesystem = factory.make_Filesystem(
fstype=self.fstype, mount_point=mount_point, **substrate
)
if filesystem.uses_mount_point:
self.assertThat(filesystem.mount_point, Equals(mount_point))
else:
self.assertThat(filesystem.mount_point, Equals("none"))
def test_filesystem_is_mounted_when_mount_point_is_set(self):
substrate = self.make_substrate()
filesystem = factory.make_Filesystem(fstype=self.fstype, **substrate)
if self.can_be_unmounted:
# Some filesystems can be unmounted. By default that's how the
# factory makes them, so we need to set mount_point to see how
# is_mounted behaves.
self.assertThat(filesystem.is_mounted, Is(False))
filesystem.mount_point = factory.make_name("path")
self.assertThat(filesystem.is_mounted, Is(True))
else:
# Some filesystems cannot be unmounted, and the factory ensures
# that they're always created with a mount point. We can unset
# mount_point and observe a change in is_mounted, but we'll be
# prevented from saving the amended filesystem.
self.assertThat(filesystem.is_mounted, Is(True))
filesystem.mount_point = None
self.assertThat(filesystem.is_mounted, Is(False))
error = self.assertRaises(ValidationError, filesystem.save)
self.assertThat(
error.messages,
Equals(["RAM-backed filesystems must be mounted."]),
)
class TestFilesystemsUsingMountPoints(MAASServerTestCase):
"""Tests the `Filesystem` model regarding use of mount points."""
scenarios = tuple(
(displayname, {"fstype": name, "mounts_at_path": (name != "swap")})
for name, displayname in FILESYSTEM_FORMAT_TYPE_CHOICES_DICT.items()
)
def test_uses_mount_point_is_true_for_real_filesystems(self):
filesystem = factory.make_Filesystem(fstype=self.fstype)
self.assertThat(
filesystem.uses_mount_point, Equals(self.mounts_at_path)
)
class TestFilesystemsUsingStorage(MAASServerTestCase):
"""Tests the `Filesystem` model regarding use of storage."""
scenarios = tuple(
(
displayname,
{
"fstype": name,
"mounts_device_or_partition": (
name != "ramfs" and name != "tmpfs"
),
},
)
for name, displayname in FILESYSTEM_FORMAT_TYPE_CHOICES_DICT.items()
)
def test_uses_mount_point_is_true_for_real_filesystems(self):
filesystem = factory.make_Filesystem(fstype=self.fstype)
self.assertThat(
filesystem.uses_storage, Equals(self.mounts_device_or_partition)
)
| agpl-3.0 | -254,908,638,647,458,720 | 38.370293 | 78 | 0.62761 | false |
larsks/cobbler-larsks | cobbler/modules/manage_import_vmware.py | 1 | 36213 | """
This is some of the code behind 'cobbler sync'.
Copyright 2006-2009, Red Hat, Inc
Michael DeHaan <[email protected]>
John Eckersberg <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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
"""
import os
import os.path
import shutil
import time
import sys
import glob
import traceback
import errno
import re
from utils import popen2
from shlex import shlex
import utils
from cexceptions import *
import templar
import item_distro
import item_profile
import item_repo
import item_system
from utils import _
# FIXME: add --quiet depending on if not --verbose?
RSYNC_CMD = "rsync -a %s '%s' %s --exclude-from=/etc/cobbler/rsync.exclude --progress"
def register():
"""
The mandatory cobbler module registration hook.
"""
return "manage/import"
class ImportVMWareManager:
def __init__(self,config,logger):
"""
Constructor
"""
self.logger = logger
self.config = config
self.api = config.api
self.distros = config.distros()
self.profiles = config.profiles()
self.systems = config.systems()
self.settings = config.settings()
self.repos = config.repos()
self.templar = templar.Templar(config)
# required function for import modules
def what(self):
return "import/vmware"
# required function for import modules
def check_for_signature(self,path,cli_breed):
signatures = [
'VMware/RPMS',
'imagedd.bz2',
]
#self.logger.info("scanning %s for a vmware-based signature" % path)
for signature in signatures:
d = os.path.join(path,signature)
if os.path.exists(d):
self.logger.info("Found a vmware compatible signature: %s" % signature)
return (True,signature)
if cli_breed and cli_breed in self.get_valid_breeds():
self.logger.info("Warning: No distro signature for kernel at %s, using value from command line" % path)
return (True,None)
return (False,None)
# required function for import modules
def run(self,pkgdir,mirror,mirror_name,network_root=None,kickstart_file=None,rsync_flags=None,arch=None,breed=None,os_version=None):
self.pkgdir = pkgdir
self.mirror = mirror
self.mirror_name = mirror_name
self.network_root = network_root
self.kickstart_file = kickstart_file
self.rsync_flags = rsync_flags
self.arch = arch
self.breed = breed
self.os_version = os_version
# some fixups for the XMLRPC interface, which does not use "None"
if self.arch == "": self.arch = None
if self.mirror == "": self.mirror = None
if self.mirror_name == "": self.mirror_name = None
if self.kickstart_file == "": self.kickstart_file = None
if self.os_version == "": self.os_version = None
if self.rsync_flags == "": self.rsync_flags = None
if self.network_root == "": self.network_root = None
# If no breed was specified on the command line, set it to "redhat" for this module
if self.breed == None:
self.breed = "vmware"
# debug log stuff for testing
#self.logger.info("self.pkgdir = %s" % str(self.pkgdir))
#self.logger.info("self.mirror = %s" % str(self.mirror))
#self.logger.info("self.mirror_name = %s" % str(self.mirror_name))
#self.logger.info("self.network_root = %s" % str(self.network_root))
#self.logger.info("self.kickstart_file = %s" % str(self.kickstart_file))
#self.logger.info("self.rsync_flags = %s" % str(self.rsync_flags))
#self.logger.info("self.arch = %s" % str(self.arch))
#self.logger.info("self.breed = %s" % str(self.breed))
#self.logger.info("self.os_version = %s" % str(self.os_version))
# both --import and --name are required arguments
if self.mirror is None:
utils.die(self.logger,"import failed. no --path specified")
if self.mirror_name is None:
utils.die(self.logger,"import failed. no --name specified")
# if --arch is supplied, validate it to ensure it's valid
if self.arch is not None and self.arch != "":
self.arch = self.arch.lower()
if self.arch == "x86":
# be consistent
self.arch = "i386"
if self.arch not in self.get_valid_arches():
utils.die(self.logger,"arch must be one of: %s" % string.join(self.get_valid_arches(),", "))
# if we're going to do any copying, set where to put things
# and then make sure nothing is already there.
self.path = os.path.normpath( "%s/ks_mirror/%s" % (self.settings.webdir, self.mirror_name) )
if os.path.exists(self.path) and self.arch is None:
# FIXME : Raise exception even when network_root is given ?
utils.die(self.logger,"Something already exists at this import location (%s). You must specify --arch to avoid potentially overwriting existing files." % self.path)
# import takes a --kickstart for forcing selection that can't be used in all circumstances
if self.kickstart_file and not self.breed:
utils.die(self.logger,"Kickstart file can only be specified when a specific breed is selected")
if self.os_version and not self.breed:
utils.die(self.logger,"OS version can only be specified when a specific breed is selected")
if self.breed and self.breed.lower() not in self.get_valid_breeds():
utils.die(self.logger,"Supplied import breed is not supported by this module")
# if --arch is supplied, make sure the user is not importing a path with a different
# arch, which would just be silly.
if self.arch:
# append the arch path to the name if the arch is not already
# found in the name.
for x in self.get_valid_arches():
if self.path.lower().find(x) != -1:
if self.arch != x :
utils.die(self.logger,"Architecture found on pathname (%s) does not fit the one given in command line (%s)"%(x,self.arch))
break
else:
# FIXME : This is very likely removed later at get_proposed_name, and the guessed arch appended again
self.path += ("-%s" % self.arch)
# make the output path and mirror content but only if not specifying that a network
# accessible support location already exists (this is --available-as on the command line)
if self.network_root is None:
# we need to mirror (copy) the files
utils.mkdir(self.path)
# prevent rsync from creating the directory name twice
# if we are copying via rsync
if not self.mirror.endswith("/"):
self.mirror = "%s/" % self.mirror
if self.mirror.startswith("http://") or self.mirror.startswith("ftp://") or self.mirror.startswith("nfs://"):
# http mirrors are kind of primative. rsync is better.
# that's why this isn't documented in the manpage and we don't support them.
# TODO: how about adding recursive FTP as an option?
utils.die(self.logger,"unsupported protocol")
else:
# good, we're going to use rsync..
# we don't use SSH for public mirrors and local files.
# presence of user@host syntax means use SSH
spacer = ""
if not self.mirror.startswith("rsync://") and not self.mirror.startswith("/"):
spacer = ' -e "ssh" '
rsync_cmd = RSYNC_CMD
if self.rsync_flags:
rsync_cmd = rsync_cmd + " " + self.rsync_flags
# kick off the rsync now
utils.run_this(rsync_cmd, (spacer, self.mirror, self.path), self.logger)
else:
# rather than mirroring, we're going to assume the path is available
# over http, ftp, and nfs, perhaps on an external filer. scanning still requires
# --mirror is a filesystem path, but --available-as marks the network path
if not os.path.exists(self.mirror):
utils.die(self.logger, "path does not exist: %s" % self.mirror)
# find the filesystem part of the path, after the server bits, as each distro
# URL needs to be calculated relative to this.
if not self.network_root.endswith("/"):
self.network_root = self.network_root + "/"
self.path = os.path.normpath( self.mirror )
valid_roots = [ "nfs://", "ftp://", "http://" ]
for valid_root in valid_roots:
if self.network_root.startswith(valid_root):
break
else:
utils.die(self.logger, "Network root given to --available-as must be nfs://, ftp://, or http://")
if self.network_root.startswith("nfs://"):
try:
(a,b,rest) = self.network_root.split(":",3)
except:
utils.die(self.logger, "Network root given to --available-as is missing a colon, please see the manpage example.")
# now walk the filesystem looking for distributions that match certain patterns
self.logger.info("adding distros")
distros_added = []
# FIXME : search below self.path for isolinux configurations or known directories from TRY_LIST
os.path.walk(self.path, self.distro_adder, distros_added)
# find out if we can auto-create any repository records from the install tree
#if self.network_root is None:
# self.logger.info("associating repos")
# # FIXME: this automagic is not possible (yet) without mirroring
# self.repo_finder(distros_added)
# find the most appropriate answer files for each profile object
self.logger.info("associating kickstarts")
self.kickstart_finder(distros_added)
# ensure bootloaders are present
self.api.pxegen.copy_bootloaders()
return True
# required function for import modules
def get_valid_arches(self):
return ["i386", "x86_64", "x86",]
# required function for import modules
def get_valid_breeds(self):
return ["vmware",]
# required function for import modules
def get_valid_os_versions(self):
return ["esx4","esxi"]
def get_valid_repo_breeds(self):
return ["rsync", "rhn", "yum",]
def get_release_files(self):
"""
Find distro release packages.
"""
data = glob.glob(os.path.join(self.get_pkgdir(), "vmware-esx-vmware-release-*"))
data2 = []
for x in data:
b = os.path.basename(x)
if b.find("vmware") != -1:
data2.append(x)
if len(data2) == 0:
# ESXi maybe?
return glob.glob(os.path.join(self.get_rootdir(), "vmkernel.gz"))
return data2
def get_tree_location(self, distro):
"""
Once a distribution is identified, find the part of the distribution
that has the URL in it that we want to use for kickstarting the
distribution, and create a ksmeta variable $tree that contains this.
"""
base = self.get_rootdir()
if self.network_root is None:
dest_link = os.path.join(self.settings.webdir, "links", distro.name)
# create the links directory only if we are mirroring because with
# SELinux Apache can't symlink to NFS (without some doing)
if not os.path.exists(dest_link):
try:
os.symlink(base, dest_link)
except:
# this shouldn't happen but I've seen it ... debug ...
self.logger.warning("symlink creation failed: %(base)s, %(dest)s") % { "base" : base, "dest" : dest_link }
# how we set the tree depends on whether an explicit network_root was specified
tree = "http://@@http_server@@/cblr/links/%s" % (distro.name)
self.set_install_tree(distro, tree)
else:
# where we assign the kickstart source is relative to our current directory
# and the input start directory in the crawl. We find the path segments
# between and tack them on the network source path to find the explicit
# network path to the distro that Anaconda can digest.
tail = self.path_tail(self.path, base)
tree = self.network_root[:-1] + tail
self.set_install_tree(distro, tree)
return
def repo_finder(self, distros_added):
"""
This routine looks through all distributions and tries to find
any applicable repositories in those distributions for post-install
usage.
"""
for distro in distros_added:
self.logger.info("traversing distro %s" % distro.name)
# FIXME : Shouldn't decide this the value of self.network_root ?
if distro.kernel.find("ks_mirror") != -1:
basepath = os.path.dirname(distro.kernel)
top = self.get_rootdir()
self.logger.info("descent into %s" % top)
# FIXME : The location of repo definition is known from breed
os.path.walk(top, self.repo_scanner, distro)
else:
self.logger.info("this distro isn't mirrored")
def repo_scanner(self,distro,dirname,fnames):
"""
This is an os.path.walk routine that looks for potential yum repositories
to be added to the configuration for post-install usage.
"""
matches = {}
for x in fnames:
if x == "base" or x == "repodata":
self.logger.info("processing repo at : %s" % dirname)
# only run the repo scanner on directories that contain a comps.xml
gloob1 = glob.glob("%s/%s/*comps*.xml" % (dirname,x))
if len(gloob1) >= 1:
if matches.has_key(dirname):
self.logger.info("looks like we've already scanned here: %s" % dirname)
continue
self.logger.info("need to process repo/comps: %s" % dirname)
self.process_comps_file(dirname, distro)
matches[dirname] = 1
else:
self.logger.info("directory %s is missing xml comps file, skipping" % dirname)
continue
def process_comps_file(self, comps_path, distro):
"""
When importing Fedora/EL certain parts of the install tree can also be used
as yum repos containing packages that might not yet be available via updates
in yum. This code identifies those areas.
"""
processed_repos = {}
masterdir = "repodata"
if not os.path.exists(os.path.join(comps_path, "repodata")):
# older distros...
masterdir = "base"
# figure out what our comps file is ...
self.logger.info("looking for %(p1)s/%(p2)s/*comps*.xml" % { "p1" : comps_path, "p2" : masterdir })
files = glob.glob("%s/%s/*comps*.xml" % (comps_path, masterdir))
if len(files) == 0:
self.logger.info("no comps found here: %s" % os.path.join(comps_path, masterdir))
return # no comps xml file found
# pull the filename from the longer part
comps_file = files[0].split("/")[-1]
try:
# store the yum configs on the filesystem so we can use them later.
# and configure them in the kickstart post, etc
counter = len(distro.source_repos)
# find path segment for yum_url (changing filesystem path to http:// trailing fragment)
seg = comps_path.rfind("ks_mirror")
urlseg = comps_path[seg+10:]
# write a yum config file that shows how to use the repo.
if counter == 0:
dotrepo = "%s.repo" % distro.name
else:
dotrepo = "%s-%s.repo" % (distro.name, counter)
fname = os.path.join(self.settings.webdir, "ks_mirror", "config", "%s-%s.repo" % (distro.name, counter))
repo_url = "http://@@http_server@@/cobbler/ks_mirror/config/%s-%s.repo" % (distro.name, counter)
repo_url2 = "http://@@http_server@@/cobbler/ks_mirror/%s" % (urlseg)
distro.source_repos.append([repo_url,repo_url2])
# NOTE: the following file is now a Cheetah template, so it can be remapped
# during sync, that's why we have the @@http_server@@ left as templating magic.
# repo_url2 is actually no longer used. (?)
config_file = open(fname, "w+")
config_file.write("[core-%s]\n" % counter)
config_file.write("name=core-%s\n" % counter)
config_file.write("baseurl=http://@@http_server@@/cobbler/ks_mirror/%s\n" % (urlseg))
config_file.write("enabled=1\n")
config_file.write("gpgcheck=0\n")
config_file.write("priority=$yum_distro_priority\n")
config_file.close()
# don't run creatrepo twice -- this can happen easily for Xen and PXE, when
# they'll share same repo files.
if not processed_repos.has_key(comps_path):
utils.remove_yum_olddata(comps_path)
#cmd = "createrepo --basedir / --groupfile %s %s" % (os.path.join(comps_path, masterdir, comps_file), comps_path)
cmd = "createrepo %s --groupfile %s %s" % (self.settings.createrepo_flags,os.path.join(comps_path, masterdir, comps_file), comps_path)
utils.subprocess_call(self.logger, cmd, shell=True)
processed_repos[comps_path] = 1
# for older distros, if we have a "base" dir parallel with "repodata", we need to copy comps.xml up one...
p1 = os.path.join(comps_path, "repodata", "comps.xml")
p2 = os.path.join(comps_path, "base", "comps.xml")
if os.path.exists(p1) and os.path.exists(p2):
shutil.copyfile(p1,p2)
except:
self.logger.error("error launching createrepo (not installed?), ignoring")
utils.log_exc(self.logger)
def distro_adder(self,distros_added,dirname,fnames):
"""
This is an os.path.walk routine that finds distributions in the directory
to be scanned and then creates them.
"""
# FIXME: If there are more than one kernel or initrd image on the same directory,
# results are unpredictable
initrd = None
kernel = None
for x in fnames:
adtls = []
fullname = os.path.join(dirname,x)
if os.path.islink(fullname) and os.path.isdir(fullname):
if fullname.startswith(self.path):
self.logger.warning("avoiding symlink loop")
continue
self.logger.info("following symlink: %s" % fullname)
os.path.walk(fullname, self.distro_adder, distros_added)
if ( x.startswith("initrd") or x.startswith("ramdisk.image.gz") or x.startswith("vmkboot.gz") ) and x != "initrd.size":
initrd = os.path.join(dirname,x)
if ( x.startswith("vmlinu") or x.startswith("kernel.img") or x.startswith("linux") or x.startswith("mboot.c32") ) and x.find("initrd") == -1:
kernel = os.path.join(dirname,x)
# if we've collected a matching kernel and initrd pair, turn the in and add them to the list
if initrd is not None and kernel is not None:
adtls.append(self.add_entry(dirname,kernel,initrd))
kernel = None
initrd = None
for adtl in adtls:
distros_added.extend(adtl)
def add_entry(self,dirname,kernel,initrd):
"""
When we find a directory with a valid kernel/initrd in it, create the distribution objects
as appropriate and save them. This includes creating xen and rescue distros/profiles
if possible.
"""
proposed_name = self.get_proposed_name(dirname,kernel)
proposed_arch = self.get_proposed_arch(dirname)
if self.arch and proposed_arch and self.arch != proposed_arch:
utils.die(self.logger,"Arch from pathname (%s) does not match with supplied one %s"%(proposed_arch,self.arch))
archs = self.learn_arch_from_tree()
if not archs:
if self.arch:
archs.append( self.arch )
else:
if self.arch and self.arch not in archs:
utils.die(self.logger, "Given arch (%s) not found on imported tree %s"%(self.arch,self.get_pkgdir()))
if proposed_arch:
if archs and proposed_arch not in archs:
self.logger.warning("arch from pathname (%s) not found on imported tree %s" % (proposed_arch,self.get_pkgdir()))
return
archs = [ proposed_arch ]
if len(archs)>1:
self.logger.warning("- Warning : Multiple archs found : %s" % (archs))
distros_added = []
for pxe_arch in archs:
name = proposed_name + "-" + pxe_arch
existing_distro = self.distros.find(name=name)
if existing_distro is not None:
self.logger.warning("skipping import, as distro name already exists: %s" % name)
continue
else:
self.logger.info("creating new distro: %s" % name)
distro = self.config.new_distro()
if name.find("-autoboot") != -1:
# this is an artifact of some EL-3 imports
continue
distro.set_name(name)
distro.set_kernel(kernel)
distro.set_initrd(initrd)
distro.set_arch(pxe_arch)
distro.set_breed(self.breed)
# If a version was supplied on command line, we set it now
if self.os_version:
distro.set_os_version(self.os_version)
self.distros.add(distro,save=True)
distros_added.append(distro)
existing_profile = self.profiles.find(name=name)
# see if the profile name is already used, if so, skip it and
# do not modify the existing profile
if existing_profile is None:
self.logger.info("creating new profile: %s" % name)
#FIXME: The created profile holds a default kickstart, and should be breed specific
profile = self.config.new_profile()
else:
self.logger.info("skipping existing profile, name already exists: %s" % name)
continue
# save our minimal profile which just points to the distribution and a good
# default answer file
profile.set_name(name)
profile.set_distro(name)
profile.set_kickstart(self.kickstart_file)
# We just set the virt type to vmware for these
# since newer VMwares support running ESX as a guest for testing
profile.set_virt_type("vmware")
# save our new profile to the collection
self.profiles.add(profile,save=True)
return distros_added
def get_proposed_name(self,dirname,kernel=None):
"""
Given a directory name where we have a kernel/initrd pair, try to autoname
the distribution (and profile) object based on the contents of that path
"""
if self.network_root is not None:
name = self.mirror_name + "-".join(self.path_tail(os.path.dirname(self.path),dirname).split("/"))
else:
# remove the part that says /var/www/cobbler/ks_mirror/name
name = "-".join(dirname.split("/")[5:])
if kernel is not None and kernel.find("PAE") != -1:
name = name + "-PAE"
# These are all Ubuntu's doing, the netboot images are buried pretty
# deep. ;-) -JC
name = name.replace("-netboot","")
name = name.replace("-ubuntu-installer","")
name = name.replace("-amd64","")
name = name.replace("-i386","")
# we know that some kernel paths should not be in the name
name = name.replace("-images","")
name = name.replace("-pxeboot","")
name = name.replace("-install","")
name = name.replace("-isolinux","")
# some paths above the media root may have extra path segments we want
# to clean up
name = name.replace("-os","")
name = name.replace("-tree","")
name = name.replace("var-www-cobbler-", "")
name = name.replace("ks_mirror-","")
name = name.replace("--","-")
# remove any architecture name related string, as real arch will be appended later
name = name.replace("chrp","ppc64")
for separator in [ '-' , '_' , '.' ] :
for arch in [ "i386" , "x86_64" , "ia64" , "ppc64", "ppc32", "ppc", "x86" , "s390x", "s390" , "386" , "amd" ]:
name = name.replace("%s%s" % ( separator , arch ),"")
return name
def get_proposed_arch(self,dirname):
"""
Given an directory name, can we infer an architecture from a path segment?
"""
if dirname.find("x86_64") != -1 or dirname.find("amd") != -1:
return "x86_64"
if dirname.find("ia64") != -1:
return "ia64"
if dirname.find("i386") != -1 or dirname.find("386") != -1 or dirname.find("x86") != -1:
return "i386"
if dirname.find("s390x") != -1:
return "s390x"
if dirname.find("s390") != -1:
return "s390"
if dirname.find("ppc64") != -1 or dirname.find("chrp") != -1:
return "ppc64"
if dirname.find("ppc32") != -1:
return "ppc"
if dirname.find("ppc") != -1:
return "ppc"
return None
def arch_walker(self,foo,dirname,fnames):
"""
See docs on learn_arch_from_tree.
The TRY_LIST is used to speed up search, and should be dropped for default importer
Searched kernel names are kernel-header, linux-headers-, kernel-largesmp, kernel-hugemem
This method is useful to get the archs, but also to package type and a raw guess of the breed
"""
# try to find a kernel header RPM and then look at it's arch.
for x in fnames:
if self.match_kernelarch_file(x):
for arch in self.get_valid_arches():
if x.find(arch) != -1:
foo[arch] = 1
for arch in [ "i686" , "amd64" ]:
if x.find(arch) != -1:
foo[arch] = 1
def kickstart_finder(self,distros_added):
"""
For all of the profiles in the config w/o a kickstart, use the
given kickstart file, or look at the kernel path, from that,
see if we can guess the distro, and if we can, assign a kickstart
if one is available for it.
"""
for profile in self.profiles:
distro = self.distros.find(name=profile.get_conceptual_parent().name)
if distro is None or not (distro in distros_added):
continue
kdir = os.path.dirname(distro.kernel)
if self.kickstart_file == None:
for rpm in self.get_release_files():
# FIXME : This redhat specific check should go into the importer.find_release_files method
if rpm.find("notes") != -1:
continue
results = self.scan_pkg_filename(rpm)
# FIXME : If os is not found on tree but set with CLI, no kickstart is searched
if results is None:
self.logger.warning("No version found on imported tree")
continue
(flavor, major, minor, release, update) = results
version , ks = self.set_variance(flavor, major, minor, release, update, distro.arch)
if self.os_version:
if self.os_version != version:
utils.die(self.logger,"CLI version differs from tree : %s vs. %s" % (self.os_version,version))
ds = self.get_datestamp()
distro.set_comment("%s.%s.%s update %s" % (version,minor,release,update))
distro.set_os_version(version)
if ds is not None:
distro.set_tree_build_time(ds)
profile.set_kickstart(ks)
if flavor == "esxi":
self.logger.info("This is an ESXi distro - adding extra PXE files to boot-files list")
# add extra files to boot_files in the distro
boot_files = ''
for file in ('vmkernel.gz','sys.vgz','cim.vgz','ienviron.vgz','install.vgz'):
boot_files += '$img_path/%s=%s/%s ' % (file,self.path,file)
distro.set_boot_files(boot_files.strip())
self.profiles.add(profile,save=True)
self.configure_tree_location(distro)
self.distros.add(distro,save=True) # re-save
self.api.serialize()
def configure_tree_location(self, distro):
"""
Once a distribution is identified, find the part of the distribution
that has the URL in it that we want to use for kickstarting the
distribution, and create a ksmeta variable $tree that contains this.
"""
base = self.get_rootdir()
if self.network_root is None:
dest_link = os.path.join(self.settings.webdir, "links", distro.name)
# create the links directory only if we are mirroring because with
# SELinux Apache can't symlink to NFS (without some doing)
if not os.path.exists(dest_link):
try:
os.symlink(base, dest_link)
except:
# this shouldn't happen but I've seen it ... debug ...
self.logger.warning("symlink creation failed: %(base)s, %(dest)s") % { "base" : base, "dest" : dest_link }
# how we set the tree depends on whether an explicit network_root was specified
tree = "http://@@http_server@@/cblr/links/%s" % (distro.name)
self.set_install_tree( distro, tree)
else:
# where we assign the kickstart source is relative to our current directory
# and the input start directory in the crawl. We find the path segments
# between and tack them on the network source path to find the explicit
# network path to the distro that Anaconda can digest.
tail = utils.path_tail(self.path, base)
tree = self.network_root[:-1] + tail
self.set_install_tree( distro, tree)
def get_rootdir(self):
return self.mirror
def get_pkgdir(self):
if not self.pkgdir:
return None
return os.path.join(self.get_rootdir(),self.pkgdir)
def set_install_tree(self, distro, url):
distro.ks_meta["tree"] = url
def learn_arch_from_tree(self):
"""
If a distribution is imported from DVD, there is a good chance the path doesn't
contain the arch and we should add it back in so that it's part of the
meaningful name ... so this code helps figure out the arch name. This is important
for producing predictable distro names (and profile names) from differing import sources
"""
result = {}
# FIXME : this is called only once, should not be a walk
if self.get_pkgdir():
os.path.walk(self.get_pkgdir(), self.arch_walker, result)
if result.pop("amd64",False):
result["x86_64"] = 1
if result.pop("i686",False):
result["i386"] = 1
return result.keys()
def match_kernelarch_file(self, filename):
"""
Is the given filename a kernel filename?
"""
if not filename.endswith("rpm") and not filename.endswith("deb"):
return False
for match in ["kernel-header", "kernel-source", "kernel-smp", "kernel-largesmp", "kernel-hugemem", "linux-headers-", "kernel-devel", "kernel-"]:
if filename.find(match) != -1:
return True
return False
def scan_pkg_filename(self, rpm):
"""
Determine what the distro is based on the release package filename.
"""
rpm_file = os.path.basename(rpm)
if rpm_file.lower().find("-esx-") != -1:
flavor = "esx"
match = re.search(r'release-(\d)+-(\d)+\.(\d)+\.(\d)+-(\d)\.', rpm_file)
if match:
major = match.group(2)
minor = match.group(3)
release = match.group(4)
update = match.group(5)
else:
# FIXME: what should we do if the re fails above?
return None
elif rpm_file.lower() == "vmkernel.gz":
flavor = "esxi"
major = 0
minor = 0
release = 0
update = 0
# this should return something like:
# VMware ESXi 4.1.0 [Releasebuild-260247], built on May 18 2010
# though there will most likely be multiple results
scan_cmd = 'gunzip -c %s | strings | grep -i "^vmware esxi"' % rpm
(data,rc) = utils.subprocess_sp(self.logger, scan_cmd)
lines = data.split('\n')
m = re.compile(r'ESXi (\d)+\.(\d)+\.(\d)+ \[Releasebuild-([\d]+)\]')
for line in lines:
match = m.search(line)
if match:
major = match.group(1)
minor = match.group(2)
release = match.group(3)
update = match.group(4)
break
else:
return None
#self.logger.info("DEBUG: in scan_pkg_filename() - major=%s, minor=%s, release=%s, update=%s" % (major,minor,release,update))
return (flavor, major, minor, release, update)
def get_datestamp(self):
"""
Based on a VMWare tree find the creation timestamp
"""
pass
def set_variance(self, flavor, major, minor, release, update, arch):
"""
Set distro specific versioning.
"""
os_version = "%s%s" % (flavor, major)
if flavor == "esx4":
ks = "/var/lib/cobbler/kickstarts/esx.ks"
elif flavor == "esxi4":
ks = "/var/lib/cobbler/kickstarts/esxi.ks"
else:
ks = "/var/lib/cobbler/kickstarts/default.ks"
return os_version , ks
# ==========================================================================
def get_import_manager(config,logger):
return ImportVMWareManager(config,logger)
| gpl-2.0 | -2,283,180,977,123,447,000 | 41.010441 | 177 | 0.570679 | false |
krahman/rethinkdb | test/memcached_workloads/cas.py | 1 | 1805 | #!/usr/bin/env python
# Copyright 2010-2012 RethinkDB, all rights reserved.
from random import shuffle
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import memcached_workload_common
from vcoptparse import *
op = memcached_workload_common.option_parser_for_memcache()
del op["mclib"] # No longer optional; we only work with memcache.
op["num_ints"] = IntFlag("--num-ints", 10)
opts = op.parse(sys.argv)
opts["mclib"] = "memcache"
with memcached_workload_common.make_memcache_connection(opts) as mc:
print "Shuffling numbers"
ints = range(0, opts["num_ints"])
shuffle(ints)
print "Checking cas on numbers"
for i in ints:
print "Inserting %d" % i
if (0 == mc.set(str(i), str(i))):
raise ValueError("Insert of %d failed" % i)
print "Getting %d" % i
value, _, cas_id = mc.explicit_gets(str(i))
if (value != str(i)):
raise ValueError("get failed, should be %d=>%d, was %s" % (i, i, value))
print "'cas'-ing %d" % i
if (0 == mc.explicit_cas(str(i), str(i+1), cas_id)):
raise ValueError("cas of %d failed" % i)
print "Verifying cas %d" % i
value, _, cas_id = mc.explicit_gets(str(i))
if (value != str(i+1)):
raise ValueError("get for cas failed, should be %d=>%d, was %s" % (i, i+1, value))
print "Modifying %d again" % i
if (0 == mc.set(str(i), str(i+10))):
raise ValueError("Modify of %d failed" % i)
print "'cas'-ing %d again" % i
if (0 != mc.explicit_cas(str(i), str(i+20), cas_id)):
raise ValueError("cas of %d should have failed, item has been modified" % i)
| agpl-3.0 | -7,830,055,373,795,374,000 | 37.404255 | 99 | 0.571745 | false |
timborden/browser-laptop | tools/publish_release.py | 1 | 2080 | #!/usr/bin/env python
import json
import os
from lib.github import GitHub
import requests
BROWSER_LAPTOP_REPO = 'brave/browser-laptop'
TARGET_ARCH= os.environ['TARGET_ARCH'] if os.environ.has_key('TARGET_ARCH') else 'x64'
RELEASE_NAME = 'Dev Channel Beta'
def main():
github = GitHub(auth_token())
releases = github.repos(BROWSER_LAPTOP_REPO).releases.get()
tag = ('v' + json.load(open('package.json'))['version'] +
release_channel())
tag_exists = False
for release in releases:
if not release['draft'] and release['tag_name'] == tag:
tag_exists = True
break
release = create_or_get_release_draft(github, releases, tag,
tag_exists)
# Press the publish button.
publish_release(github, release['id'])
def create_release_draft(github, tag):
name = '{0} {1}'.format(RELEASE_NAME, tag)
# TODO: Parse release notes from CHANGELOG.md
body = '(placeholder)'
if body == '':
sys.stderr.write('Quit due to empty release note.\n')
sys.exit(1)
data = dict(tag_name=tag, name=name, body=body, draft=True, prerelease=True)
r = github.repos(BROWSER_LAPTOP_REPO).releases.post(data=data)
return r
def create_or_get_release_draft(github, releases, tag, tag_exists):
# Search for existing draft.
for release in releases:
if release['draft']:
return release
if tag_exists:
tag = 'do-not-publish-me'
return create_release_draft(github, tag)
def auth_token():
token = os.environ['GITHUB_TOKEN']
message = ('Error: Please set the $GITHUB_TOKEN '
'environment variable, which is your personal token')
assert token, message
return token
def release_channel():
channel = os.environ['CHANNEL']
message = ('Error: Please set the $CHANNEL '
'environment variable, which is your release channel')
assert channel, message
return channel
def publish_release(github, release_id):
data = dict(draft=False)
github.repos(BROWSER_LAPTOP_REPO).releases(release_id).patch(data=data)
if __name__ == '__main__':
import sys
sys.exit(main())
| mpl-2.0 | 1,073,077,027,997,134,500 | 29.144928 | 86 | 0.672596 | false |
mesheven/pyOCD | pyocd/core/memory_interface.py | 1 | 4407 | # pyOCD debugger
# Copyright (c) 2018 Arm Limited
# SPDX-License-Identifier: Apache-2.0
#
# 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 ..utility import conversion
## @brief Interface for memory access.
class MemoryInterface(object):
## @brief Write a single memory location.
#
# By default the transfer size is a word.
def write_memory(self, addr, data, transfer_size=32):
raise NotImplementedError()
## @brief Read a memory location.
#
# By default, a word will be read.
def read_memory(self, addr, transfer_size=32, now=True):
raise NotImplementedError()
## @brief Write an aligned block of 32-bit words.
def write_memory_block32(self, addr, data):
raise NotImplementedError()
## @brief Read an aligned block of 32-bit words.
def read_memory_block32(self, addr, size):
raise NotImplementedError()
# @brief Shorthand to write a 32-bit word.
def write32(self, addr, value):
self.write_memory(addr, value, 32)
# @brief Shorthand to write a 16-bit halfword.
def write16(self, addr, value):
self.write_memory(addr, value, 16)
# @brief Shorthand to write a byte.
def write8(self, addr, value):
self.write_memory(addr, value, 8)
# @brief Shorthand to read a 32-bit word.
def read32(self, addr, now=True):
return self.read_memory(addr, 32, now)
# @brief Shorthand to read a 16-bit halfword.
def read16(self, addr, now=True):
return self.read_memory(addr, 16, now)
# @brief Shorthand to read a byte.
def read8(self, addr, now=True):
return self.read_memory(addr, 8, now)
## @brief Read a block of unaligned bytes in memory.
# @return an array of byte values
def read_memory_block8(self, addr, size):
res = []
# try to read 8bits data
if (size > 0) and (addr & 0x01):
mem = self.read8(addr)
res.append(mem)
size -= 1
addr += 1
# try to read 16bits data
if (size > 1) and (addr & 0x02):
mem = self.read16(addr)
res.append(mem & 0xff)
res.append((mem >> 8) & 0xff)
size -= 2
addr += 2
# try to read aligned block of 32bits
if (size >= 4):
mem = self.read_memory_block32(addr, size // 4)
res += conversion.u32le_list_to_byte_list(mem)
size -= 4*len(mem)
addr += 4*len(mem)
if (size > 1):
mem = self.read16(addr)
res.append(mem & 0xff)
res.append((mem >> 8) & 0xff)
size -= 2
addr += 2
if (size > 0):
mem = self.read8(addr)
res.append(mem)
return res
## @brief Write a block of unaligned bytes in memory.
def write_memory_block8(self, addr, data):
size = len(data)
idx = 0
#try to write 8 bits data
if (size > 0) and (addr & 0x01):
self.write8(addr, data[idx])
size -= 1
addr += 1
idx += 1
# try to write 16 bits data
if (size > 1) and (addr & 0x02):
self.write16(addr, data[idx] | (data[idx+1] << 8))
size -= 2
addr += 2
idx += 2
# write aligned block of 32 bits
if (size >= 4):
data32 = conversion.byte_list_to_u32le_list(data[idx:idx + (size & ~0x03)])
self.write_memory_block32(addr, data32)
addr += size & ~0x03
idx += size & ~0x03
size -= size & ~0x03
# try to write 16 bits data
if (size > 1):
self.write16(addr, data[idx] | (data[idx+1] << 8))
size -= 2
addr += 2
idx += 2
#try to write 8 bits data
if (size > 0):
self.write8(addr, data[idx])
| apache-2.0 | 3,468,156,629,870,681,000 | 29.818182 | 87 | 0.56501 | false |
tundra/neutrino | tests/python/plankton/planktontest.py | 1 | 3832 | # Copyright 2013 the Neutrino authors (see AUTHORS).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import plankton
from plankton import codec
import unittest
@plankton.serializable
class Object(object):
def __init__(self, header=None):
self.header = header
self.payload = None
def set_header(self, value):
self.header = value
return self
@plankton.header
def get_header(self):
return self.header
def set_payload(self, value):
self.payload = value
return self
def set_contents(self, value):
return self.set_payload(value)
@plankton.payload
def get_payload(self):
return self.payload
# An environment reference. This is kind of cheating -- in reality the
# references would be resolved to real objects but for simplicity we stick with
# these placeholders.
class EnvRef(object):
def __init__(self, key):
self.key = key
def __eq__(self, that):
assert isinstance(that, EnvRef)
return self.key == that.key
def __hash__(self):
return hash(self.key)
class Context(object):
def __init__(self):
self.refs = {}
def new_object(self, id=None):
result = Object()
if not id is None:
self.refs[id] = result
return result
def get_ref(self, id):
return self.refs[id]
def new_env_ref(self, key, id=None):
result = EnvRef(key)
if not id is None:
self.refs[id] = result
return result
class RecordingAssembler(object):
def __init__(self):
self.entries = []
def tag(self, value):
self.entries.append(('tag', value))
return self
def int32(self, value):
self.entries.append(('int32', value))
return self
def uint32(self, value):
self.entries.append(('uint32', value))
return self
def blob(self, bytes):
self.entries.append(('blob', str(bytes)))
return self
class TestCase(unittest.TestCase):
def new_context(self):
return Context()
def run_test(self, input, assemble):
self.run_encode_test(input, assemble)
self.run_decode_test(input, assemble)
def run_decode_test(self, input, assemble):
# Write the assembly using the assembler. We're assuming the assembler works
# (which gets tested by other tests).
assm = codec.EncodingAssembler()
assemble(assm)
bytes = assm.bytes
# Then try decoding the bytes.
decoder = plankton.Decoder(default_object=Object)
decoded = decoder.decode(bytes)
self.check_equals(input, decoded)
def run_encode_test(self, input, assemble):
expected_assm = RecordingAssembler()
assemble(expected_assm)
expected = expected_assm.entries
found_assm = RecordingAssembler()
plankton.Encoder().write(input, assembler=found_assm)
found = found_assm.entries
self.assertEquals(expected, found)
def are_equal(self, a, b, seen):
if isinstance(a, Object) and isinstance(b, Object):
for (sa, sb) in seen:
if sa is a:
return sb is b
seen.append((a, b))
ah = a.header
bh = b.header
ap = a.payload
bp = b.payload
return self.are_equal(ah, bh, seen) and self.are_equal(ap, bp, seen)
elif isinstance(a, list) and isinstance(b, list):
if len(a) != len(b):
return false
for i in xrange(0, len(a)):
if not self.are_equal(a[i], b[i], seen):
return False
return True
elif isinstance(a, dict) and isinstance(b, dict):
if len(a) != len(b):
return False
for k in a.keys():
if not k in b:
return False
if not self.are_equal(a[k], b[k], seen):
return False
return True
elif a == b:
return True
else:
return False
def check_equals(self, expected, decoded):
if not self.are_equal(expected, decoded, []):
self.assertEquals(expected, decoded)
| apache-2.0 | 1,784,414,413,716,150,800 | 22.801242 | 80 | 0.641701 | false |
n0mjs710/HBlink | hb_bridge_all.py | 1 | 13416 | #!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2018 Cortney T. Buffington, N0MJS <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
This is a very simple call/packet router for Homebrew Repeater Protocol. It
will forward traffic from any system to all other systems configured in the
hblink.py configuration file. It does not check for call contentions or
filter TS/TGID combinations. It should really only be used as a proxy to
hide multiple Homebrew repater protocol systems behind what appears as a single
repeater, hotspot, etc.
As is, this program only works with group voice packets. It could work for all
of them by removing a few things.
'''
from __future__ import print_function
# Python modules we need
import sys
from bitarray import bitarray
from time import time
from importlib import import_module
from types import ModuleType
# Twisted is pretty important, so I keep it separate
from twisted.internet.protocol import Factory, Protocol
from twisted.protocols.basic import NetstringReceiver
from twisted.internet import reactor, task
# Things we import from the main hblink module
from hblink import HBSYSTEM, OPENBRIDGE, systems, hblink_handler, reportFactory, REPORT_OPCODES, config_reports, mk_aliases
from dmr_utils.utils import hex_str_3, int_id, get_alias
from dmr_utils import decode, bptc, const
import hb_config
import hb_log
import hb_const
# The module needs logging logging, but handlers, etc. are controlled by the parent
import logging
logger = logging.getLogger(__name__)
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
__author__ = 'Cortney T. Buffington, N0MJS'
__copyright__ = 'Copyright (c) 2016-2018 Cortney T. Buffington, N0MJS and the K0USY Group'
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
__license__ = 'GNU GPLv3'
__maintainer__ = 'Cort Buffington, N0MJS'
__email__ = '[email protected]'
__status__ = 'pre-alpha'
# Module gobal varaibles
class bridgeallSYSTEM(HBSYSTEM):
def __init__(self, _name, _config, _report):
HBSYSTEM.__init__(self, _name, _config, _report)
# Status information for the system, TS1 & TS2
# 1 & 2 are "timeslot"
# In TX_EMB_LC, 2-5 are burst B-E
self.STATUS = {
1: {
'RX_START': time(),
'RX_SEQ': '\x00',
'RX_RFS': '\x00',
'TX_RFS': '\x00',
'RX_STREAM_ID': '\x00',
'TX_STREAM_ID': '\x00',
'RX_TGID': '\x00\x00\x00',
'TX_TGID': '\x00\x00\x00',
'RX_TIME': time(),
'TX_TIME': time(),
'RX_TYPE': hb_const.HBPF_SLT_VTERM,
'RX_LC': '\x00',
'TX_H_LC': '\x00',
'TX_T_LC': '\x00',
'TX_EMB_LC': {
1: '\x00',
2: '\x00',
3: '\x00',
4: '\x00',
}
},
2: {
'RX_START': time(),
'RX_SEQ': '\x00',
'RX_RFS': '\x00',
'TX_RFS': '\x00',
'RX_STREAM_ID': '\x00',
'TX_STREAM_ID': '\x00',
'RX_TGID': '\x00\x00\x00',
'TX_TGID': '\x00\x00\x00',
'RX_TIME': time(),
'TX_TIME': time(),
'RX_TYPE': hb_const.HBPF_SLT_VTERM,
'RX_LC': '\x00',
'TX_H_LC': '\x00',
'TX_T_LC': '\x00',
'TX_EMB_LC': {
1: '\x00',
2: '\x00',
3: '\x00',
4: '\x00',
}
}
}
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
pkt_time = time()
dmrpkt = _data[20:53]
_bits = int_id(_data[15])
if _call_type == 'group':
# Is this is a new call stream?
if (_stream_id != self.STATUS[_slot]['RX_STREAM_ID']):
self.STATUS['RX_START'] = pkt_time
logger.info('(%s) *CALL START* STREAM ID: %s SUB: %s (%s) PEER: %s (%s) TGID %s (%s), TS %s', \
self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot)
# Final actions - Is this a voice terminator?
if (_frame_type == hb_const.HBPF_DATA_SYNC) and (_dtype_vseq == hb_const.HBPF_SLT_VTERM) and (self.STATUS[_slot]['RX_TYPE'] != hb_const.HBPF_SLT_VTERM):
call_duration = pkt_time - self.STATUS['RX_START']
logger.info('(%s) *CALL END* STREAM ID: %s SUB: %s (%s) PEER: %s (%s) TGID %s (%s), TS %s, Duration: %s', \
self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot, call_duration)
# Mark status variables for use later
self.STATUS[_slot]['RX_RFS'] = _rf_src
self.STATUS[_slot]['RX_TYPE'] = _dtype_vseq
self.STATUS[_slot]['RX_TGID'] = _dst_id
self.STATUS[_slot]['RX_TIME'] = pkt_time
self.STATUS[_slot]['RX_STREAM_ID'] = _stream_id
for _target in self._CONFIG['SYSTEMS']:
if _target != self._system:
_target_status = systems[_target].STATUS
_target_system = self._CONFIG['SYSTEMS'][_target]
_target_status[_slot]['TX_STREAM_ID'] = _stream_id
# ACL Processing
if self._CONFIG['GLOBAL']['USE_ACL']:
if not acl_check(_rf_src, self._CONFIG['GLOBAL']['SUB_ACL']):
if self._laststrid != _stream_id:
logger.debug('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s FROM SUBSCRIBER %s BY GLOBAL ACL', _target_system, int_id(_stream_id), int_id(_rf_src))
self._laststrid = _stream_id
return
if _slot == 1 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG1_ACL']):
if self._laststrid != _stream_id:
logger.debug('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s ON TGID %s BY GLOBAL TS1 ACL', _target_system, int_id(_stream_id), int_id(_dst_id))
self._laststrid = _stream_id
return
if _slot == 2 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG2_ACL']):
if self._laststrid != _stream_id:
logger.debug('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s ON TGID %s BY GLOBAL TS2 ACL', _target_system, int_id(_stream_id), int_id(_dst_id))
self._laststrid = _stream_id
return
if self._target_system['USE_ACL']:
if not acl_check(_rf_src, _target_system['SUB_ACL']):
if self._laststrid != _stream_id:
logger.debug('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s FROM SUBSCRIBER %s BY SYSTEM ACL', _target_system, int_id(_stream_id), int_id(_rf_src))
self._laststrid = _stream_id
return
if _slot == 1 and not acl_check(_dst_id, _target_system['TG1_ACL']):
if self._laststrid != _stream_id:
logger.debug('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s ON TGID %s BY SYSTEM TS1 ACL', _target_system, int_id(_stream_id), int_id(_dst_id))
self._laststrid = _stream_id
return
if _slot == 2 and not acl_check(_dst_id, _target_system['TG2_ACL']):
if self._laststrid != _stream_id:
logger.debug('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s ON TGID %s BY SYSTEM TS2 ACL', _target_system, int_id(_stream_id), int_id(_dst_id))
self._laststrid = _stream_id
return
self._laststrid = _stream_id
systems[_target].send_system(_data)
#logger.debug('(%s) Packet routed to system: %s', self._system, _target)
#************************************************
# MAIN PROGRAM LOOP STARTS HERE
#************************************************
if __name__ == '__main__':
import argparse
import sys
import os
import signal
from dmr_utils.utils import try_download, mk_id_dict
# Change the current directory to the location of the application
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually hblink.cfg)')
parser.add_argument('-l', '--logging', action='store', dest='LOG_LEVEL', help='Override config file logging level.')
cli_args = parser.parse_args()
# Ensure we have a path for the config file, if one wasn't specified, then use the default (top of file)
if not cli_args.CONFIG_FILE:
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/hblink.cfg'
# Call the external routine to build the configuration dictionary
CONFIG = hb_config.build_config(cli_args.CONFIG_FILE)
# Start the system logger
if cli_args.LOG_LEVEL:
CONFIG['LOGGER']['LOG_LEVEL'] = cli_args.LOG_LEVEL
logger = hb_log.config_logging(CONFIG['LOGGER'])
logger.info('\n\nCopyright (c) 2013, 2014, 2015, 2016, 2018\n\tThe Founding Members of the K0USY Group. All rights reserved.\n')
logger.debug('Logging system started, anything from here on gets logged')
# Set up the signal handler
def sig_handler(_signal, _frame):
logger.info('SHUTDOWN: HBROUTER IS TERMINATING WITH SIGNAL %s', str(_signal))
hblink_handler(_signal, _frame)
logger.info('SHUTDOWN: ALL SYSTEM HANDLERS EXECUTED - STOPPING REACTOR')
reactor.stop()
# Set signal handers so that we can gracefully exit if need be
for sig in [signal.SIGTERM, signal.SIGINT]:
signal.signal(sig, sig_handler)
# Create the name-number mapping dictionaries
peer_ids, subscriber_ids, talkgroup_ids = mk_aliases(CONFIG)
# INITIALIZE THE REPORTING LOOP
report_server = config_reports(CONFIG, reportFactory)
# HBlink instance creation
logger.info('HBlink \'hb_bridge_all.py\' -- SYSTEM STARTING...')
for system in CONFIG['SYSTEMS']:
if CONFIG['SYSTEMS'][system]['ENABLED']:
if CONFIG['SYSTEMS'][system]['MODE'] == 'OPENBRIDGE':
logger.critical('%s FATAL: Instance is mode \'OPENBRIDGE\', \n\t\t...Which would be tragic for Bridge All, since it carries multiple call\n\t\tstreams simultaneously. hb_bridge_all.py onlyl works with MMDVM-based systems', system)
sys.exit('hb_bridge_all.py cannot function with systems that are not MMDVM devices. System {} is configured as an OPENBRIDGE'.format(system))
else:
systems[system] = bridgeallSYSTEM(system, CONFIG, report_server)
reactor.listenUDP(CONFIG['SYSTEMS'][system]['PORT'], systems[system], interface=CONFIG['SYSTEMS'][system]['IP'])
logger.debug('%s instance created: %s, %s', CONFIG['SYSTEMS'][system]['MODE'], system, systems[system])
reactor.run()
| gpl-3.0 | 960,318,455,813,328,300 | 50.011407 | 246 | 0.534586 | false |
f-cap/sen | sen/tui/constants.py | 1 | 6074 |
MAIN_LIST_FOCUS = "main_list_focus"
STATUS_BG = "#06a"
STATUS_BG_FOCUS = "#08d"
# name, fg, bg, mono, fg_h, bg_h
PALLETE = [
(MAIN_LIST_FOCUS, 'default', 'brown', "default", "white", "#060"), # a60
('main_list_lg', 'light gray', 'default', "default", "g100", "default"),
('main_list_dg', 'dark gray', 'default', "default", "g78", "default"),
('main_list_ddg', 'dark gray', 'default', "default", "g56", "default"),
('main_list_white', 'white', 'default', "default", "white", "default"),
('main_list_green', 'dark green', 'default', "default", "#0f0", "default"),
('main_list_yellow', 'brown', 'default', "default", "#ff0", "default"),
('main_list_orange', 'light red', 'default', "default", "#fa0", "default"),
('main_list_red', 'dark red', 'default', "default", "#f00", "default"),
('image_names', 'light magenta', 'default', "default", "#F0F", "default"),
('status_box', 'default', 'black', "default", "g100", STATUS_BG),
('status_box_focus', 'default', 'black', "default", "white", STATUS_BG_FOCUS),
('status', 'default', 'default', "default", "default", STATUS_BG),
('status_text', 'default', 'default', "default", "g100", STATUS_BG),
('status_text_green', 'default', 'default', "default", "#0f0", STATUS_BG),
('status_text_yellow', 'default', 'default', "default", "#ff0", STATUS_BG),
('status_text_orange', 'default', 'default', "default", "#f80", STATUS_BG),
('status_text_red', 'default', 'default', "default", "#f66", STATUS_BG),
('notif_error', "white", 'dark red', "default", "white", "#f00",),
('notif_info', 'white', 'default', "default", "g100", "default"),
('notif_important', 'white', 'default', "default", "white", "default"),
('notif_text_green', 'white', 'default', "white", "#0f0", "default"),
('notif_text_yellow', 'white', 'default', "white", "#ff0", "default"),
('notif_text_orange', 'white', 'default', "white", "#f80", "default"),
('notif_text_red', 'white', 'default', "white", "#f66", "default"),
('tree', 'dark green', 'default', "default", "dark green", "default"),
('graph_bg', "default", 'default', "default", "default", "default"),
('graph_lines_cpu', "default", 'default', "default", "default", "#d63"),
('graph_lines_cpu_tips', "default", 'default', "default", "#d63", "default"),
('graph_lines_cpu_legend', "default", 'default', "default", "#f96", "default"),
('graph_lines_mem', "default", 'default', "default", "default", "#39f"),
('graph_lines_mem_tips', "default", 'default', "default", "#39f", "default"),
('graph_lines_mem_legend', "default", 'default', "default", "#6af", "default"),
('graph_lines_blkio_r', "default", 'default', "default", "default", "#9b0"),
('graph_lines_blkio_r_tips', "default", 'default', "default", "#9b0", "default"),
('graph_lines_blkio_r_legend', "default", 'default', "default", "#cf0", "default"),
('graph_lines_blkio_w', "default", 'default', "default", "default", "#b90"),
('graph_lines_blkio_w_tips', "default", 'default', "default", "#b90", "default"),
('graph_lines_blkio_w_legend', "default", 'default', "default", "#fc0", "default"),
('graph_lines_net_r', "default", 'default', "default", "default", "#3ca"),
('graph_lines_net_r_tips', "default", 'default', "default", "#3ca", "default"),
('graph_lines_net_r_legend', "default", 'default', "default", "#6fc", "default"),
('graph_lines_net_w', "default", 'default', "default", "default", "#3ac"),
('graph_lines_net_w_tips', "default", 'default', "default", "#3ac", "default"),
('graph_lines_net_w_legend', "default", 'default', "default", "#6cf", "default"),
]
STATUS_BAR_REFRESH_SECONDS = 5
CLEAR_NOTIF_BAR_MESSAGE_IN = 5
# FIXME: generate dynamically now
HELP_TEXT = """\
# Keybindings
Since I am a heavy `vim` user, these keybindings are trying to stay close to vim.
## Global
/ search (provide empty query to disable searching)
n next search occurrence
N previous search occurrence
f4 display only lines matching provided query (provide empty query to clear filtering)
* main listing provides additional filtering (for more info, check Listing Section)
* example query: "fed" - display lines containing string "fed"
f5 open a tree view of all images (`docker images --tree` equivalent)
ctrl o next buffer
ctrl i previous buffer
x remove buffer
ctrl l redraw user interface
h, ? show help
## Movement
gg go to first item
G go to last item
j go one line down
k go one line up
pg up
ctrl u go 10 lines up
pg down
ctrl d go 10 lines down
## Listing
@ refresh listing
f4 display only lines matching provided query (provide empty query to clear filtering)
* space-separated list of query strings, currently supported filters are:
* t[ype]=c[ontainer[s]]
* t[ype]=i[mage[s]]
* s[tate]=r[unning])
example query may be:
* "type=container" - show only containers (short equivalent is "t=c")
* "type=image fedora" - show images with string "fedora" in name (equivalent "t=i fedora")
## Image commands in listing
i inspect image
d remove image (irreversible!)
enter display detailed info about image (when layer is focused)
## Container commands in listing
i inspect container
l display logs of container
f follow logs of container
d remove container (irreversible!)
t stop container
s start container
r restart container
p pause container
u unpause container
X kill container
! toggle realtime updates of the interface (this is useful when you are removing multiple
objects and don't want the listing change during that so you accidentally remove something)
## Tree buffer
enter display detailed info about image (opens image info buffer)
## Image info buffer
d remove image tag (when image name is focused)
enter display detailed info about image (when layer is focused)
i inspect image (when layer is focused)
"""
| mit | 6,278,611,867,250,509,000 | 42.697842 | 101 | 0.623477 | false |
zenoss/metrology | metrology/registry.py | 1 | 2345 | import inspect
from threading import RLock
from metrology.exceptions import RegistryException
from metrology.instruments import Counter, Derive, Profiler, Meter, Timer, UtilizationTimer, HistogramUniform
class Registry(object):
def __init__(self):
self.lock = RLock()
self.metrics = {}
def clear(self):
with self.lock:
for metric in self.metrics.values():
if hasattr(metric, 'stop'):
metric.stop()
self.metrics.clear()
def counter(self, name):
return self.add_or_get(name, Counter)
def meter(self, name):
return self.add_or_get(name, Meter)
def gauge(self, name, klass):
return self.add_or_get(name, klass)
def timer(self, name):
return self.add_or_get(name, Timer)
def utilization_timer(self, name):
return self.add_or_get(name, UtilizationTimer)
def health_check(self, name, klass):
return self.add_or_get(name, klass)
def histogram(self, name, klass=None):
if not klass:
klass = HistogramUniform
return self.add_or_get(name, klass)
def derive(self, name):
return self.add_or_get(name, Derive)
def profiler(self, name):
return self.add_or_get(name, Profiler)
def get(self, name):
with self.lock:
return self.metrics[name]
def add(self, name, metric):
with self.lock:
if name in self.metrics:
raise RegistryException("{0} already present in the registry.".format(name))
else:
self.metrics[name] = metric
def add_or_get(self, name, klass):
with self.lock:
metric = self.metrics.get(name)
if metric is not None:
if not isinstance(metric, klass):
raise RegistryException("{0} is not of type {1}.".format(name, klass))
else:
if inspect.isclass(klass):
metric = klass()
else:
metric = klass
self.metrics[name] = metric
return metric
def stop(self):
self.clear()
def __iter__(self):
with self.lock:
for name, metric in self.metrics.items():
yield name, metric
registry = Registry()
| mit | 3,099,961,023,612,505,000 | 27.253012 | 109 | 0.568443 | false |
Tivix/django-spam | demo/demo/settings.py | 1 | 2540 | """
Django settings for demo project.
Generated by 'django-admin startproject' using Django 1.11.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'demo-key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_spam',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'demo.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'demo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
| mit | 8,307,893,044,195,437,000 | 23.423077 | 72 | 0.685039 | false |
kmhughes/robotbrains-examples | comm/mqtt/python/mqttclient.py | 1 | 2058 | ##
# Copyright (C) 2015 Keith M. Hughes.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
##
import jprops
import paho.mqtt.client as mqtt
import json
# The callback for when the MQTT client gets an acknowledgement from the MQTT
# server.
def on_connect(client, userdata, rc):
print("Connected with result code "+str(rc))
# Only subscribe if the connection was successful
if rc eq 0:
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("/greeting")
data = { 'foo' : 1}
client.publish("/greeting", json.dumps(data))
# The callback for when te MQTT client receives a publiched message for a
# topic it is subscribed to
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
# Read the properties that define user names and passwords.
#
# A Java properties file is being used so that the same properties can
# be used in both languages.
with open('/Users/keith/mqtt.properties') as fp:
properties = jprops.load_properties(fp)
# Create the client.
client = mqtt.Client()
# Set the methods to use for connection and message receiving
client.on_connect = on_connect
client.on_message = on_message
# Set the user name and password from the properties
client.username_pw_set(properties['mqtt.username'], properties['mqtt.password'])
# Connect to the server.
client.connect("smartspaces.io", 1883, 60)
# This method will not return and will continually loop to receive network
# traffic.
client.loop_forever()
| apache-2.0 | 3,648,597,902,645,912,000 | 32.737705 | 80 | 0.740525 | false |
Nep-gear/nep-bio | py_atm/trigger_calibracion.py | 1 | 1853 | import time
from nep import*
import signal
import sys
import datetime as dt
def time_diference(str_t1,str_t2):
try:
y = dt.datetime.strptime(str_t1, "%Y-%m-%d %H:%M:%S.%f")
except:
y = dt.datetime.strptime(str_t1, "%Y-%m-%d %H:%M:%S")
try:
x = dt.datetime.strptime(str_t2, "%Y-%m-%d %H:%M:%S.%f")
except:
x = dt.datetime.strptime(str_t2, "%Y-%m-%d %H:%M:%S")
diff_h = abs(x.hour - y.hour)
diff_min = abs(x.minute - y.minute)
diff_sec = abs(x.second - y.second)
diff_micro = abs(x.microsecond - y.microsecond)
print str(diff_h) + ":" + str(diff_min) + ":" + str(diff_sec) + "." + str(diff_micro)
def signal_handler(signal, frame):
"""Signal handler used to close the app"""
print('Signal Handler, you pressed Ctrl+C!')
print('Exit in 2 seconds...')
time.sleep(2)
sys.exit()
# New signal handler
signal.signal(signal.SIGINT, signal_handler)
lan = launcher()
lan.launch("camera1.py")
lan.launch("camera2.py")
time.sleep(5)
y = raw_input("Press ENTER to start comunication")
print ("....")
pub = publisher("/trigger", True)
##sub1 = subscriber("/force_plate", False)
sub1 = subscriber("/camera1", False)
sub2 = subscriber("/camera2", False)
# Test comunication, not change ----
msg = {'trigger':3}
pub.send_info(msg)
time.sleep(.2)
pub.send_info(msg)
time.sleep(.2)
pub.send_info(msg)
# ----------------------------------
print
y = raw_input("Press ENTER to get a new image || Press c + enter to finish")
msg = {'trigger':1}
pub.send_info(msg)
new = True
while new:
y = raw_input("Waiting new enter ....")
if(y == "c"):
msg = {'trigger':2}
pub.send_info(msg)
new = False
else:
pub.send_info(msg)
print('Exit in 2 seconds...')
time.sleep(2)
sys.exit()
| mit | -338,504,633,992,957,000 | 20.298851 | 90 | 0.576363 | false |
omangin/multimodal | multimodal/learner.py | 1 | 3766 | # encoding: utf-8
"""Class to abstract learning from multiple modalities."""
from .lib.nmf import KLdivNMF as NMF
from .lib.array_utils import safe_hstack
def fit_coefficients(data_obs, dictionary, iter_nmf=100, verbose=False):
nmf_obs = NMF(n_components=dictionary.shape[0], max_iter=iter_nmf, tol=0)
nmf_obs.components_ = dictionary
coefficients = nmf_obs.transform(data_obs, scale_W=True)
return coefficients
class MultimodalLearner(object):
def __init__(self, modalities, dimensions, coefficients, k,
sparseness=None, sp_coef=.1):
self.mod = modalities # Names of the modalities
self.dim = dimensions # Dimensions of modalities
self.coef = coefficients # Coefficients used to compensate
# between modalities
self.k = k
self.sparseness = sparseness # data, components, None
self.sp_coef = sp_coef
self.dico = None # None means not trained yet
def train(self, data_matrices, iterations):
n_samples = data_matrices[0].shape[0]
for m, d in zip(data_matrices, self.dim):
assert(m.shape == (n_samples, d))
Vtrain = self.stack_data(self.mod, data_matrices)
# Perform the experiment
if self.sparseness is not None:
raise NotImplemented
self.nmf_train = NMF(n_components=self.k, max_iter=iterations, tol=0)
self.nmf_train.fit(Vtrain, scale_W=True)
self.dico = self.nmf_train.components_
def get_dico(self, modality=None):
if modality is None:
return self.dico
else:
start, stop = self.get_axis_range(modality)
return self.dico[:, start:stop]
def get_stacked_dicos(self, modalities):
return safe_hstack([self.get_dico(modality=m) for m in modalities])
def stack_data(self, modalities, data_matrices):
coefs = [self.coef[self.get_index(mod)] for mod in modalities]
return safe_hstack([c * m
for m, c in zip(data_matrices, coefs)])
def get_axis_range(self, modality):
idx = self.get_index(modality)
start = sum(self.dim[:idx])
stop = start + self.dim[idx]
return (start, stop)
def get_index(self, modality):
return self.mod.index(modality)
def reconstruct_internal(self, orig_mod, test_data, iterations):
return self.reconstruct_internal_multi([orig_mod], [test_data],
iterations)
def reconstruct_internal_multi(self, orig_mods, test_data, iterations):
for mod, data in zip(orig_mods, test_data):
assert(data.shape[1] == self.dim[self.get_index(mod)])
stacked_dico = self.get_stacked_dicos(orig_mods)
stacked_data = self.stack_data(orig_mods, test_data)
internal = fit_coefficients(stacked_data, stacked_dico,
iter_nmf=iterations)
return internal
def reconstruct_modality(self, dest_mod, internal):
return internal.dot(self.get_dico(dest_mod))
def reconstruct_modalities(self, dest_mods, internal):
return internal.dot(self.get_stacked_dicos(dest_mods))
def modality_to_modality(self, orig_mod, dest_mod, test_data, iterations):
return self.modalities_to_modalities([orig_mod], [dest_mod],
[test_data], iterations)
def modalities_to_modalities(self, orig_mods, dest_mods, test_data,
iterations):
internal = self.reconstruct_internal_multi(orig_mods, test_data,
iterations)
return self.reconstruct_modalities(dest_mods, internal)
| bsd-3-clause | -7,851,279,790,040,370,000 | 39.06383 | 78 | 0.611524 | false |
sweerpotato/Darkness | darkness.py | 1 | 2984 | from __future__ import print_function
import sys
class Direction:
NORTH = 1
EAST = 2
SOUTH = 3
WEST = 4
def ERROR(s):
sys.exit("ERROR: " + s)
def check_darkness_size(lines):
columns = len(lines[0])
for line in lines:
if(len(line) != columns):
ERROR("MALFORMED DARKNESS")
def generate_darkness(program):
lines = program.split("\n")
check_darkness_size(lines)
darkness = [[char for char in line] for line in lines]
return darkness
def navigate(darkness):
debug = False
value = 0
direction = Direction.EAST
increment_mode = True
ascii = False
x, y = 0, 0
#Flipped darkness, real world solution
while darkness[y][x] != ' ':
op = darkness[y][x].encode("utf-8")
if(debug is True):
print("DEBUG: op is " + op.decode("utf-8") + ", x is " + chr(x + 48) + ", y is " + chr(y + 48))
if(op == "█"):
if(increment_mode is False and value != 0):
value -= 1
elif(increment_mode is True):
value += 1
elif(op == "▀"):
increment_mode = True
elif(op == "▄"):
increment_mode = False
elif(op == "■"):
if(ascii is True):
print(chr(value), end = "")
else:
print(value, end = "")
elif(op == "─"):
ascii = not ascii
elif(op == "╬" or op == "┼"):
if(direction == Direction.NORTH):
if(value != 0):
direction = Direction.EAST
else:
direction = Direction.WEST
elif(direction == Direction.EAST):
if(value != 0):
direction = Direction.SOUTH
else:
direction = Direction.NORTH
elif(direction == Direction.SOUTH):
if(value != 0):
direction = Direction.WEST
else:
direction = Direction.EAST
elif(direction == Direction.WEST):
if(value != 0):
direction = Direction.NORTH
else:
direction = Direction.SOUTH
if(op == "┼"):
value = 0
if(debug is True):
print("DEBUG: DIRECTION IS " + chr(direction + 48))
if(direction == Direction.NORTH):
y -= 1
elif(direction == Direction.EAST):
x += 1
elif(direction == Direction.SOUTH):
y += 1
elif(direction == Direction.WEST):
x -= 1
def main():
if(len(sys.argv) > 1):
program = open(sys.argv[-1], "r").read().decode("string-escape").decode("utf-8")
darkness = generate_darkness(program)
navigate(darkness)
else:
ERROR("EXPECTED FILE")
if __name__ == '__main__':
main() | mit | 2,270,772,790,524,705,300 | 27.528846 | 107 | 0.463924 | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.