repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
macs03/demo-cms
cms/lib/python2.7/site-packages/reversion/south_migrations/0001_initial.py
15
6489
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Revision' db.create_table('reversion_revision', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm["%s.%s" % (User._meta.app_label, User._meta.object_name)], null=True, blank=True)), ('comment', self.gf('django.db.models.fields.TextField')(blank=True)), )) db.send_create_signal('reversion', ['Revision']) # Adding model 'Version' db.create_table('reversion_version', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('revision', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['reversion.Revision'])), ('object_id', self.gf('django.db.models.fields.TextField')()), ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])), ('format', self.gf('django.db.models.fields.CharField')(max_length=255)), ('serialized_data', self.gf('django.db.models.fields.TextField')()), ('object_repr', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal('reversion', ['Version']) def backwards(self, orm): # Deleting model 'Revision' db.delete_table('reversion_revision') # Deleting model 'Version' db.delete_table('reversion_version') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, "%s.%s" % (User._meta.app_label, User._meta.module_name): { 'Meta': {'object_name': User.__name__, "db_table": "'%s'" % User._meta.db_table}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), User._meta.pk.column: ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'reversion.revision': { 'Meta': {'object_name': 'Revision'}, 'comment': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name), 'null': 'True', 'blank': 'True'}) }, 'reversion.version': { 'Meta': {'object_name': 'Version'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'format': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.TextField', [], {}), 'object_repr': ('django.db.models.fields.TextField', [], {}), 'revision': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['reversion.Revision']"}), 'serialized_data': ('django.db.models.fields.TextField', [], {}) } } complete_apps = ['reversion']
mit
moijes12/oh-mainline
vendor/packages/gdata/src/gdata/tlslite/messages.py
273
18429
"""Classes representing TLS messages.""" from utils.compat import * from utils.cryptomath import * from errors import * from utils.codec import * from constants import * from X509 import X509 from X509CertChain import X509CertChain import sha import md5 class RecordHeader3: def __init__(self): self.type = 0 self.version = (0,0) self.length = 0 self.ssl2 = False def create(self, version, type, length): self.type = type self.version = version self.length = length return self def write(self): w = Writer(5) w.add(self.type, 1) w.add(self.version[0], 1) w.add(self.version[1], 1) w.add(self.length, 2) return w.bytes def parse(self, p): self.type = p.get(1) self.version = (p.get(1), p.get(1)) self.length = p.get(2) self.ssl2 = False return self class RecordHeader2: def __init__(self): self.type = 0 self.version = (0,0) self.length = 0 self.ssl2 = True def parse(self, p): if p.get(1)!=128: raise SyntaxError() self.type = ContentType.handshake self.version = (2,0) #We don't support 2-byte-length-headers; could be a problem self.length = p.get(1) return self class Msg: def preWrite(self, trial): if trial: w = Writer() else: length = self.write(True) w = Writer(length) return w def postWrite(self, w, trial): if trial: return w.index else: return w.bytes class Alert(Msg): def __init__(self): self.contentType = ContentType.alert self.level = 0 self.description = 0 def create(self, description, level=AlertLevel.fatal): self.level = level self.description = description return self def parse(self, p): p.setLengthCheck(2) self.level = p.get(1) self.description = p.get(1) p.stopLengthCheck() return self def write(self): w = Writer(2) w.add(self.level, 1) w.add(self.description, 1) return w.bytes class HandshakeMsg(Msg): def preWrite(self, handshakeType, trial): if trial: w = Writer() w.add(handshakeType, 1) w.add(0, 3) else: length = self.write(True) w = Writer(length) w.add(handshakeType, 1) w.add(length-4, 3) return w class ClientHello(HandshakeMsg): def __init__(self, ssl2=False): self.contentType = ContentType.handshake self.ssl2 = ssl2 self.client_version = (0,0) self.random = createByteArrayZeros(32) self.session_id = createByteArraySequence([]) self.cipher_suites = [] # a list of 16-bit values self.certificate_types = [CertificateType.x509] self.compression_methods = [] # a list of 8-bit values self.srp_username = None # a string def create(self, version, random, session_id, cipher_suites, certificate_types=None, srp_username=None): self.client_version = version self.random = random self.session_id = session_id self.cipher_suites = cipher_suites self.certificate_types = certificate_types self.compression_methods = [0] self.srp_username = srp_username return self def parse(self, p): if self.ssl2: self.client_version = (p.get(1), p.get(1)) cipherSpecsLength = p.get(2) sessionIDLength = p.get(2) randomLength = p.get(2) self.cipher_suites = p.getFixList(3, int(cipherSpecsLength/3)) self.session_id = p.getFixBytes(sessionIDLength) self.random = p.getFixBytes(randomLength) if len(self.random) < 32: zeroBytes = 32-len(self.random) self.random = createByteArrayZeros(zeroBytes) + self.random self.compression_methods = [0]#Fake this value #We're not doing a stopLengthCheck() for SSLv2, oh well.. else: p.startLengthCheck(3) self.client_version = (p.get(1), p.get(1)) self.random = p.getFixBytes(32) self.session_id = p.getVarBytes(1) self.cipher_suites = p.getVarList(2, 2) self.compression_methods = p.getVarList(1, 1) if not p.atLengthCheck(): totalExtLength = p.get(2) soFar = 0 while soFar != totalExtLength: extType = p.get(2) extLength = p.get(2) if extType == 6: self.srp_username = bytesToString(p.getVarBytes(1)) elif extType == 7: self.certificate_types = p.getVarList(1, 1) else: p.getFixBytes(extLength) soFar += 4 + extLength p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.client_hello, trial) w.add(self.client_version[0], 1) w.add(self.client_version[1], 1) w.addFixSeq(self.random, 1) w.addVarSeq(self.session_id, 1, 1) w.addVarSeq(self.cipher_suites, 2, 2) w.addVarSeq(self.compression_methods, 1, 1) extLength = 0 if self.certificate_types and self.certificate_types != \ [CertificateType.x509]: extLength += 5 + len(self.certificate_types) if self.srp_username: extLength += 5 + len(self.srp_username) if extLength > 0: w.add(extLength, 2) if self.certificate_types and self.certificate_types != \ [CertificateType.x509]: w.add(7, 2) w.add(len(self.certificate_types)+1, 2) w.addVarSeq(self.certificate_types, 1, 1) if self.srp_username: w.add(6, 2) w.add(len(self.srp_username)+1, 2) w.addVarSeq(stringToBytes(self.srp_username), 1, 1) return HandshakeMsg.postWrite(self, w, trial) class ServerHello(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake self.server_version = (0,0) self.random = createByteArrayZeros(32) self.session_id = createByteArraySequence([]) self.cipher_suite = 0 self.certificate_type = CertificateType.x509 self.compression_method = 0 def create(self, version, random, session_id, cipher_suite, certificate_type): self.server_version = version self.random = random self.session_id = session_id self.cipher_suite = cipher_suite self.certificate_type = certificate_type self.compression_method = 0 return self def parse(self, p): p.startLengthCheck(3) self.server_version = (p.get(1), p.get(1)) self.random = p.getFixBytes(32) self.session_id = p.getVarBytes(1) self.cipher_suite = p.get(2) self.compression_method = p.get(1) if not p.atLengthCheck(): totalExtLength = p.get(2) soFar = 0 while soFar != totalExtLength: extType = p.get(2) extLength = p.get(2) if extType == 7: self.certificate_type = p.get(1) else: p.getFixBytes(extLength) soFar += 4 + extLength p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.server_hello, trial) w.add(self.server_version[0], 1) w.add(self.server_version[1], 1) w.addFixSeq(self.random, 1) w.addVarSeq(self.session_id, 1, 1) w.add(self.cipher_suite, 2) w.add(self.compression_method, 1) extLength = 0 if self.certificate_type and self.certificate_type != \ CertificateType.x509: extLength += 5 if extLength != 0: w.add(extLength, 2) if self.certificate_type and self.certificate_type != \ CertificateType.x509: w.add(7, 2) w.add(1, 2) w.add(self.certificate_type, 1) return HandshakeMsg.postWrite(self, w, trial) class Certificate(HandshakeMsg): def __init__(self, certificateType): self.certificateType = certificateType self.contentType = ContentType.handshake self.certChain = None def create(self, certChain): self.certChain = certChain return self def parse(self, p): p.startLengthCheck(3) if self.certificateType == CertificateType.x509: chainLength = p.get(3) index = 0 certificate_list = [] while index != chainLength: certBytes = p.getVarBytes(3) x509 = X509() x509.parseBinary(certBytes) certificate_list.append(x509) index += len(certBytes)+3 if certificate_list: self.certChain = X509CertChain(certificate_list) elif self.certificateType == CertificateType.cryptoID: s = bytesToString(p.getVarBytes(2)) if s: try: import cryptoIDlib.CertChain except ImportError: raise SyntaxError(\ "cryptoID cert chain received, cryptoIDlib not present") self.certChain = cryptoIDlib.CertChain.CertChain().parse(s) else: raise AssertionError() p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.certificate, trial) if self.certificateType == CertificateType.x509: chainLength = 0 if self.certChain: certificate_list = self.certChain.x509List else: certificate_list = [] #determine length for cert in certificate_list: bytes = cert.writeBytes() chainLength += len(bytes)+3 #add bytes w.add(chainLength, 3) for cert in certificate_list: bytes = cert.writeBytes() w.addVarSeq(bytes, 1, 3) elif self.certificateType == CertificateType.cryptoID: if self.certChain: bytes = stringToBytes(self.certChain.write()) else: bytes = createByteArraySequence([]) w.addVarSeq(bytes, 1, 2) else: raise AssertionError() return HandshakeMsg.postWrite(self, w, trial) class CertificateRequest(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake self.certificate_types = [] #treat as opaque bytes for now self.certificate_authorities = createByteArraySequence([]) def create(self, certificate_types, certificate_authorities): self.certificate_types = certificate_types self.certificate_authorities = certificate_authorities return self def parse(self, p): p.startLengthCheck(3) self.certificate_types = p.getVarList(1, 1) self.certificate_authorities = p.getVarBytes(2) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.certificate_request, trial) w.addVarSeq(self.certificate_types, 1, 1) w.addVarSeq(self.certificate_authorities, 1, 2) return HandshakeMsg.postWrite(self, w, trial) class ServerKeyExchange(HandshakeMsg): def __init__(self, cipherSuite): self.cipherSuite = cipherSuite self.contentType = ContentType.handshake self.srp_N = 0L self.srp_g = 0L self.srp_s = createByteArraySequence([]) self.srp_B = 0L self.signature = createByteArraySequence([]) def createSRP(self, srp_N, srp_g, srp_s, srp_B): self.srp_N = srp_N self.srp_g = srp_g self.srp_s = srp_s self.srp_B = srp_B return self def parse(self, p): p.startLengthCheck(3) self.srp_N = bytesToNumber(p.getVarBytes(2)) self.srp_g = bytesToNumber(p.getVarBytes(2)) self.srp_s = p.getVarBytes(1) self.srp_B = bytesToNumber(p.getVarBytes(2)) if self.cipherSuite in CipherSuite.srpRsaSuites: self.signature = p.getVarBytes(2) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.server_key_exchange, trial) w.addVarSeq(numberToBytes(self.srp_N), 1, 2) w.addVarSeq(numberToBytes(self.srp_g), 1, 2) w.addVarSeq(self.srp_s, 1, 1) w.addVarSeq(numberToBytes(self.srp_B), 1, 2) if self.cipherSuite in CipherSuite.srpRsaSuites: w.addVarSeq(self.signature, 1, 2) return HandshakeMsg.postWrite(self, w, trial) def hash(self, clientRandom, serverRandom): oldCipherSuite = self.cipherSuite self.cipherSuite = None try: bytes = clientRandom + serverRandom + self.write()[4:] s = bytesToString(bytes) return stringToBytes(md5.md5(s).digest() + sha.sha(s).digest()) finally: self.cipherSuite = oldCipherSuite class ServerHelloDone(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake def create(self): return self def parse(self, p): p.startLengthCheck(3) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.server_hello_done, trial) return HandshakeMsg.postWrite(self, w, trial) class ClientKeyExchange(HandshakeMsg): def __init__(self, cipherSuite, version=None): self.cipherSuite = cipherSuite self.version = version self.contentType = ContentType.handshake self.srp_A = 0 self.encryptedPreMasterSecret = createByteArraySequence([]) def createSRP(self, srp_A): self.srp_A = srp_A return self def createRSA(self, encryptedPreMasterSecret): self.encryptedPreMasterSecret = encryptedPreMasterSecret return self def parse(self, p): p.startLengthCheck(3) if self.cipherSuite in CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites: self.srp_A = bytesToNumber(p.getVarBytes(2)) elif self.cipherSuite in CipherSuite.rsaSuites: if self.version in ((3,1), (3,2)): self.encryptedPreMasterSecret = p.getVarBytes(2) elif self.version == (3,0): self.encryptedPreMasterSecret = \ p.getFixBytes(len(p.bytes)-p.index) else: raise AssertionError() else: raise AssertionError() p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.client_key_exchange, trial) if self.cipherSuite in CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites: w.addVarSeq(numberToBytes(self.srp_A), 1, 2) elif self.cipherSuite in CipherSuite.rsaSuites: if self.version in ((3,1), (3,2)): w.addVarSeq(self.encryptedPreMasterSecret, 1, 2) elif self.version == (3,0): w.addFixSeq(self.encryptedPreMasterSecret, 1) else: raise AssertionError() else: raise AssertionError() return HandshakeMsg.postWrite(self, w, trial) class CertificateVerify(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake self.signature = createByteArraySequence([]) def create(self, signature): self.signature = signature return self def parse(self, p): p.startLengthCheck(3) self.signature = p.getVarBytes(2) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.certificate_verify, trial) w.addVarSeq(self.signature, 1, 2) return HandshakeMsg.postWrite(self, w, trial) class ChangeCipherSpec(Msg): def __init__(self): self.contentType = ContentType.change_cipher_spec self.type = 1 def create(self): self.type = 1 return self def parse(self, p): p.setLengthCheck(1) self.type = p.get(1) p.stopLengthCheck() return self def write(self, trial=False): w = Msg.preWrite(self, trial) w.add(self.type,1) return Msg.postWrite(self, w, trial) class Finished(HandshakeMsg): def __init__(self, version): self.contentType = ContentType.handshake self.version = version self.verify_data = createByteArraySequence([]) def create(self, verify_data): self.verify_data = verify_data return self def parse(self, p): p.startLengthCheck(3) if self.version == (3,0): self.verify_data = p.getFixBytes(36) elif self.version in ((3,1), (3,2)): self.verify_data = p.getFixBytes(12) else: raise AssertionError() p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.finished, trial) w.addFixSeq(self.verify_data, 1) return HandshakeMsg.postWrite(self, w, trial) class ApplicationData(Msg): def __init__(self): self.contentType = ContentType.application_data self.bytes = createByteArraySequence([]) def create(self, bytes): self.bytes = bytes return self def parse(self, p): self.bytes = p.bytes return self def write(self): return self.bytes
agpl-3.0
DiptoDas8/Biponi
lib/python2.7/site-packages/PIL/BdfFontFile.py
39
3355
# # The Python Imaging Library # $Id$ # # bitmap distribution font (bdf) file parser # # history: # 1996-05-16 fl created (as bdf2pil) # 1997-08-25 fl converted to FontFile driver # 2001-05-25 fl removed bogus __init__ call # 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev) # 2003-04-22 fl more robustification (from Graham Dumpleton) # # Copyright (c) 1997-2003 by Secret Labs AB. # Copyright (c) 1997-2003 by Fredrik Lundh. # # See the README file for information on usage and redistribution. # from PIL import Image from PIL import FontFile # -------------------------------------------------------------------- # parse X Bitmap Distribution Format (BDF) # -------------------------------------------------------------------- bdf_slant = { "R": "Roman", "I": "Italic", "O": "Oblique", "RI": "Reverse Italic", "RO": "Reverse Oblique", "OT": "Other" } bdf_spacing = { "P": "Proportional", "M": "Monospaced", "C": "Cell" } def bdf_char(f): # skip to STARTCHAR while True: s = f.readline() if not s: return None if s[:9] == b"STARTCHAR": break id = s[9:].strip().decode('ascii') # load symbol properties props = {} while True: s = f.readline() if not s or s[:6] == b"BITMAP": break i = s.find(b" ") props[s[:i].decode('ascii')] = s[i+1:-1].decode('ascii') # load bitmap bitmap = [] while True: s = f.readline() if not s or s[:7] == b"ENDCHAR": break bitmap.append(s[:-1]) bitmap = b"".join(bitmap) [x, y, l, d] = [int(p) for p in props["BBX"].split()] [dx, dy] = [int(p) for p in props["DWIDTH"].split()] bbox = (dx, dy), (l, -d-y, x+l, -d), (0, 0, x, y) try: im = Image.frombytes("1", (x, y), bitmap, "hex", "1") except ValueError: # deal with zero-width characters im = Image.new("1", (x, y)) return id, int(props["ENCODING"]), bbox, im ## # Font file plugin for the X11 BDF format. class BdfFontFile(FontFile.FontFile): def __init__(self, fp): FontFile.FontFile.__init__(self) s = fp.readline() if s[:13] != b"STARTFONT 2.1": raise SyntaxError("not a valid BDF file") props = {} comments = [] while True: s = fp.readline() if not s or s[:13] == b"ENDPROPERTIES": break i = s.find(b" ") props[s[:i].decode('ascii')] = s[i+1:-1].decode('ascii') if s[:i] in [b"COMMENT", b"COPYRIGHT"]: if s.find(b"LogicalFontDescription") < 0: comments.append(s[i+1:-1].decode('ascii')) font = props["FONT"].split("-") font[4] = bdf_slant[font[4].upper()] font[11] = bdf_spacing[font[11].upper()] # ascent = int(props["FONT_ASCENT"]) # descent = int(props["FONT_DESCENT"]) # fontname = ";".join(font[1:]) # print "#", fontname # for i in comments: # print "#", i font = [] while True: c = bdf_char(fp) if not c: break id, ch, (xy, dst, src), im = c if 0 <= ch < len(self.glyph): self.glyph[ch] = xy, dst, src, im
mit
Alwnikrotikz/pyicqt
src/services/Statistics.py
4
2247
# Copyright 2004-2006 Daniel Henninger <jadestorm@nc.rr.com> # Licensed for distribution under the GPL version 2, check COPYING for details import utils from twisted.words.xish.domish import Element import config import lang from debug import LogEvent, INFO, WARN, ERROR import globals class Statistics: def __init__(self, pytrans): self.pytrans = pytrans self.pytrans.adhoc.addCommand("stats", self.incomingIq, "command_Statistics") # self.stats is indexed by a unique ID, with value being the value for that statistic self.stats = {} self.stats["Uptime"] = 0 self.stats["OnlineSessions"] = 0 self.stats["IncomingMessages"] = 0 self.stats["OutgoingMessages"] = 0 self.stats["TotalSessions"] = 0 self.stats["MaxConcurrentSessions"] = 0 self.sessionstats = {} def sessionSetup(self, jid): self.sessionstats[jid] = { } self.sessionstats[jid]['IncomingMessages'] = 0 self.sessionstats[jid]['OutgoingMessages'] = 0 self.sessionstats[jid]['Connections'] = 0 def sessionUpdate(self, jid, setting, value): if not self.sessionstats.has_key(jid): self.sessionSetup(jid) self.sessionstats[jid][setting] += value def incomingIq(self, el): to = el.getAttribute("from") ID = el.getAttribute("id") ulang = utils.getLang(el) iq = Element((None, "iq")) iq.attributes["to"] = to iq.attributes["from"] = config.jid if ID: iq.attributes["id"] = ID iq.attributes["type"] = "result" command = iq.addElement("command") command.attributes["sessionid"] = self.pytrans.makeMessageID() command.attributes["xmlns"] = globals.COMMANDS command.attributes["status"] = "completed" x = command.addElement("x") x.attributes["xmlns"] = globals.XDATA x.attributes["type"] = "result" title = x.addElement("title") title.addContent(lang.get("command_Statistics", ulang)) for key in self.stats: label = lang.get("statistics_%s" % key, ulang) description = lang.get("statistics_%s_Desc" % key, ulang) field = x.addElement("field") field.attributes["var"] = key field.attributes["label"] = label field.attributes["type"] = "text-single" field.addElement("value").addContent(str(self.stats[key])) field.addElement("desc").addContent(description) self.pytrans.send(iq)
gpl-2.0
pmelendez-shomi/cb_console
node_modules/couchbase/node_modules/prebuild/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py
542
45270
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Notes: # # This generates makefiles suitable for inclusion into the Android build system # via an Android.mk file. It is based on make.py, the standard makefile # generator. # # The code below generates a separate .mk file for each target, but # all are sourced by the top-level GypAndroid.mk. This means that all # variables in .mk-files clobber one another, and furthermore that any # variables set potentially clash with other Android build system variables. # Try to avoid setting global variables where possible. import gyp import gyp.common import gyp.generator.make as make # Reuse global functions from make backend. import os import re import subprocess generator_default_variables = { 'OS': 'android', 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'SHARED_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'SHARED_LIB_SUFFIX': '.so', 'INTERMEDIATE_DIR': '$(gyp_intermediate_dir)', 'SHARED_INTERMEDIATE_DIR': '$(gyp_shared_intermediate_dir)', 'PRODUCT_DIR': '$(gyp_shared_intermediate_dir)', 'SHARED_LIB_DIR': '$(builddir)/lib.$(TOOLSET)', 'LIB_DIR': '$(obj).$(TOOLSET)', 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python. 'RULE_INPUT_DIRNAME': '%(INPUT_DIRNAME)s', # This gets expanded by Python. 'RULE_INPUT_PATH': '$(RULE_SOURCES)', 'RULE_INPUT_EXT': '$(suffix $<)', 'RULE_INPUT_NAME': '$(notdir $<)', 'CONFIGURATION_NAME': '$(GYP_CONFIGURATION)', } # Make supports multiple toolsets generator_supports_multiple_toolsets = True # Generator-specific gyp specs. generator_additional_non_configuration_keys = [ # Boolean to declare that this target does not want its name mangled. 'android_unmangled_name', # Map of android build system variables to set. 'aosp_build_settings', ] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] ALL_MODULES_FOOTER = """\ # "gyp_all_modules" is a concatenation of the "gyp_all_modules" targets from # all the included sub-makefiles. This is just here to clarify. gyp_all_modules: """ header = """\ # This file is generated by gyp; do not edit. """ # Map gyp target types to Android module classes. MODULE_CLASSES = { 'static_library': 'STATIC_LIBRARIES', 'shared_library': 'SHARED_LIBRARIES', 'executable': 'EXECUTABLES', } def IsCPPExtension(ext): return make.COMPILABLE_EXTENSIONS.get(ext) == 'cxx' def Sourceify(path): """Convert a path to its source directory form. The Android backend does not support options.generator_output, so this function is a noop.""" return path # Map from qualified target to path to output. # For Android, the target of these maps is a tuple ('static', 'modulename'), # ('dynamic', 'modulename'), or ('path', 'some/path') instead of a string, # since we link by module. target_outputs = {} # Map from qualified target to any linkable output. A subset # of target_outputs. E.g. when mybinary depends on liba, we want to # include liba in the linker line; when otherbinary depends on # mybinary, we just want to build mybinary first. target_link_deps = {} class AndroidMkWriter(object): """AndroidMkWriter packages up the writing of one target-specific Android.mk. Its only real entry point is Write(), and is mostly used for namespacing. """ def __init__(self, android_top_dir): self.android_top_dir = android_top_dir def Write(self, qualified_target, relative_target, base_path, output_filename, spec, configs, part_of_all, write_alias_target, sdk_version): """The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating relative_target: qualified target name relative to the root base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all' write_alias_target: flag indicating whether to create short aliases for this target sdk_version: what to emit for LOCAL_SDK_VERSION in output """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, 'w') self.fp.write(header) self.qualified_target = qualified_target self.relative_target = relative_target self.path = base_path self.target = spec['target_name'] self.type = spec['type'] self.toolset = spec['toolset'] deps, link_deps = self.ComputeDeps(spec) # Some of the generation below can add extra output, sources, or # link dependencies. All of the out params of the functions that # follow use names like extra_foo. extra_outputs = [] extra_sources = [] self.android_class = MODULE_CLASSES.get(self.type, 'GYP') self.android_module = self.ComputeAndroidModule(spec) (self.android_stem, self.android_suffix) = self.ComputeOutputParts(spec) self.output = self.output_binary = self.ComputeOutput(spec) # Standard header. self.WriteLn('include $(CLEAR_VARS)\n') # Module class and name. self.WriteLn('LOCAL_MODULE_CLASS := ' + self.android_class) self.WriteLn('LOCAL_MODULE := ' + self.android_module) # Only emit LOCAL_MODULE_STEM if it's different to LOCAL_MODULE. # The library module classes fail if the stem is set. ComputeOutputParts # makes sure that stem == modulename in these cases. if self.android_stem != self.android_module: self.WriteLn('LOCAL_MODULE_STEM := ' + self.android_stem) self.WriteLn('LOCAL_MODULE_SUFFIX := ' + self.android_suffix) if self.toolset == 'host': self.WriteLn('LOCAL_IS_HOST_MODULE := true') self.WriteLn('LOCAL_MULTILIB := $(GYP_HOST_MULTILIB)') else: self.WriteLn('LOCAL_MODULE_TARGET_ARCH := ' '$(TARGET_$(GYP_VAR_PREFIX)ARCH)') self.WriteLn('LOCAL_SDK_VERSION := %s' % sdk_version) # Grab output directories; needed for Actions and Rules. if self.toolset == 'host': self.WriteLn('gyp_intermediate_dir := ' '$(call local-intermediates-dir,,$(GYP_HOST_VAR_PREFIX))') else: self.WriteLn('gyp_intermediate_dir := ' '$(call local-intermediates-dir,,$(GYP_VAR_PREFIX))') self.WriteLn('gyp_shared_intermediate_dir := ' '$(call intermediates-dir-for,GYP,shared,,,$(GYP_VAR_PREFIX))') self.WriteLn() # List files this target depends on so that actions/rules/copies/sources # can depend on the list. # TODO: doesn't pull in things through transitive link deps; needed? target_dependencies = [x[1] for x in deps if x[0] == 'path'] self.WriteLn('# Make sure our deps are built first.') self.WriteList(target_dependencies, 'GYP_TARGET_DEPENDENCIES', local_pathify=True) # Actions must come first, since they can generate more OBJs for use below. if 'actions' in spec: self.WriteActions(spec['actions'], extra_sources, extra_outputs) # Rules must be early like actions. if 'rules' in spec: self.WriteRules(spec['rules'], extra_sources, extra_outputs) if 'copies' in spec: self.WriteCopies(spec['copies'], extra_outputs) # GYP generated outputs. self.WriteList(extra_outputs, 'GYP_GENERATED_OUTPUTS', local_pathify=True) # Set LOCAL_ADDITIONAL_DEPENDENCIES so that Android's build rules depend # on both our dependency targets and our generated files. self.WriteLn('# Make sure our deps and generated files are built first.') self.WriteLn('LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) ' '$(GYP_GENERATED_OUTPUTS)') self.WriteLn() # Sources. if spec.get('sources', []) or extra_sources: self.WriteSources(spec, configs, extra_sources) self.WriteTarget(spec, configs, deps, link_deps, part_of_all, write_alias_target) # Update global list of target outputs, used in dependency tracking. target_outputs[qualified_target] = ('path', self.output_binary) # Update global list of link dependencies. if self.type == 'static_library': target_link_deps[qualified_target] = ('static', self.android_module) elif self.type == 'shared_library': target_link_deps[qualified_target] = ('shared', self.android_module) self.fp.close() return self.android_module def WriteActions(self, actions, extra_sources, extra_outputs): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) """ for action in actions: name = make.StringToMakefileVariable('%s_%s' % (self.relative_target, action['action_name'])) self.WriteLn('### Rules for action "%s":' % action['action_name']) inputs = action['inputs'] outputs = action['outputs'] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: if not out.startswith('$'): print ('WARNING: Action for target "%s" writes output to local path ' '"%s".' % (self.target, out)) dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get('process_outputs_as_sources', False)): extra_sources += outputs # Prepare the actual command. command = gyp.common.EncodePOSIXShellList(action['action']) if 'message' in action: quiet_cmd = 'Gyp action: %s ($@)' % action['message'] else: quiet_cmd = 'Gyp action: %s ($@)' % name if len(dirs) > 0: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command cd_action = 'cd $(gyp_local_path)/%s; ' % self.path command = cd_action + command # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the gyp_* # variables for the action rule with an absolute version so that the # output goes in the right place. # Only write the gyp_* rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. main_output = make.QuoteSpaces(self.LocalPathify(outputs[0])) self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output) self.WriteLn('%s: gyp_var_prefix := $(GYP_VAR_PREFIX)' % main_output) self.WriteLn('%s: gyp_intermediate_dir := ' '$(abspath $(gyp_intermediate_dir))' % main_output) self.WriteLn('%s: gyp_shared_intermediate_dir := ' '$(abspath $(gyp_shared_intermediate_dir))' % main_output) # Android's envsetup.sh adds a number of directories to the path including # the built host binary directory. This causes actions/rules invoked by # gyp to sometimes use these instead of system versions, e.g. bison. # The built host binaries may not be suitable, and can cause errors. # So, we remove them from the PATH using the ANDROID_BUILD_PATHS variable # set by envsetup. self.WriteLn('%s: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))' % main_output) # Don't allow spaces in input/output filenames, but make an exception for # filenames which start with '$(' since it's okay for there to be spaces # inside of make function/macro invocations. for input in inputs: if not input.startswith('$(') and ' ' in input: raise gyp.common.GypError( 'Action input filename "%s" in target %s contains a space' % (input, self.target)) for output in outputs: if not output.startswith('$(') and ' ' in output: raise gyp.common.GypError( 'Action output filename "%s" in target %s contains a space' % (output, self.target)) self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' % (main_output, ' '.join(map(self.LocalPathify, inputs)))) self.WriteLn('\t@echo "%s"' % quiet_cmd) self.WriteLn('\t$(hide)%s\n' % command) for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. self.WriteLn('%s: %s ;' % (self.LocalPathify(output), main_output)) extra_outputs += outputs self.WriteLn() self.WriteLn() def WriteRules(self, rules, extra_sources, extra_outputs): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) """ if len(rules) == 0: return for rule in rules: if len(rule.get('rule_sources', [])) == 0: continue name = make.StringToMakefileVariable('%s_%s' % (self.relative_target, rule['rule_name'])) self.WriteLn('\n### Generated for rule "%s":' % name) self.WriteLn('# "%s":' % rule) inputs = rule.get('inputs') for rule_source in rule.get('rule_sources', []): (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = \ os.path.splitext(rule_source_basename) outputs = [self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule['outputs']] dirs = set() for out in outputs: if not out.startswith('$'): print ('WARNING: Rule for target %s writes output to local path %s' % (self.target, out)) dir = os.path.dirname(out) if dir: dirs.add(dir) extra_outputs += outputs if int(rule.get('process_outputs_as_sources', False)): extra_sources.extend(outputs) components = [] for component in rule['action']: component = self.ExpandInputRoot(component, rule_source_root, rule_source_dirname) if '$(RULE_SOURCES)' in component: component = component.replace('$(RULE_SOURCES)', rule_source) components.append(component) command = gyp.common.EncodePOSIXShellList(components) cd_action = 'cd $(gyp_local_path)/%s; ' % self.path command = cd_action + command if dirs: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command # We set up a rule to build the first output, and then set up # a rule for each additional output to depend on the first. outputs = map(self.LocalPathify, outputs) main_output = outputs[0] self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output) self.WriteLn('%s: gyp_var_prefix := $(GYP_VAR_PREFIX)' % main_output) self.WriteLn('%s: gyp_intermediate_dir := ' '$(abspath $(gyp_intermediate_dir))' % main_output) self.WriteLn('%s: gyp_shared_intermediate_dir := ' '$(abspath $(gyp_shared_intermediate_dir))' % main_output) # See explanation in WriteActions. self.WriteLn('%s: export PATH := ' '$(subst $(ANDROID_BUILD_PATHS),,$(PATH))' % main_output) main_output_deps = self.LocalPathify(rule_source) if inputs: main_output_deps += ' ' main_output_deps += ' '.join([self.LocalPathify(f) for f in inputs]) self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' % (main_output, main_output_deps)) self.WriteLn('\t%s\n' % command) for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. self.WriteLn('%s: %s ;' % (output, main_output)) self.WriteLn() self.WriteLn() def WriteCopies(self, copies, extra_outputs): """Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) """ self.WriteLn('### Generated for copy rule.') variable = make.StringToMakefileVariable(self.relative_target + '_copies') outputs = [] for copy in copies: for path in copy['files']: # The Android build system does not allow generation of files into the # source tree. The destination should start with a variable, which will # typically be $(gyp_intermediate_dir) or # $(gyp_shared_intermediate_dir). Note that we can't use an assertion # because some of the gyp tests depend on this. if not copy['destination'].startswith('$'): print ('WARNING: Copy rule for target %s writes output to ' 'local path %s' % (self.target, copy['destination'])) # LocalPathify() calls normpath, stripping trailing slashes. path = Sourceify(self.LocalPathify(path)) filename = os.path.split(path)[1] output = Sourceify(self.LocalPathify(os.path.join(copy['destination'], filename))) self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES) | $(ACP)' % (output, path)) self.WriteLn('\t@echo Copying: $@') self.WriteLn('\t$(hide) mkdir -p $(dir $@)') self.WriteLn('\t$(hide) $(ACP) -rpf $< $@') self.WriteLn() outputs.append(output) self.WriteLn('%s = %s' % (variable, ' '.join(map(make.QuoteSpaces, outputs)))) extra_outputs.append('$(%s)' % variable) self.WriteLn() def WriteSourceFlags(self, spec, configs): """Write out the flags and include paths used to compile source files for the current target. Args: spec, configs: input from gyp. """ for configname, config in sorted(configs.iteritems()): extracted_includes = [] self.WriteLn('\n# Flags passed to both C and C++ files.') cflags, includes_from_cflags = self.ExtractIncludesFromCFlags( config.get('cflags', []) + config.get('cflags_c', [])) extracted_includes.extend(includes_from_cflags) self.WriteList(cflags, 'MY_CFLAGS_%s' % configname) self.WriteList(config.get('defines'), 'MY_DEFS_%s' % configname, prefix='-D', quoter=make.EscapeCppDefine) self.WriteLn('\n# Include paths placed before CFLAGS/CPPFLAGS') includes = list(config.get('include_dirs', [])) includes.extend(extracted_includes) includes = map(Sourceify, map(self.LocalPathify, includes)) includes = self.NormalizeIncludePaths(includes) self.WriteList(includes, 'LOCAL_C_INCLUDES_%s' % configname) self.WriteLn('\n# Flags passed to only C++ (and not C) files.') self.WriteList(config.get('cflags_cc'), 'LOCAL_CPPFLAGS_%s' % configname) self.WriteLn('\nLOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) ' '$(MY_DEFS_$(GYP_CONFIGURATION))') # Undefine ANDROID for host modules # TODO: the source code should not use macro ANDROID to tell if it's host # or target module. if self.toolset == 'host': self.WriteLn('# Undefine ANDROID for host modules') self.WriteLn('LOCAL_CFLAGS += -UANDROID') self.WriteLn('LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) ' '$(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))') self.WriteLn('LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))') # Android uses separate flags for assembly file invocations, but gyp expects # the same CFLAGS to be applied: self.WriteLn('LOCAL_ASFLAGS := $(LOCAL_CFLAGS)') def WriteSources(self, spec, configs, extra_sources): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. We need to handle shared_intermediate directory source files as a special case by copying them to the intermediate directory and treating them as a genereated sources. Otherwise the Android build rules won't pick them up. Args: spec, configs: input from gyp. extra_sources: Sources generated from Actions or Rules. """ sources = filter(make.Compilable, spec.get('sources', [])) generated_not_sources = [x for x in extra_sources if not make.Compilable(x)] extra_sources = filter(make.Compilable, extra_sources) # Determine and output the C++ extension used by these sources. # We simply find the first C++ file and use that extension. all_sources = sources + extra_sources local_cpp_extension = '.cpp' for source in all_sources: (root, ext) = os.path.splitext(source) if IsCPPExtension(ext): local_cpp_extension = ext break if local_cpp_extension != '.cpp': self.WriteLn('LOCAL_CPP_EXTENSION := %s' % local_cpp_extension) # We need to move any non-generated sources that are coming from the # shared intermediate directory out of LOCAL_SRC_FILES and put them # into LOCAL_GENERATED_SOURCES. We also need to move over any C++ files # that don't match our local_cpp_extension, since Android will only # generate Makefile rules for a single LOCAL_CPP_EXTENSION. local_files = [] for source in sources: (root, ext) = os.path.splitext(source) if '$(gyp_shared_intermediate_dir)' in source: extra_sources.append(source) elif '$(gyp_intermediate_dir)' in source: extra_sources.append(source) elif IsCPPExtension(ext) and ext != local_cpp_extension: extra_sources.append(source) else: local_files.append(os.path.normpath(os.path.join(self.path, source))) # For any generated source, if it is coming from the shared intermediate # directory then we add a Make rule to copy them to the local intermediate # directory first. This is because the Android LOCAL_GENERATED_SOURCES # must be in the local module intermediate directory for the compile rules # to work properly. If the file has the wrong C++ extension, then we add # a rule to copy that to intermediates and use the new version. final_generated_sources = [] # If a source file gets copied, we still need to add the orginal source # directory as header search path, for GCC searches headers in the # directory that contains the source file by default. origin_src_dirs = [] for source in extra_sources: local_file = source if not '$(gyp_intermediate_dir)/' in local_file: basename = os.path.basename(local_file) local_file = '$(gyp_intermediate_dir)/' + basename (root, ext) = os.path.splitext(local_file) if IsCPPExtension(ext) and ext != local_cpp_extension: local_file = root + local_cpp_extension if local_file != source: self.WriteLn('%s: %s' % (local_file, self.LocalPathify(source))) self.WriteLn('\tmkdir -p $(@D); cp $< $@') origin_src_dirs.append(os.path.dirname(source)) final_generated_sources.append(local_file) # We add back in all of the non-compilable stuff to make sure that the # make rules have dependencies on them. final_generated_sources.extend(generated_not_sources) self.WriteList(final_generated_sources, 'LOCAL_GENERATED_SOURCES') origin_src_dirs = gyp.common.uniquer(origin_src_dirs) origin_src_dirs = map(Sourceify, map(self.LocalPathify, origin_src_dirs)) self.WriteList(origin_src_dirs, 'GYP_COPIED_SOURCE_ORIGIN_DIRS') self.WriteList(local_files, 'LOCAL_SRC_FILES') # Write out the flags used to compile the source; this must be done last # so that GYP_COPIED_SOURCE_ORIGIN_DIRS can be used as an include path. self.WriteSourceFlags(spec, configs) def ComputeAndroidModule(self, spec): """Return the Android module name used for a gyp spec. We use the complete qualified target name to avoid collisions between duplicate targets in different directories. We also add a suffix to distinguish gyp-generated module names. """ if int(spec.get('android_unmangled_name', 0)): assert self.type != 'shared_library' or self.target.startswith('lib') return self.target if self.type == 'shared_library': # For reasons of convention, the Android build system requires that all # shared library modules are named 'libfoo' when generating -l flags. prefix = 'lib_' else: prefix = '' if spec['toolset'] == 'host': suffix = '_$(TARGET_$(GYP_VAR_PREFIX)ARCH)_host_gyp' else: suffix = '_gyp' if self.path: middle = make.StringToMakefileVariable('%s_%s' % (self.path, self.target)) else: middle = make.StringToMakefileVariable(self.target) return ''.join([prefix, middle, suffix]) def ComputeOutputParts(self, spec): """Return the 'output basename' of a gyp spec, split into filename + ext. Android libraries must be named the same thing as their module name, otherwise the linker can't find them, so product_name and so on must be ignored if we are building a library, and the "lib" prepending is not done for Android. """ assert self.type != 'loadable_module' # TODO: not supported? target = spec['target_name'] target_prefix = '' target_ext = '' if self.type == 'static_library': target = self.ComputeAndroidModule(spec) target_ext = '.a' elif self.type == 'shared_library': target = self.ComputeAndroidModule(spec) target_ext = '.so' elif self.type == 'none': target_ext = '.stamp' elif self.type != 'executable': print ("ERROR: What output file should be generated?", "type", self.type, "target", target) if self.type != 'static_library' and self.type != 'shared_library': target_prefix = spec.get('product_prefix', target_prefix) target = spec.get('product_name', target) product_ext = spec.get('product_extension') if product_ext: target_ext = '.' + product_ext target_stem = target_prefix + target return (target_stem, target_ext) def ComputeOutputBasename(self, spec): """Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so' """ return ''.join(self.ComputeOutputParts(spec)) def ComputeOutput(self, spec): """Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so' """ if self.type == 'executable': # We install host executables into shared_intermediate_dir so they can be # run by gyp rules that refer to PRODUCT_DIR. path = '$(gyp_shared_intermediate_dir)' elif self.type == 'shared_library': if self.toolset == 'host': path = '$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)' else: path = '$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)' else: # Other targets just get built into their intermediate dir. if self.toolset == 'host': path = ('$(call intermediates-dir-for,%s,%s,true,,' '$(GYP_HOST_VAR_PREFIX))' % (self.android_class, self.android_module)) else: path = ('$(call intermediates-dir-for,%s,%s,,,$(GYP_VAR_PREFIX))' % (self.android_class, self.android_module)) assert spec.get('product_dir') is None # TODO: not supported? return os.path.join(path, self.ComputeOutputBasename(spec)) def NormalizeIncludePaths(self, include_paths): """ Normalize include_paths. Convert absolute paths to relative to the Android top directory. Args: include_paths: A list of unprocessed include paths. Returns: A list of normalized include paths. """ normalized = [] for path in include_paths: if path[0] == '/': path = gyp.common.RelativePath(path, self.android_top_dir) normalized.append(path) return normalized def ExtractIncludesFromCFlags(self, cflags): """Extract includes "-I..." out from cflags Args: cflags: A list of compiler flags, which may be mixed with "-I.." Returns: A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed. """ clean_cflags = [] include_paths = [] for flag in cflags: if flag.startswith('-I'): include_paths.append(flag[2:]) else: clean_cflags.append(flag) return (clean_cflags, include_paths) def FilterLibraries(self, libraries): """Filter the 'libraries' key to separate things that shouldn't be ldflags. Library entries that look like filenames should be converted to android module names instead of being passed to the linker as flags. Args: libraries: the value of spec.get('libraries') Returns: A tuple (static_lib_modules, dynamic_lib_modules, ldflags) """ static_lib_modules = [] dynamic_lib_modules = [] ldflags = [] for libs in libraries: # Libs can have multiple words. for lib in libs.split(): # Filter the system libraries, which are added by default by the Android # build system. if (lib == '-lc' or lib == '-lstdc++' or lib == '-lm' or lib.endswith('libgcc.a')): continue match = re.search(r'([^/]+)\.a$', lib) if match: static_lib_modules.append(match.group(1)) continue match = re.search(r'([^/]+)\.so$', lib) if match: dynamic_lib_modules.append(match.group(1)) continue if lib.startswith('-l'): ldflags.append(lib) return (static_lib_modules, dynamic_lib_modules, ldflags) def ComputeDeps(self, spec): """Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps). """ deps = [] link_deps = [] if 'dependencies' in spec: deps.extend([target_outputs[dep] for dep in spec['dependencies'] if target_outputs[dep]]) for dep in spec['dependencies']: if dep in target_link_deps: link_deps.append(target_link_deps[dep]) deps.extend(link_deps) return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps)) def WriteTargetFlags(self, spec, configs, link_deps): """Write Makefile code to specify the link flags and library dependencies. spec, configs: input from gyp. link_deps: link dependency list; see ComputeDeps() """ # Libraries (i.e. -lfoo) # These must be included even for static libraries as some of them provide # implicit include paths through the build system. libraries = gyp.common.uniquer(spec.get('libraries', [])) static_libs, dynamic_libs, ldflags_libs = self.FilterLibraries(libraries) if self.type != 'static_library': for configname, config in sorted(configs.iteritems()): ldflags = list(config.get('ldflags', [])) self.WriteLn('') self.WriteList(ldflags, 'LOCAL_LDFLAGS_%s' % configname) self.WriteList(ldflags_libs, 'LOCAL_GYP_LIBS') self.WriteLn('LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION)) ' '$(LOCAL_GYP_LIBS)') # Link dependencies (i.e. other gyp targets this target depends on) # These need not be included for static libraries as within the gyp build # we do not use the implicit include path mechanism. if self.type != 'static_library': static_link_deps = [x[1] for x in link_deps if x[0] == 'static'] shared_link_deps = [x[1] for x in link_deps if x[0] == 'shared'] else: static_link_deps = [] shared_link_deps = [] # Only write the lists if they are non-empty. if static_libs or static_link_deps: self.WriteLn('') self.WriteList(static_libs + static_link_deps, 'LOCAL_STATIC_LIBRARIES') self.WriteLn('# Enable grouping to fix circular references') self.WriteLn('LOCAL_GROUP_STATIC_LIBRARIES := true') if dynamic_libs or shared_link_deps: self.WriteLn('') self.WriteList(dynamic_libs + shared_link_deps, 'LOCAL_SHARED_LIBRARIES') def WriteTarget(self, spec, configs, deps, link_deps, part_of_all, write_alias_target): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() part_of_all: flag indicating this target is part of 'all' write_alias_target: flag indicating whether to create short aliases for this target """ self.WriteLn('### Rules for final target.') if self.type != 'none': self.WriteTargetFlags(spec, configs, link_deps) settings = spec.get('aosp_build_settings', {}) if settings: self.WriteLn('### Set directly by aosp_build_settings.') for k, v in settings.iteritems(): if isinstance(v, list): self.WriteList(v, k) else: self.WriteLn('%s := %s' % (k, make.QuoteIfNecessary(v))) self.WriteLn('') # Add to the set of targets which represent the gyp 'all' target. We use the # name 'gyp_all_modules' as the Android build system doesn't allow the use # of the Make target 'all' and because 'all_modules' is the equivalent of # the Make target 'all' on Android. if part_of_all and write_alias_target: self.WriteLn('# Add target alias to "gyp_all_modules" target.') self.WriteLn('.PHONY: gyp_all_modules') self.WriteLn('gyp_all_modules: %s' % self.android_module) self.WriteLn('') # Add an alias from the gyp target name to the Android module name. This # simplifies manual builds of the target, and is required by the test # framework. if self.target != self.android_module and write_alias_target: self.WriteLn('# Alias gyp target name.') self.WriteLn('.PHONY: %s' % self.target) self.WriteLn('%s: %s' % (self.target, self.android_module)) self.WriteLn('') # Add the command to trigger build of the target type depending # on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY # NOTE: This has to come last! modifier = '' if self.toolset == 'host': modifier = 'HOST_' if self.type == 'static_library': self.WriteLn('include $(BUILD_%sSTATIC_LIBRARY)' % modifier) elif self.type == 'shared_library': self.WriteLn('LOCAL_PRELINK_MODULE := false') self.WriteLn('include $(BUILD_%sSHARED_LIBRARY)' % modifier) elif self.type == 'executable': # Executables are for build and test purposes only, so they're installed # to a directory that doesn't get included in the system image. self.WriteLn('LOCAL_MODULE_PATH := $(gyp_shared_intermediate_dir)') self.WriteLn('include $(BUILD_%sEXECUTABLE)' % modifier) else: self.WriteLn('LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp') self.WriteLn('LOCAL_UNINSTALLABLE_MODULE := true') if self.toolset == 'target': self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_VAR_PREFIX)') else: self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_HOST_VAR_PREFIX)') self.WriteLn() self.WriteLn('include $(BUILD_SYSTEM)/base_rules.mk') self.WriteLn() self.WriteLn('$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)') self.WriteLn('\t$(hide) echo "Gyp timestamp: $@"') self.WriteLn('\t$(hide) mkdir -p $(dir $@)') self.WriteLn('\t$(hide) touch $@') self.WriteLn() self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX :=') def WriteList(self, value_list, variable=None, prefix='', quoter=make.QuoteIfNecessary, local_pathify=False): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = '' if value_list: value_list = [quoter(prefix + l) for l in value_list] if local_pathify: value_list = [self.LocalPathify(l) for l in value_list] values = ' \\\n\t' + ' \\\n\t'.join(value_list) self.fp.write('%s :=%s\n\n' % (variable, values)) def WriteLn(self, text=''): self.fp.write(text + '\n') def LocalPathify(self, path): """Convert a subdirectory-relative path into a normalized path which starts with the make variable $(LOCAL_PATH) (i.e. the top of the project tree). Absolute paths, or paths that contain variables, are just normalized.""" if '$(' in path or os.path.isabs(path): # path is not a file in the project tree in this case, but calling # normpath is still important for trimming trailing slashes. return os.path.normpath(path) local_path = os.path.join('$(LOCAL_PATH)', self.path, path) local_path = os.path.normpath(local_path) # Check that normalizing the path didn't ../ itself out of $(LOCAL_PATH) # - i.e. that the resulting path is still inside the project tree. The # path may legitimately have ended up containing just $(LOCAL_PATH), though, # so we don't look for a slash. assert local_path.startswith('$(LOCAL_PATH)'), ( 'Path %s attempts to escape from gyp path %s !)' % (path, self.path)) return local_path def ExpandInputRoot(self, template, expansion, dirname): if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template: return template path = template % { 'INPUT_ROOT': expansion, 'INPUT_DIRNAME': dirname, } return os.path.normpath(path) def PerformBuild(data, configurations, params): # The android backend only supports the default configuration. options = params['options'] makefile = os.path.abspath(os.path.join(options.toplevel_dir, 'GypAndroid.mk')) env = dict(os.environ) env['ONE_SHOT_MAKEFILE'] = makefile arguments = ['make', '-C', os.environ['ANDROID_BUILD_TOP'], 'gyp_all_modules'] print 'Building: %s' % arguments subprocess.check_call(arguments, env=env) def GenerateOutput(target_list, target_dicts, data, params): options = params['options'] generator_flags = params.get('generator_flags', {}) builddir_name = generator_flags.get('output_dir', 'out') limit_to_target_all = generator_flags.get('limit_to_target_all', False) write_alias_targets = generator_flags.get('write_alias_targets', True) sdk_version = generator_flags.get('aosp_sdk_version', 19) android_top_dir = os.environ.get('ANDROID_BUILD_TOP') assert android_top_dir, '$ANDROID_BUILD_TOP not set; you need to run lunch.' def CalculateMakefilePath(build_file, base_name): """Determine where to write a Makefile for a given gyp file.""" # Paths in gyp files are relative to the .gyp file, but we want # paths relative to the source root for the master makefile. Grab # the path of the .gyp file as the base to relativize against. # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp". base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.depth) # We write the file in the base_path directory. output_file = os.path.join(options.depth, base_path, base_name) assert not options.generator_output, ( 'The Android backend does not support options.generator_output.') base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.toplevel_dir) return base_path, output_file # TODO: search for the first non-'Default' target. This can go # away when we add verification that all targets have the # necessary configurations. default_configuration = None toolsets = set([target_dicts[target]['toolset'] for target in target_list]) for target in target_list: spec = target_dicts[target] if spec['default_configuration'] != 'Default': default_configuration = spec['default_configuration'] break if not default_configuration: default_configuration = 'Default' srcdir = '.' makefile_name = 'GypAndroid' + options.suffix + '.mk' makefile_path = os.path.join(options.toplevel_dir, makefile_name) assert not options.generator_output, ( 'The Android backend does not support options.generator_output.') gyp.common.EnsureDirExists(makefile_path) root_makefile = open(makefile_path, 'w') root_makefile.write(header) # We set LOCAL_PATH just once, here, to the top of the project tree. This # allows all the other paths we use to be relative to the Android.mk file, # as the Android build system expects. root_makefile.write('\nLOCAL_PATH := $(call my-dir)\n') # Find the list of targets that derive from the gyp file(s) being built. needed_targets = set() for build_file in params['build_files']: for target in gyp.common.AllTargets(target_list, target_dicts, build_file): needed_targets.add(target) build_files = set() include_list = set() android_modules = {} for qualified_target in target_list: build_file, target, toolset = gyp.common.ParseQualifiedTarget( qualified_target) relative_build_file = gyp.common.RelativePath(build_file, options.toplevel_dir) build_files.add(relative_build_file) included_files = data[build_file]['included_files'] for included_file in included_files: # The included_files entries are relative to the dir of the build file # that included them, so we have to undo that and then make them relative # to the root dir. relative_include_file = gyp.common.RelativePath( gyp.common.UnrelativePath(included_file, build_file), options.toplevel_dir) abs_include_file = os.path.abspath(relative_include_file) # If the include file is from the ~/.gyp dir, we should use absolute path # so that relocating the src dir doesn't break the path. if (params['home_dot_gyp'] and abs_include_file.startswith(params['home_dot_gyp'])): build_files.add(abs_include_file) else: build_files.add(relative_include_file) base_path, output_file = CalculateMakefilePath(build_file, target + '.' + toolset + options.suffix + '.mk') spec = target_dicts[qualified_target] configs = spec['configurations'] part_of_all = qualified_target in needed_targets if limit_to_target_all and not part_of_all: continue relative_target = gyp.common.QualifiedTarget(relative_build_file, target, toolset) writer = AndroidMkWriter(android_top_dir) android_module = writer.Write(qualified_target, relative_target, base_path, output_file, spec, configs, part_of_all=part_of_all, write_alias_target=write_alias_targets, sdk_version=sdk_version) if android_module in android_modules: print ('ERROR: Android module names must be unique. The following ' 'targets both generate Android module name %s.\n %s\n %s' % (android_module, android_modules[android_module], qualified_target)) return android_modules[android_module] = qualified_target # Our root_makefile lives at the source root. Compute the relative path # from there to the output_file for including. mkfile_rel_path = gyp.common.RelativePath(output_file, os.path.dirname(makefile_path)) include_list.add(mkfile_rel_path) root_makefile.write('GYP_CONFIGURATION ?= %s\n' % default_configuration) root_makefile.write('GYP_VAR_PREFIX ?=\n') root_makefile.write('GYP_HOST_VAR_PREFIX ?=\n') root_makefile.write('GYP_HOST_MULTILIB ?=\n') # Write out the sorted list of includes. root_makefile.write('\n') for include_file in sorted(include_list): root_makefile.write('include $(LOCAL_PATH)/' + include_file + '\n') root_makefile.write('\n') if write_alias_targets: root_makefile.write(ALL_MODULES_FOOTER) root_makefile.close()
mit
robcarver17/pysystemtrade
sysproduction/reporting/trades_report.py
1
16443
from copy import copy from collections import namedtuple import datetime import numpy as np import pandas as pd from syscore.genutils import transfer_object_attributes from syscore.pdutils import make_df_from_list_of_named_tuple from syscore.objects import header, table, body_text, arg_not_supplied, missing_data from sysdata.data_blob import dataBlob from sysproduction.data.orders import dataOrders from sysproduction.data.instruments import diagInstruments from sysproduction.reporting.risk_report import get_current_annualised_stdev_for_instrument def trades_info( data=arg_not_supplied, calendar_days_back=1, end_date=arg_not_supplied, start_date=arg_not_supplied, ): """ Report on system status :param: data blob :return: list of formatted output items """ if data is arg_not_supplied: data = dataBlob() if end_date is arg_not_supplied: end_date = datetime.datetime.now() if start_date is arg_not_supplied: start_date = end_date - datetime.timedelta(days=calendar_days_back) results_object = get_trades_report_data( data, start_date=start_date, end_date=end_date ) formatted_output = format_trades_data(results_object) return formatted_output def get_trades_report_data(data, start_date, end_date): broker_orders = get_recent_broker_orders(data, start_date, end_date) if len(broker_orders) == 0: empty_df = pd.DataFrame() results_object = dict(overview=empty_df) return results_object overview = broker_orders[ [ "instrument_code", "strategy_name", "contract_date", "fill_datetime", "fill", "filled_price", ] ] delays = create_delay_df(broker_orders) raw_slippage = create_raw_slippage_df(broker_orders) vol_slippage = create_vol_norm_slippage_df(raw_slippage, data) cash_slippage = create_cash_slippage_df(raw_slippage, data) summary_dict = {} item_list = [ "delay", "bid_ask", "execution", "versus_limit", "versus_parent_limit", "total_trading", ] detailed_raw_results = get_stats_for_slippage_groups( raw_slippage, item_list) summary_dict.update(detailed_raw_results) item_list = [ "delay_vol", "bid_ask_vol", "execution_vol", "versus_limit_vol", "versus_parent_limit_vol", "total_trading_vol", ] detailed_vol_results = get_stats_for_slippage_groups( vol_slippage, item_list) summary_dict.update(detailed_vol_results) item_list = [ "delay_cash", "bid_ask_cash", "execution_cash", "versus_limit_cash", "versus_parent_limit_cash", "total_trading_cash", ] detailed_cash_results = get_stats_for_slippage_groups( cash_slippage, item_list) summary_dict.update(detailed_cash_results) results_object = dict( overview=overview, delays=delays, raw_slippage=raw_slippage, vol_slippage=vol_slippage, cash_slippage=cash_slippage, summary_dict=summary_dict, ) return results_object def format_trades_data(results_object): """ Put the results into a printable format :param results_dict: dict, keys are different segments :return: """ formatted_output = [] formatted_output.append( header("Trades report produced on %s" % (str(datetime.datetime.now()))) ) if len(results_object["overview"]) == 0: formatted_output.append(body_text("No trades in relevant period")) return formatted_output table1_df = results_object["overview"] table1 = table("Broker orders", table1_df) formatted_output.append(table1) table2_df = results_object["delays"] table2 = table("Delays", table2_df) formatted_output.append(table2) table3_df = results_object["raw_slippage"] table3 = table("Slippage (ticks per lot)", table3_df) formatted_output.append(table3) table4_df = results_object["vol_slippage"] table4 = table( "Slippage (normalised by annual vol, BP of annual SR)", table4_df) formatted_output.append(table4) table5_df = results_object["cash_slippage"] table5 = table("Slippage (In base currency)", table5_df) formatted_output.append(table5) summary_results_dict = results_object["summary_dict"] for summary_table_name, summary_table_item in summary_results_dict.items(): summary_table = table( "Summary %s" % summary_table_name, summary_table_item) formatted_output.append(summary_table) return formatted_output tradesData = namedtuple( "tradesData", [ "order_id", "instrument_code", "strategy_name", "contract_date", "fill", "filled_price", "mid_price", "side_price", "offside_price", "parent_reference_price", # from contract order "parent_reference_datetime", # from instrument order "submit_datetime", "fill_datetime", "limit_price", "trade", "buy_or_sell", "parent_limit_price", "commission", ], ) data = dataBlob() def get_recent_broker_orders(data, start_date, end_date): data_orders = dataOrders(data) order_id_list = data_orders.get_historic_broker_order_ids_in_date_range( start_date, end_date ) orders_as_list = [get_tuple_object_from_order_id( data, order_id) for order_id in order_id_list] pdf = make_df_from_list_of_named_tuple(tradesData, orders_as_list) return pdf def get_tuple_object_from_order_id(data, order_id): data_orders = dataOrders(data) order = data_orders.get_historic_broker_order_from_order_id_with_execution_data( order_id) tuple_object = transfer_object_attributes(tradesData, order) return tuple_object def create_delay_df(broker_orders): delay_data_as_list = [ delay_row( broker_orders.iloc[irow]) for irow in range( len(broker_orders))] delay_data_df = pd.concat(delay_data_as_list, axis=1) delay_data_df = delay_data_df.transpose() delay_data_df.index = broker_orders.index return delay_data_df def delay_row(order_row): submit_minus_generated, filled_minus_submit = delay_calculations_for_order_row( order_row) new_order_row = copy(order_row) new_order_row = new_order_row[ [ "instrument_code", "strategy_name", "parent_reference_datetime", "submit_datetime", "fill_datetime", ] ] new_order_row = new_order_row.append( pd.Series( [submit_minus_generated, filled_minus_submit], index=["submit_minus_generated", "filled_minus_submit"], ) ) return new_order_row def delay_calculations_for_order_row(order_row): submit_minus_generated = delay_calc( order_row.parent_reference_datetime, order_row.submit_datetime ) filled_minus_submit = delay_calc( order_row.submit_datetime, order_row.fill_datetime) return submit_minus_generated, filled_minus_submit def delay_calc(first_time, second_time): if first_time is None or second_time is None: return np.nan time_diff = second_time - first_time time_diff_seconds = time_diff.total_seconds() if time_diff_seconds < 0: return np.nan return time_diff_seconds def create_raw_slippage_df(broker_orders): raw_slippage_data_as_list = [ raw_slippage_row( broker_orders.iloc[irow]) for irow in range( len(broker_orders))] raw_slippage_df = pd.concat(raw_slippage_data_as_list, axis=1) raw_slippage_df = raw_slippage_df.transpose() raw_slippage_df.index = broker_orders.index return raw_slippage_df def raw_slippage_row(order_row): ( delay, bid_ask, execution, versus_limit, versus_parent_limit, total_trading, ) = price_calculations_for_order_row(order_row) new_order_row = copy(order_row) new_order_row = new_order_row[ [ "instrument_code", "strategy_name", "trade", "parent_reference_price", "parent_limit_price", "mid_price", "side_price", "offside_price", "limit_price", "filled_price", ] ] new_order_row = new_order_row.append( pd.Series( [ delay, bid_ask, execution, versus_limit, versus_parent_limit, total_trading, ], index=[ "delay", "bid_ask", "execution", "versus_limit", "versus_parent_limit", "total_trading", ], ) ) return new_order_row def price_calculations_for_order_row(order_row): buying_multiplier = order_row.buy_or_sell # Following are always floats: parent_reference_price, limit_price, # calculated_mid_price, calculated_side_price, fill_price delay = price_slippage( buying_multiplier, order_row.parent_reference_price, order_row.mid_price, ) bid_ask = price_slippage( buying_multiplier, order_row.mid_price, order_row.side_price, ) execution = price_slippage( buying_multiplier, order_row.side_price, order_row.filled_price, ) total_trading = bid_ask + execution versus_limit = price_slippage( buying_multiplier, order_row.limit_price, order_row.filled_price) versus_parent_limit = price_slippage( buying_multiplier, order_row.parent_limit_price, order_row.filled_price, ) return delay, bid_ask, execution, versus_limit, versus_parent_limit, total_trading def price_slippage(buying_multiplier, first_price, second_price): # Slippage is always negative (bad) positive (good) # This will return a negative number if second price is adverse versus # first price if first_price is None or second_price is None: return np.nan # 1 if buying, -1 if selling # if buying, want second price to be lower than first # if selling, want second price to be higher than first slippage = buying_multiplier * (first_price - second_price) return slippage def create_cash_slippage_df(raw_slippage, data): # What does this slippage mean in money terms cash_slippage_data_as_list = [ cash_slippage_row(raw_slippage.iloc[irow], data) for irow in range(len(raw_slippage)) ] cash_slippage_df = pd.concat(cash_slippage_data_as_list, axis=1) cash_slippage_df = cash_slippage_df.transpose() cash_slippage_df.index = raw_slippage.index return cash_slippage_df def cash_slippage_row(slippage_row, data): # rewrite ( delay_cash, bid_ask_cash, execution_cash, versus_limit_cash, versus_parent_limit_cash, total_trading_cash, value_of_price_point, ) = cash_calculations_for_slippage_row(slippage_row, data) new_slippage_row = copy(slippage_row) new_slippage_row = new_slippage_row[ [ "instrument_code", "strategy_name", "trade", ] ] new_slippage_row = new_slippage_row.append( pd.Series( [ value_of_price_point, delay_cash, bid_ask_cash, execution_cash, versus_limit_cash, versus_parent_limit_cash, total_trading_cash, ], index=[ "value_of_price_point", "delay_cash", "bid_ask_cash", "execution_cash", "versus_limit_cash", "versus_parent_limit_cash", "total_trading_cash", ], ) ) return new_slippage_row def cash_calculations_for_slippage_row(slippage_row, data): # What's a tick worth in base currency? diag_instruments = diagInstruments(data) value_of_price_point = diag_instruments.get_point_size_base_currency( slippage_row.instrument_code ) input_items = [ "delay", "bid_ask", "execution", "versus_limit", "versus_parent_limit", "total_trading", ] output = [value_of_price_point * slippage_row[input_name] for input_name in input_items] return tuple(output + [value_of_price_point]) def create_vol_norm_slippage_df(raw_slippage, data): # What does this slippage mean in vol normalised terms for irow in range(len(raw_slippage)): vol_slippage_row(raw_slippage.iloc[irow], data) vol_slippage_data_as_list = [ vol_slippage_row(raw_slippage.iloc[irow], data) for irow in range(len(raw_slippage)) ] vol_slippage_df = pd.concat(vol_slippage_data_as_list, axis=1) vol_slippage_df = vol_slippage_df.transpose() vol_slippage_df.index = raw_slippage.index return vol_slippage_df def vol_slippage_row(slippage_row, data): # rewrite ( vol_delay, vol_bid_ask, vol_execution, vol_versus_limit, vol_versus_parent_limit, total_trading_vol, last_annual_vol, ) = vol_calculations_for_slippage_row(slippage_row, data) new_slippage_row = copy(slippage_row) new_slippage_row = new_slippage_row[ [ "instrument_code", "strategy_name", "trade", ] ] new_slippage_row = new_slippage_row.append( pd.Series( [ last_annual_vol, vol_delay, vol_bid_ask, vol_execution, vol_versus_limit, vol_versus_parent_limit, total_trading_vol, ], index=[ "last_annual_vol", "delay_vol", "bid_ask_vol", "execution_vol", "versus_limit_vol", "versus_parent_limit_vol", "total_trading_vol", ], ) ) return new_slippage_row def vol_calculations_for_slippage_row(slippage_row, data): last_annual_vol = get_last_annual_vol_for_slippage_row(slippage_row, data) input_items = [ "delay", "bid_ask", "execution", "versus_limit", "versus_parent_limit", "total_trading", ] output = [10000 * slippage_row[input_name] / last_annual_vol for input_name in input_items] return tuple(output + [last_annual_vol]) def get_last_annual_vol_for_slippage_row(slippage_row, data): instrument_code = slippage_row.instrument_code last_annual_vol = get_current_annualised_stdev_for_instrument(data, instrument_code) return last_annual_vol def get_stats_for_slippage_groups(df_to_process, item_list): results = {} for item_name in item_list: sum_data = df_to_process.groupby( ["strategy_name", "instrument_code"]).agg({item_name: "sum"}) count_data = df_to_process.groupby( ["strategy_name", "instrument_code"]).agg({item_name: "count"}) avg_data = sum_data / count_data try: std = df_to_process.groupby( ["strategy_name", "instrument_code"]).agg({item_name: "std"}) except pd.core.base.DataError: # not enough items to calculate standard deviation std = np.nan lower_range = avg_data + (-2 * std) upper_range = avg_data + (2 * std) results[item_name + " Sum"] = sum_data results[item_name + " Count"] = count_data results[item_name + " Mean"] = avg_data results[item_name + " Lower range"] = lower_range results[item_name + " Upper range"] = upper_range total_sum_data = df_to_process.groupby(["strategy_name"]).agg( {item_name: "sum"} ) results[item_name + " Total Sum"] = total_sum_data return results
gpl-3.0
luispedro/milk
milk/supervised/weighted_voting_adaboost.py
2
2972
from math import exp, log from operator import itemgetter ''' AdaBoost implementation with weighted voting as a decision procedure ''' class weighted_voting_adaboost(object): # initializes with already built classifiers and corresponding def __init__(self, in_classifiers, in_coefficients): self.classifiers = in_classifiers self.coefficients = in_coefficients # decision by weighted voting def apply(self, in_features): # a "class number" => "votes value" mapping answers = {} for classifier, coefficient in zip(self.classifiers, self.coefficients): answer = classifier.apply(in_features) if answer in answers: answers[answer] += coefficient else: answers[answer] = coefficient # dict maximum by value result = max(iter(answers.items()), key=itemgetter(1)) return result[0] class weighted_voting_ada_learner(object): def __init__(self, in_composition_size, in_learner): self.learner = in_learner self.composition_size = in_composition_size def reset(self, in_features): self.classifiers = [] # linear coefficients for the classifiers in composition self.coefficients = [] self.weights = [1. / float(len(in_features))] * len(in_features) def train(self, in_features, in_labels): self.reset(in_features) for iteration in range(self.composition_size): self.classifiers.append(self.learner.train(in_features, in_labels, weights=self.weights)) # new classifier initially gets weight 1 self.coefficients.append(1) answers = [] for obj in in_features: answers.append(self.classifiers[-1].apply(obj)) err = self.compute_weighted_error(in_labels, answers) if abs(err) < 1e-6: return weighted_voting_adaboost(self.classifiers, self.coefficients) alpha = 0.5 * log((1.0 - err) / err) # updating the coefficient of the last added classifier self.coefficients[-1] = alpha self.update_weights(in_labels, answers, alpha) self.normalize_weights() return weighted_voting_adaboost(self.classifiers, self.coefficients) def compute_weighted_error(self, in_labels, in_answers): error = 0. w_sum = sum(self.weights) for ind in range(len(in_labels)): error += (in_answers[ind] != in_labels[ind]) * self.weights[ind] / w_sum return error def update_weights(self, in_labels, in_answers, in_alpha): for ind in range(len(in_labels)): self.weights[ind] *= exp(in_alpha * (in_answers[ind] != in_labels[ind])) def normalize_weights(self): w_sum = sum(self.weights) for ind in range(len(self.weights)): self.weights[ind] /= w_sum
mit
mydongistiny/external_chromium_org
chrome/common/extensions/docs/server2/document_parser_test.py
121
8495
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from document_parser import ParseDocument, RemoveTitle _WHOLE_DOCUMENT = ''' Preamble before heading. <h1 id='main' class='header'>Main header</h1> Some intro to the content. <h2 id='banana' class='header' title=''>Bananas</h2> Something about bananas. <h2 id='orange' title='hello'>Oranges</h2> Something about oranges. <h3 id='valencia'>Valencia Oranges</h3> A description of valencia oranges. <h3 id='seville'>Seville Oranges</h3> A description of seville oranges. <h2>Grapefruit</h3> Grapefruit closed a h2 with a h3. This should be a warning. <h1 id='not-main'>Not the main header</h1> But it should still show up in the TOC as though it were an h2. <h2>Not <h3>a banana</h2> The embedded h3 should be ignored. <h4>It's a h4</h4> h4 are part of the document structure, but this is not inside a h3. <h3>Plantains</h3> Now I'm just getting lazy. <h4>Another h4</h4> This h4 is inside a h3 so will show up. <h5>Header 5</h5> Header 5s are not parsed. ''' _WHOLE_DOCUMENT_WITHOUT_TITLE = ''' Preamble before heading. Some intro to the content. <h2 id='banana' class='header' title=''>Bananas</h2> Something about bananas. <h2 id='orange' title='hello'>Oranges</h2> Something about oranges. <h3 id='valencia'>Valencia Oranges</h3> A description of valencia oranges. <h3 id='seville'>Seville Oranges</h3> A description of seville oranges. <h2>Grapefruit</h3> Grapefruit closed a h2 with a h3. This should be a warning. <h1 id='not-main'>Not the main header</h1> But it should still show up in the TOC as though it were an h2. <h2>Not <h3>a banana</h2> The embedded h3 should be ignored. <h4>It's a h4</h4> h4 are part of the document structure, but this is not inside a h3. <h3>Plantains</h3> Now I'm just getting lazy. <h4>Another h4</h4> This h4 is inside a h3 so will show up. <h5>Header 5</h5> Header 5s are not parsed. ''' class DocumentParserUnittest(unittest.TestCase): def testEmptyDocument(self): self.assertEqual(('', 'No opening <h1> was found'), RemoveTitle('')) result = ParseDocument('') self.assertEqual(None, result.title) self.assertEqual(None, result.title_attributes) self.assertEqual([], result.sections) self.assertEqual([], result.warnings) result = ParseDocument('', expect_title=True) self.assertEqual('', result.title) self.assertEqual({}, result.title_attributes) self.assertEqual([], result.sections) self.assertEqual(['Expected a title'], result.warnings) def testRemoveTitle(self): no_closing_tag = '<h1>No closing tag' self.assertEqual((no_closing_tag, 'No closing </h1> was found'), RemoveTitle(no_closing_tag)) no_opening_tag = 'No opening tag</h1>' self.assertEqual((no_opening_tag, 'No opening <h1> was found'), RemoveTitle(no_opening_tag)) tags_wrong_order = '</h1>Tags in wrong order<h1>' self.assertEqual((tags_wrong_order, 'The </h1> appeared before the <h1>'), RemoveTitle(tags_wrong_order)) multiple_titles = '<h1>First header</h1> and <h1>Second header</h1>' self.assertEqual((' and <h1>Second header</h1>', None), RemoveTitle(multiple_titles)) upper_case = '<H1>Upper case header tag</H1> hi' self.assertEqual((' hi', None), RemoveTitle(upper_case)) mixed_case = '<H1>Mixed case header tag</h1> hi' self.assertEqual((' hi', None), RemoveTitle(mixed_case)) def testOnlyTitleDocument(self): document = '<h1 id="header">heading</h1>' self.assertEqual(('', None), RemoveTitle(document)) result = ParseDocument(document) self.assertEqual(None, result.title) self.assertEqual(None, result.title_attributes) self.assertEqual([], result.sections) self.assertEqual(['Found unexpected title "heading"'], result.warnings) result = ParseDocument(document, expect_title=True) self.assertEqual('heading', result.title) self.assertEqual({'id': 'header'}, result.title_attributes) self.assertEqual([], result.sections) self.assertEqual([], result.warnings) def testWholeDocument(self): self.assertEqual((_WHOLE_DOCUMENT_WITHOUT_TITLE, None), RemoveTitle(_WHOLE_DOCUMENT)) result = ParseDocument(_WHOLE_DOCUMENT, expect_title=True) self.assertEqual('Main header', result.title) self.assertEqual({'id': 'main', 'class': 'header'}, result.title_attributes) self.assertEqual([ 'Found closing </h3> while processing a <h2> (line 19, column 15)', 'Found multiple <h1> tags. Subsequent <h1> tags will be classified as ' '<h2> for the purpose of the structure (line 22, column 1)', 'Found <h3> in the middle of processing a <h2> (line 25, column 9)', # TODO(kalman): Re-enable this warning once the reference pages have # their references fixed. #'Found <h4> without any preceding <h3> (line 28, column 1)', ], result.warnings) # The non-trivial table of contents assertions... self.assertEqual(1, len(result.sections)) entries = result.sections[0].structure self.assertEqual(4, len(entries), entries) entry0, entry1, entry2, entry3 = entries self.assertEqual('hello', entry0.name) self.assertEqual({'id': 'orange'}, entry0.attributes) self.assertEqual(2, len(entry0.entries)) entry0_0, entry0_1 = entry0.entries self.assertEqual('Valencia Oranges', entry0_0.name) self.assertEqual({'id': 'valencia'}, entry0_0.attributes) self.assertEqual([], entry0_0.entries) self.assertEqual('Seville Oranges', entry0_1.name) self.assertEqual({'id': 'seville'}, entry0_1.attributes) self.assertEqual([], entry0_1.entries) self.assertEqual('Grapefruit', entry1.name) self.assertEqual({}, entry1.attributes) self.assertEqual([], entry1.entries) self.assertEqual('Not the main header', entry2.name) self.assertEqual({'id': 'not-main'}, entry2.attributes) self.assertEqual([], entry2.entries) self.assertEqual('Not a banana', entry3.name) self.assertEqual({}, entry3.attributes) self.assertEqual(2, len(entry3.entries)) entry3_1, entry3_2 = entry3.entries self.assertEqual('It\'s a h4', entry3_1.name) self.assertEqual({}, entry3_1.attributes) self.assertEqual([], entry3_1.entries) self.assertEqual('Plantains', entry3_2.name) self.assertEqual({}, entry3_2.attributes) self.assertEqual(1, len(entry3_2.entries)) entry3_2_1, = entry3_2.entries self.assertEqual('Another h4', entry3_2_1.name) self.assertEqual({}, entry3_2_1.attributes) self.assertEqual([], entry3_2_1.entries) def testSingleExplicitSection(self): def test(document): result = ParseDocument(document, expect_title=True) self.assertEqual([], result.warnings) self.assertEqual('Header', result.title) self.assertEqual(1, len(result.sections)) section0, = result.sections entry0, = section0.structure self.assertEqual('An inner header', entry0.name) # A single section, one with the title inside the section, the other out. test('<h1>Header</h1>' '<section>' 'Just a single section here.' '<h2>An inner header</h2>' '</section>') test('<section>' 'Another single section here.' '<h1>Header</h1>' '<h2>An inner header</h2>' '</section>') def testMultipleSections(self): result = ParseDocument( '<h1>Header</h1>' '<h2>First header</h2>' 'This content outside a section is the first section.' '<section>' 'Second section' '<h2>Second header</h2>' '</section>' '<section>' 'Third section' '<h2>Third header</h2>' '</section>', expect_title=True) self.assertEqual([], result.warnings) self.assertEqual('Header', result.title) self.assertEqual(3, len(result.sections)) section0, section1, section2 = result.sections def assert_single_header(section, name): self.assertEqual(1, len(section.structure)) self.assertEqual(name, section.structure[0].name) assert_single_header(section0, 'First header') assert_single_header(section1, 'Second header') assert_single_header(section2, 'Third header') if __name__ == '__main__': unittest.main()
bsd-3-clause
TrainMAnB/vcoincore
qa/rpc-tests/rawtransactions.py
46
5925
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test re-org scenarios with a mempool that contains transactions # that spend (directly or indirectly) coinbase transactions. # from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from pprint import pprint from time import sleep # Create one-input, one-output, no-fee transaction: class RawTransactionsTest(BitcoinTestFramework): def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 3) def setup_network(self, split=False): self.nodes = start_nodes(3, self.options.tmpdir) #connect to a local machine for debugging #url = "http://bitcoinrpc:DP6DvqZtqXarpeNWyN3LZTFchCCyCUuHwNF7E8pX99x1@%s:%d" % ('127.0.0.1', 18332) #proxy = AuthServiceProxy(url) #proxy.url = url # store URL on proxy for info #self.nodes.append(proxy) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) self.is_network_split=False self.sync_all() def run_test(self): #prepare some coins for multiple *rawtransaction commands self.nodes[2].generate(1) self.nodes[0].generate(101) self.sync_all() self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),1.5); self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),1.0); self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),5.0); self.sync_all() self.nodes[0].generate(5) self.sync_all() ######################################### # sendrawtransaction with missing input # ######################################### inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1}] #won't exists outputs = { self.nodes[0].getnewaddress() : 4.998 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) rawtx = self.nodes[2].signrawtransaction(rawtx) errorString = "" try: rawtx = self.nodes[2].sendrawtransaction(rawtx['hex']) except JSONRPCException,e: errorString = e.error['message'] assert_equal("Missing inputs" in errorString, True); ######################### # RAW TX MULTISIG TESTS # ######################### # 2of2 test addr1 = self.nodes[2].getnewaddress() addr2 = self.nodes[2].getnewaddress() addr1Obj = self.nodes[2].validateaddress(addr1) addr2Obj = self.nodes[2].validateaddress(addr2) mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) mSigObjValid = self.nodes[2].validateaddress(mSigObj) #use balance deltas instead of absolute values bal = self.nodes[2].getbalance() # send 1.2 BTC to msig adr txId = self.nodes[0].sendtoaddress(mSigObj, 1.2); self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(self.nodes[2].getbalance(), bal+Decimal('1.20000000')) #node2 has both keys of the 2of2 ms addr., tx should affect the balance # 2of3 test from different nodes bal = self.nodes[2].getbalance() addr1 = self.nodes[1].getnewaddress() addr2 = self.nodes[2].getnewaddress() addr3 = self.nodes[2].getnewaddress() addr1Obj = self.nodes[1].validateaddress(addr1) addr2Obj = self.nodes[2].validateaddress(addr2) addr3Obj = self.nodes[2].validateaddress(addr3) mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']]) mSigObjValid = self.nodes[2].validateaddress(mSigObj) txId = self.nodes[0].sendtoaddress(mSigObj, 2.2); decTx = self.nodes[0].gettransaction(txId) rawTx = self.nodes[0].decoderawtransaction(decTx['hex']) sPK = rawTx['vout'][0]['scriptPubKey']['hex'] self.sync_all() self.nodes[0].generate(1) self.sync_all() #THIS IS A INCOMPLETE FEATURE #NODE2 HAS TWO OF THREE KEY AND THE FUNDS SHOULD BE SPENDABLE AND COUNT AT BALANCE CALCULATION assert_equal(self.nodes[2].getbalance(), bal) #for now, assume the funds of a 2of3 multisig tx are not marked as spendable txDetails = self.nodes[0].gettransaction(txId, True) rawTx = self.nodes[0].decoderawtransaction(txDetails['hex']) vout = False for outpoint in rawTx['vout']: if outpoint['value'] == Decimal('2.20000000'): vout = outpoint break; bal = self.nodes[0].getbalance() inputs = [{ "txid" : txId, "vout" : vout['n'], "scriptPubKey" : vout['scriptPubKey']['hex']}] outputs = { self.nodes[0].getnewaddress() : 2.19 } rawTx = self.nodes[2].createrawtransaction(inputs, outputs) rawTxPartialSigned = self.nodes[1].signrawtransaction(rawTx, inputs) assert_equal(rawTxPartialSigned['complete'], False) #node1 only has one key, can't comp. sign the tx rawTxSigned = self.nodes[2].signrawtransaction(rawTx, inputs) assert_equal(rawTxSigned['complete'], True) #node2 can sign the tx compl., own two of three keys self.nodes[2].sendrawtransaction(rawTxSigned['hex']) rawTx = self.nodes[0].decoderawtransaction(rawTxSigned['hex']) self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(self.nodes[0].getbalance(), bal+Decimal('50.00000000')+Decimal('2.19000000')) #block reward + tx if __name__ == '__main__': RawTransactionsTest().main()
mit
agry/NGECore2
scripts/mobiles/corellia/mutated_krevol_clicker.py
2
1517
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobileTemplate.setCreatureName('mutated_krevol_clicker') mobileTemplate.setLevel(8) mobileTemplate.setDifficulty(Difficulty.NORMAL) mobileTemplate.setMinSpawnDistance(4) mobileTemplate.setMaxSpawnDistance(8) mobileTemplate.setDeathblow(False) mobileTemplate.setScale(1) mobileTemplate.setMeatType("Insect Meat") mobileTemplate.setMeatAmount(10) mobileTemplate.setSocialGroup("horned krevol") mobileTemplate.setAssistRange(2) mobileTemplate.setStalker(False) mobileTemplate.setOptionsBitmask(Options.ATTACKABLE) templates = Vector() templates.add('object/mobile/shared_mutated_krevol_clicker.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() attacks.add('bm_bite_2') attacks.add('bm_bolster_armor_2') attacks.add('bm_enfeeble_2') mobileTemplate.setDefaultAttack('creatureMeleeAttack') mobileTemplate.setAttacks(attacks) core.spawnService.addMobileTemplate('mutated_krevol_clicker', mobileTemplate) return
lgpl-3.0
kantai/passe-framework-prototype
django/http/utils.py
87
3306
""" Functions that modify an HTTP request or response in some way. """ # This group of functions are run as part of the response handling, after # everything else, including all response middleware. Think of them as # "compulsory response middleware". Be careful about what goes here, because # it's a little fiddly to override this behavior, so they should be truly # universally applicable. def fix_location_header(request, response): """ Ensures that we always use an absolute URI in any location header in the response. This is required by RFC 2616, section 14.30. Code constructing response objects is free to insert relative paths, as this function converts them to absolute paths. """ if 'Location' in response and request.get_host(): response['Location'] = request.build_absolute_uri(response['Location']) return response def conditional_content_removal(request, response): """ Removes the content of responses for HEAD requests, 1xx, 204 and 304 responses. Ensures compliance with RFC 2616, section 4.3. """ if 100 <= response.status_code < 200 or response.status_code in (204, 304): response.content = '' response['Content-Length'] = 0 if request.method == 'HEAD': response.content = '' return response def fix_IE_for_attach(request, response): """ This function will prevent Django from serving a Content-Disposition header while expecting the browser to cache it (only when the browser is IE). This leads to IE not allowing the client to download. """ useragent = request.META.get('HTTP_USER_AGENT', '').upper() if 'MSIE' not in useragent and 'CHROMEFRAME' not in useragent: return response offending_headers = ('no-cache', 'no-store') if response.has_header('Content-Disposition'): try: del response['Pragma'] except KeyError: pass if response.has_header('Cache-Control'): cache_control_values = [value.strip() for value in response['Cache-Control'].split(',') if value.strip().lower() not in offending_headers] if not len(cache_control_values): del response['Cache-Control'] else: response['Cache-Control'] = ', '.join(cache_control_values) return response def fix_IE_for_vary(request, response): """ This function will fix the bug reported at http://support.microsoft.com/kb/824847/en-us?spid=8722&sid=global by clearing the Vary header whenever the mime-type is not safe enough for Internet Explorer to handle. Poor thing. """ useragent = request.META.get('HTTP_USER_AGENT', '').upper() if 'MSIE' not in useragent and 'CHROMEFRAME' not in useragent: return response # These mime-types that are decreed "Vary-safe" for IE: safe_mime_types = ('text/html', 'text/plain', 'text/sgml') # The first part of the Content-Type field will be the MIME type, # everything after ';', such as character-set, can be ignored. mime_type = response.get('Content-Type', '').partition(';')[0] if mime_type not in safe_mime_types: try: del response['Vary'] except KeyError: pass return response
bsd-3-clause
GeyerA/android_external_chromium_org
chrome/test/functional/chromoting/me2me_connect.py
68
3054
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Chromoting me2me connect/disconnect related test cases.""" import chromoting_base import pyauto class Me2MeConnect(chromoting_base.ChromotingBase): """Drives me2me connect test cases.""" def setUp(self): """Set up for me2me connect test.""" # Disable test on vista and xp until the failure is figured if self.IsWinVista() or self.IsWinXP(): return pyauto.PyUITest.setUp(self) self.InstallHostDaemon() webapp = self.InstallExtension(self.GetWebappPath()) self.host.LaunchApp(webapp) self.host.Authenticate() self.host.StartMe2Me() self.host.CleanupHostList() self.host.EnableConnectionsInstalled() self.client.LaunchApp(webapp) def tearDown(self): """Mainly uninstalls the host daemon.""" # Disable test on vista and xp until the failure is figured if self.IsWinVista() or self.IsWinXP(): return self.host.DisableConnections() self.UninstallHostDaemon() pyauto.PyUITest.tearDown(self) def testMe2MeConnectDisconnectReconnectDisconnect(self): """Connects, disconnects, reconnects and disconnects""" # Disable test on vista and xp until the failure is figured if self.IsWinVista() or self.IsWinXP(): return self.client.ConnectMe2Me('111111', 'IN_SESSION', self.client_tab_index) self.client.DisconnectMe2Me(False, self.client_tab_index) self.client.ReconnectMe2Me('111111', self.client_tab_index) self.client.DisconnectMe2Me(True, self.client_tab_index) def testMe2MeConnectWithWrongPin(self): """Connects and disconnects.""" # Disable test on vista and xp until the failure is figured if self.IsWinVista() or self.IsWinXP(): return self.client.ConnectMe2Me('222222', 'CLIENT_CONNECT_FAILED_ME2ME', self.client_tab_index) self.client.ReconnectMe2Me('111111', self.client_tab_index) self.client.DisconnectMe2Me(True, self.client_tab_index) def testMe2MeChangePin(self): """Changes pin, connects with new pin and then disconnects.""" # Disable test on vista and xp until the failure is figured if self.IsWinVista() or self.IsWinXP(): return self.host.ChangePin('222222') self.client.ConnectMe2Me('222222', 'IN_SESSION', self.client_tab_index) self.client.DisconnectMe2Me(True, self.client_tab_index) def testMe2MeChangeName(self): """Changes host name, connects and then disconnects.""" # Disable test on vista and xp until the failure is figured if self.IsWinVista() or self.IsWinXP(): return self.client.ChangeName("Changed") self.client.ConnectMe2Me('111111', 'IN_SESSION', self.client_tab_index) self.client.DisconnectMe2Me(True, self.client_tab_index) if __name__ == '__main__': chromoting_base.Main()
bsd-3-clause
hkmogul/mingus
mingus/midi/win32midisequencer.py
10
2392
# mingus - Music theory Python package, win32midisequencer module. # Copyright (C) 2008-2010, Bart Spaans, Ben Fisher # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """MIDI playback support for mingus in MS Windows. This module will use the default MIDI output device, which can be chosen in the control panel. No extra dlls or modules are needed; uses built-in ctypes module. Caution: this will throw Win32MidiException if there is no device, or device can't be opened. """ import sys # We should be able to import this module on non-win32 systems without # raising exceptions. So instead, raise in the init() method. if sys.platform=='win32': import win32midi from win32midi import Win32MidiException from datetime import datetime from mingus.midi.sequencer import Sequencer from mingus.containers.instrument import MidiInstrument class Win32MidiSequencer(Sequencer): output = None midplayer = None def init(self): if sys.platform != 'win32': raise RuntimeError('Intended for use on win32 platform') self.midplayer = win32midi.Win32MidiPlayer() self.midplayer.openDevice() def __del__(self): self.midplayer.closeDevice() # Implement Sequencer's interface def play_event(self, note, channel, velocity): self.midplayer.rawNoteOn(note, channel, velocity) def stop_event(self, note, channel): self.midplayer.rawNoteOff(note, channel) def cc_event(self, channel, control, value): self.midplayer.controllerChange(control,value, channel) def instr_event(self, channel, instr, bank): #"bank" currently not supported self.midplayer.programChange(instr, channel)
gpl-3.0
andyfaff/scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_C.py
21
18458
# -*- coding: utf-8 -*- import numpy as np from numpy import (abs, asarray, cos, exp, floor, pi, sign, sin, sqrt, sum, size, tril, isnan, atleast_2d, repeat) from numpy.testing import assert_almost_equal from .go_benchmark import Benchmark class CarromTable(Benchmark): r""" CarromTable objective function. The CarromTable [1]_ global optimization problem is a multimodal minimization problem defined as follows: .. math:: f_{\text{CarromTable}}(x) = - \frac{1}{30}\left(\cos(x_1) cos(x_2) e^{\left|1 - \frac{\sqrt{x_1^2 + x_2^2}}{\pi}\right|}\right)^2 with :math:`x_i \in [-10, 10]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = -24.15681551650653` for :math:`x_i = \pm 9.646157266348881` for :math:`i = 1, 2` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N)) self.global_optimum = [(9.646157266348881, 9.646134286497169), (-9.646157266348881, 9.646134286497169), (9.646157266348881, -9.646134286497169), (-9.646157266348881, -9.646134286497169)] self.fglob = -24.15681551650653 def fun(self, x, *args): self.nfev += 1 u = cos(x[0]) * cos(x[1]) v = sqrt(x[0] ** 2 + x[1] ** 2) return -((u * exp(abs(1 - v / pi))) ** 2) / 30. class Chichinadze(Benchmark): r""" Chichinadze objective function. This class defines the Chichinadze [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Chichinadze}}(x) = x_{1}^{2} - 12 x_{1} + 8 \sin\left(\frac{5}{2} \pi x_{1}\right) + 10 \cos\left(\frac{1}{2} \pi x_{1}\right) + 11 - 0.2 \frac{\sqrt{5}}{e^{\frac{1}{2} \left(x_{2} -0.5 \right)^{2}}} with :math:`x_i \in [-30, 30]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = -42.94438701899098` for :math:`x = [6.189866586965680, 0.5]` .. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015 TODO: Jamil#33 has a dividing factor of 2 in the sin term. However, f(x) for the given solution does not give the global minimum. i.e. the equation is at odds with the solution. Only by removing the dividing factor of 2, i.e. `8 * sin(5 * pi * x[0])` does the given solution result in the given global minimum. Do we keep the result or equation? """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-30.0] * self.N, [30.0] * self.N)) self.custom_bounds = [(-10, 10), (-10, 10)] self.global_optimum = [[6.189866586965680, 0.5]] self.fglob = -42.94438701899098 def fun(self, x, *args): self.nfev += 1 return (x[0] ** 2 - 12 * x[0] + 11 + 10 * cos(pi * x[0] / 2) + 8 * sin(5 * pi * x[0] / 2) - 1.0 / sqrt(5) * exp(-((x[1] - 0.5) ** 2) / 2)) class Cigar(Benchmark): r""" Cigar objective function. This class defines the Cigar [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Cigar}}(x) = x_1^2 + 10^6\sum_{i=2}^{n} x_i^2 Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-100, 100]` for :math:`i = 1, ..., n`. *Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for :math:`i = 1, ..., n` .. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015 """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-100.0] * self.N, [100.0] * self.N)) self.custom_bounds = [(-5, 5), (-5, 5)] self.global_optimum = [[0 for _ in range(self.N)]] self.fglob = 0.0 self.change_dimensionality = True def fun(self, x, *args): self.nfev += 1 return x[0] ** 2 + 1e6 * sum(x[1:] ** 2) class Cola(Benchmark): r""" Cola objective function. This class defines the Cola global optimization problem. The 17-dimensional function computes indirectly the formula :math:`f(n, u)` by setting :math:`x_0 = y_0, x_1 = u_0, x_i = u_{2(i2)}, y_i = u_{2(i2)+1}` : .. math:: f_{\text{Cola}}(x) = \sum_{i<j}^{n} \left (r_{i,j} - d_{i,j} \right )^2 Where :math:`r_{i, j}` is given by: .. math:: r_{i, j} = \sqrt{(x_i - x_j)^2 + (y_i - y_j)^2} And :math:`d` is a symmetric matrix given by: .. math:: \{d} = \left [ d_{ij} \right ] = \begin{pmatrix} 1.27 & & & & & & & & \\ 1.69 & 1.43 & & & & & & & \\ 2.04 & 2.35 & 2.43 & & & & & & \\ 3.09 & 3.18 & 3.26 & 2.85 & & & & & \\ 3.20 & 3.22 & 3.27 & 2.88 & 1.55 & & & & \\ 2.86 & 2.56 & 2.58 & 2.59 & 3.12 & 3.06 & & & \\ 3.17 & 3.18 & 3.18 & 3.12 & 1.31 & 1.64 & 3.00 & \\ 3.21 & 3.18 & 3.18 & 3.17 & 1.70 & 1.36 & 2.95 & 1.32 & \\ 2.38 & 2.31 & 2.42 & 1.94 & 2.85 & 2.81 & 2.56 & 2.91 & 2.97 \end{pmatrix} This function has bounds :math:`x_0 \in [0, 4]` and :math:`x_i \in [-4, 4]` for :math:`i = 1, ..., n-1`. *Global optimum* 11.7464. .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ def __init__(self, dimensions=17): Benchmark.__init__(self, dimensions) self._bounds = [[0.0, 4.0]] + list(zip([-4.0] * (self.N - 1), [4.0] * (self.N - 1))) self.global_optimum = [[0.651906, 1.30194, 0.099242, -0.883791, -0.8796, 0.204651, -3.28414, 0.851188, -3.46245, 2.53245, -0.895246, 1.40992, -3.07367, 1.96257, -2.97872, -0.807849, -1.68978]] self.fglob = 11.7464 self.d = asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1.27, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1.69, 1.43, 0, 0, 0, 0, 0, 0, 0, 0], [2.04, 2.35, 2.43, 0, 0, 0, 0, 0, 0, 0], [3.09, 3.18, 3.26, 2.85, 0, 0, 0, 0, 0, 0], [3.20, 3.22, 3.27, 2.88, 1.55, 0, 0, 0, 0, 0], [2.86, 2.56, 2.58, 2.59, 3.12, 3.06, 0, 0, 0, 0], [3.17, 3.18, 3.18, 3.12, 1.31, 1.64, 3.00, 0, 0, 0], [3.21, 3.18, 3.18, 3.17, 1.70, 1.36, 2.95, 1.32, 0, 0], [2.38, 2.31, 2.42, 1.94, 2.85, 2.81, 2.56, 2.91, 2.97, 0.]]) def fun(self, x, *args): self.nfev += 1 xi = atleast_2d(asarray([0.0, x[0]] + list(x[1::2]))) xj = repeat(xi, size(xi, 1), axis=0) xi = xi.T yi = atleast_2d(asarray([0.0, 0.0] + list(x[2::2]))) yj = repeat(yi, size(yi, 1), axis=0) yi = yi.T inner = (sqrt(((xi - xj) ** 2 + (yi - yj) ** 2)) - self.d) ** 2 inner = tril(inner, -1) return sum(sum(inner, axis=1)) class Colville(Benchmark): r""" Colville objective function. This class defines the Colville global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Colville}}(x) = \left(x_{1} -1\right)^{2} + 100 \left(x_{1}^{2} - x_{2}\right)^{2} + 10.1 \left(x_{2} -1\right)^{2} + \left(x_{3} -1\right)^{2} + 90 \left(x_{3}^{2} - x_{4}\right)^{2} + 10.1 \left(x_{4} -1\right)^{2} + 19.8 \frac{x_{4} -1}{x_{2}} with :math:`x_i \in [-10, 10]` for :math:`i = 1, ..., 4`. *Global optimum*: :math:`f(x) = 0` for :math:`x_i = 1` for :math:`i = 1, ..., 4` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. TODO docstring equation is wrong use Jamil#36 """ def __init__(self, dimensions=4): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N)) self.global_optimum = [[1 for _ in range(self.N)]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 return (100 * (x[0] - x[1] ** 2) ** 2 + (1 - x[0]) ** 2 + (1 - x[2]) ** 2 + 90 * (x[3] - x[2] ** 2) ** 2 + 10.1 * ((x[1] - 1) ** 2 + (x[3] - 1) ** 2) + 19.8 * (x[1] - 1) * (x[3] - 1)) class Corana(Benchmark): r""" Corana objective function. This class defines the Corana [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Corana}}(x) = \begin{cases} \sum_{i=1}^n 0.15 d_i [z_i - 0.05\textrm{sgn}(z_i)]^2 & \textrm{if }|x_i-z_i| < 0.05 \\ d_ix_i^2 & \textrm{otherwise}\end{cases} Where, in this exercise: .. math:: z_i = 0.2 \lfloor |x_i/s_i|+0.49999\rfloor\textrm{sgn}(x_i), d_i=(1,1000,10,100, ...) with :math:`x_i \in [-5, 5]` for :math:`i = 1, ..., 4`. *Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for :math:`i = 1, ..., 4` ..[1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015 """ def __init__(self, dimensions=4): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-5.0] * self.N, [5.0] * self.N)) self.global_optimum = [[0 for _ in range(self.N)]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 d = [1., 1000., 10., 100.] r = 0 for j in range(4): zj = floor(abs(x[j] / 0.2) + 0.49999) * sign(x[j]) * 0.2 if abs(x[j] - zj) < 0.05: r += 0.15 * ((zj - 0.05 * sign(zj)) ** 2) * d[j] else: r += d[j] * x[j] * x[j] return r class CosineMixture(Benchmark): r""" Cosine Mixture objective function. This class defines the Cosine Mixture global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{CosineMixture}}(x) = -0.1 \sum_{i=1}^n \cos(5 \pi x_i) - \sum_{i=1}^n x_i^2 Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-1, 1]` for :math:`i = 1, ..., N`. *Global optimum*: :math:`f(x) = -0.1N` for :math:`x_i = 0` for :math:`i = 1, ..., N` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. TODO, Jamil #38 has wrong minimum and wrong fglob. I plotted it. -(x**2) term is always negative if x is negative. cos(5 * pi * x) is equal to -1 for x=-1. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self.change_dimensionality = True self._bounds = list(zip([-1.0] * self.N, [1.0] * self.N)) self.global_optimum = [[-1. for _ in range(self.N)]] self.fglob = -0.9 * self.N def fun(self, x, *args): self.nfev += 1 return -0.1 * sum(cos(5.0 * pi * x)) - sum(x ** 2.0) class CrossInTray(Benchmark): r""" Cross-in-Tray objective function. This class defines the Cross-in-Tray [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{CrossInTray}}(x) = - 0.0001 \left(\left|{e^{\left|{100 - \frac{\sqrt{x_{1}^{2} + x_{2}^{2}}}{\pi}}\right|} \sin\left(x_{1}\right) \sin\left(x_{2}\right)}\right| + 1\right)^{0.1} with :math:`x_i \in [-15, 15]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = -2.062611870822739` for :math:`x_i = \pm 1.349406608602084` for :math:`i = 1, 2` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N)) self.global_optimum = [(1.349406685353340, 1.349406608602084), (-1.349406685353340, 1.349406608602084), (1.349406685353340, -1.349406608602084), (-1.349406685353340, -1.349406608602084)] self.fglob = -2.062611870822739 def fun(self, x, *args): self.nfev += 1 return (-0.0001 * (abs(sin(x[0]) * sin(x[1]) * exp(abs(100 - sqrt(x[0] ** 2 + x[1] ** 2) / pi))) + 1) ** (0.1)) class CrossLegTable(Benchmark): r""" Cross-Leg-Table objective function. This class defines the Cross-Leg-Table [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{CrossLegTable}}(x) = - \frac{1}{\left(\left|{e^{\left|{100 - \frac{\sqrt{x_{1}^{2} + x_{2}^{2}}}{\pi}}\right|} \sin\left(x_{1}\right) \sin\left(x_{2}\right)}\right| + 1\right)^{0.1}} with :math:`x_i \in [-10, 10]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = -1`. The global minimum is found on the planes :math:`x_1 = 0` and :math:`x_2 = 0` ..[1] Mishra, S. Global Optimization by Differential Evolution and Particle Swarm Methods: Evaluation on Some Benchmark Functions Munich University, 2006 """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N)) self.global_optimum = [[0., 0.]] self.fglob = -1.0 def fun(self, x, *args): self.nfev += 1 u = 100 - sqrt(x[0] ** 2 + x[1] ** 2) / pi v = sin(x[0]) * sin(x[1]) return -(abs(v * exp(abs(u))) + 1) ** (-0.1) class CrownedCross(Benchmark): r""" Crowned Cross objective function. This class defines the Crowned Cross [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{CrownedCross}}(x) = 0.0001 \left(\left|{e^{\left|{100 - \frac{\sqrt{x_{1}^{2} + x_{2}^{2}}}{\pi}}\right|} \sin\left(x_{1}\right) \sin\left(x_{2}\right)}\right| + 1\right)^{0.1} with :math:`x_i \in [-10, 10]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x_i) = 0.0001`. The global minimum is found on the planes :math:`x_1 = 0` and :math:`x_2 = 0` ..[1] Mishra, S. Global Optimization by Differential Evolution and Particle Swarm Methods: Evaluation on Some Benchmark Functions Munich University, 2006 """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N)) self.global_optimum = [[0, 0]] self.fglob = 0.0001 def fun(self, x, *args): self.nfev += 1 u = 100 - sqrt(x[0] ** 2 + x[1] ** 2) / pi v = sin(x[0]) * sin(x[1]) return 0.0001 * (abs(v * exp(abs(u))) + 1) ** (0.1) class Csendes(Benchmark): r""" Csendes objective function. This class defines the Csendes [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Csendes}}(x) = \sum_{i=1}^n x_i^6 \left[ 2 + \sin \left( \frac{1}{x_i} \right ) \right] Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-1, 1]` for :math:`i = 1, ..., N`. *Global optimum*: :math:`f(x) = 0.0` for :math:`x_i = 0` for :math:`i = 1, ..., N` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self.change_dimensionality = True self._bounds = list(zip([-1.0] * self.N, [1.0] * self.N)) self.global_optimum = [[0 for _ in range(self.N)]] self.fglob = np.nan def fun(self, x, *args): self.nfev += 1 try: return sum((x ** 6.0) * (2.0 + sin(1.0 / x))) except ZeroDivisionError: return np.nan except FloatingPointError: return np.nan def success(self, x): """Is a candidate solution at the global minimum""" val = self.fun(asarray(x)) if isnan(val): return True try: assert_almost_equal(val, 0., 4) return True except AssertionError: return False return False class Cube(Benchmark): r""" Cube objective function. This class defines the Cube global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Cube}}(x) = 100(x_2 - x_1^3)^2 + (1 - x1)^2 Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-10, 10]` for :math:`i=1,...,N`. *Global optimum*: :math:`f(x_i) = 0.0` for :math:`x = [1, 1]` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. TODO: jamil#41 has the wrong solution. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N)) self.custom_bounds = ([0, 2], [0, 2]) self.global_optimum = [[1.0, 1.0]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 return 100.0 * (x[1] - x[0] ** 3.0) ** 2.0 + (1.0 - x[0]) ** 2.0
bsd-3-clause
seanli9jan/tensorflow
tensorflow/python/kernel_tests/resource_variable_ops_test.py
2
42123
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.ops.resource_variable_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import gc import os import pickle import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import momentum from tensorflow.python.training import saver from tensorflow.python.training import training_util from tensorflow.python.util import compat class ResourceVariableOpsTest(test_util.TensorFlowTestCase): def tearDown(self): gc.collect() # This will only contain uncollectable garbage, i.e. reference cycles # involving objects with __del__ defined. self.assertEqual(0, len(gc.garbage)) def testHandleDtypeShapeMatch(self): with self.cached_session(): handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[]) with self.assertRaises(ValueError): resource_variable_ops.assign_variable_op( handle, constant_op.constant(0.0, dtype=dtypes.float32)).run() with self.assertRaises(ValueError): resource_variable_ops.assign_variable_op(handle, constant_op.constant( [0], dtype=dtypes.int32)).run() resource_variable_ops.assign_variable_op(handle, constant_op.constant( 0, dtype=dtypes.int32)).run() def testGPUInt64(self): if not context.context().num_gpus(): return with context.eager_mode(), context.device("gpu:0"): v = resource_variable_ops.ResourceVariable(1, dtype=dtypes.int64) self.assertAllEqual(1, v.numpy()) def testEagerNameNotIdentity(self): with context.eager_mode(): v0 = resource_variable_ops.ResourceVariable(1.0, name="a") v1 = resource_variable_ops.ResourceVariable(2.0, name="a") self.assertAllEqual(v0.numpy(), 1.0) self.assertAllEqual(v1.numpy(), 2.0) def testEagerNameNotNeeded(self): with context.eager_mode(): v0 = resource_variable_ops.ResourceVariable(1.0) self.assertAllEqual(v0.numpy(), 1.0) def testReadVariableDtypeMismatchEager(self): with context.eager_mode(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1], name="foo") resource_variable_ops.assign_variable_op(handle, 1) with self.assertRaisesRegexp(errors.InvalidArgumentError, "Trying to read variable with wrong dtype. " "Expected float got int32."): _ = resource_variable_ops.read_variable_op(handle, dtype=dtypes.float32) def testEagerInitializedValue(self): with context.eager_mode(): variable = resource_variable_ops.ResourceVariable(1.0, name="eager-init") self.assertAllEqual(variable.numpy(), 1.0) self.assertAllEqual(variable.initialized_value().numpy(), 1.0) def testEagerBool(self): with context.eager_mode(): v = resource_variable_ops.ResourceVariable(False, name="bool_test") self.assertAllEqual(bool(v), False) def testEagerDeepCopy(self): with context.eager_mode(): init_value = np.ones((4, 4, 4)) variable = resource_variable_ops.ResourceVariable(init_value, name="init") copied_variable = copy.deepcopy(variable) copied_variable.assign(4 * np.ones((4, 4, 4))) # Copying the variable should create a new underlying tensor with distinct # values. self.assertFalse(np.allclose(variable.numpy(), copied_variable.numpy())) def testGraphDeepCopy(self): with self.cached_session(): init_value = np.ones((4, 4, 4)) variable = resource_variable_ops.ResourceVariable(init_value, name="init") with self.assertRaises(NotImplementedError): copy.deepcopy(variable) @test_util.run_in_graph_and_eager_modes def testStridedSliceAssign(self): v = resource_variable_ops.ResourceVariable([1.0, 2.0]) self.evaluate(variables.global_variables_initializer()) self.evaluate(v[0].assign(2.0)) self.assertAllEqual(self.evaluate(v), [2.0, 2.0]) def testDifferentAssignGraph(self): with ops.Graph().as_default(): v = resource_variable_ops.ResourceVariable(1.0) ops.reset_default_graph() v.assign(2.0) # Note: this fails if we run convert_to_tensor on not the # variable graph. def testFetchHandle(self): with self.cached_session(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1], name="foo") self.assertGreater(len(handle.eval()), 0) def testCachedValueReadBeforeWrite(self): with self.cached_session() as sess: v = resource_variable_ops.ResourceVariable(0.0, caching_device="cpu:0") sess.run(v.initializer) value, _ = sess.run([v, v.assign_add(1.0)]) self.assertAllEqual(value, 0.0) def testAssignVariableDtypeMismatchEager(self): with context.eager_mode(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1], name="foo") resource_variable_ops.assign_variable_op( handle, constant_op.constant([1])) with self.assertRaisesRegexp(errors.InvalidArgumentError, "Trying to assign variable with wrong " "dtype. Expected int32 got float."): resource_variable_ops.assign_variable_op( handle, constant_op.constant([1.], dtype=dtypes.float32)) def testUnprintableHandle(self): with context.eager_mode(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1], name="foo") self.assertIn("<unprintable>", str(handle)) self.assertIn("<unprintable>", repr(handle)) @test_util.run_in_graph_and_eager_modes def testDtypeSurvivesIdentity(self): handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[]) id_handle = array_ops.identity(handle) self.evaluate(resource_variable_ops.assign_variable_op( id_handle, constant_op.constant(0, dtype=dtypes.int32))) def testUnreadOpName(self): v = resource_variable_ops.ResourceVariable(1.0) self.assertNotEqual(v.name, v.assign_add(1.0).name) @test_util.run_in_graph_and_eager_modes def testCreateRead(self): handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[]) self.evaluate(resource_variable_ops.assign_variable_op( handle, constant_op.constant(1, dtype=dtypes.int32))) value = self.evaluate( resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)) self.assertAllEqual(1, value) @test_util.run_in_graph_and_eager_modes def testManyAssigns(self): handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[]) create = resource_variable_ops.assign_variable_op( handle, constant_op.constant(1, dtype=dtypes.int32)) with ops.control_dependencies([create]): first_read = resource_variable_ops.read_variable_op( handle, dtype=dtypes.int32) with ops.control_dependencies([first_read]): write = resource_variable_ops.assign_variable_op( handle, constant_op.constant(2, dtype=dtypes.int32)) with ops.control_dependencies([write]): second_read = resource_variable_ops.read_variable_op( handle, dtype=dtypes.int32) f, s = self.evaluate([first_read, second_read]) self.assertEqual(f, 1) self.assertEqual(s, 2) @test_util.run_in_graph_and_eager_modes def testAssignAdd(self): handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[]) self.evaluate(resource_variable_ops.assign_variable_op( handle, constant_op.constant(1, dtype=dtypes.int32))) self.evaluate(resource_variable_ops.assign_add_variable_op( handle, constant_op.constant(1, dtype=dtypes.int32))) read = self.evaluate( resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32)) self.assertEqual(read, 2) @test_util.run_in_graph_and_eager_modes def testScatterAdd(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_add( handle, [0], constant_op.constant([[2]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[3]]) @test_util.run_in_graph_and_eager_modes def testScatterSub(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_sub( handle, [0], constant_op.constant([[2]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[-1]]) @test_util.run_in_graph_and_eager_modes def testScatterMul(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_mul( handle, [0], constant_op.constant([[5]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[5]]) def testEagerPickle(self): with context.eager_mode(): tmp_dir = self.get_temp_dir() fname = os.path.join(tmp_dir, "var.pickle") with open(fname, "wb") as f: v = resource_variable_ops.ResourceVariable(10.0) pickle.dump(v, f) with open(fname, "rb") as f: v = pickle.load(f) self.assertAllEqual(v.numpy(), 10.0) @test_util.run_in_graph_and_eager_modes def testScatterDiv(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_div( handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[2]]) def testUseResource(self): v = variables.VariableV1(1.0, use_resource=True) self.assertTrue(isinstance(v, resource_variable_ops.ResourceVariable)) def testEagerNoUseResource(self): with context.eager_mode(): v = variables.Variable(1.0) self.assertTrue(isinstance(v, resource_variable_ops.ResourceVariable)) @test_util.run_in_graph_and_eager_modes def testScatterMin(self): with ops.device("cpu:0"): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op(handle, constant_op.constant( [[6]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_min(handle, [0], constant_op.constant( [[3]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[3]]) def testMetagraph(self): with ops.Graph().as_default(): with variable_scope.variable_scope("foo", use_resource=True): a = variable_scope.get_variable("a", initializer=10.0) momentum.MomentumOptimizer( learning_rate=0.001, momentum=0.1).minimize( a, colocate_gradients_with_ops=True, global_step=training_util.get_or_create_global_step()) graph = ops.get_default_graph() meta_graph_def = saver.export_meta_graph(graph=graph) with ops.Graph().as_default(): saver.import_meta_graph(meta_graph_def, import_scope="") meta_graph_two = saver.export_meta_graph(graph=graph) self.assertEqual(meta_graph_def, meta_graph_two) @test_util.run_in_graph_and_eager_modes def testScatterMax(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_max( handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[6]]) @test_util.run_in_graph_and_eager_modes def testScatterAddScalar(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_add( handle, [0], constant_op.constant(2, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[3]]) @test_util.run_in_graph_and_eager_modes def testScatterSubScalar(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_sub( handle, [0], constant_op.constant(2, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[-1]]) @test_util.run_in_graph_and_eager_modes def testScatterMulScalar(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_mul( handle, [0], constant_op.constant(5, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[5]]) @test_util.run_in_graph_and_eager_modes def testScatterDivScalar(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_div( handle, [0], constant_op.constant(3, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[2]]) @test_util.run_in_graph_and_eager_modes def testScatterMinScalar(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_min( handle, [0], constant_op.constant(3, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[3]]) @test_util.run_in_graph_and_eager_modes def testScatterMaxScalar(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) self.evaluate( resource_variable_ops.resource_scatter_max( handle, [0], constant_op.constant(3, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[6]]) def testScatterUpdateString(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.string, shape=[1, 1]) self.evaluate(resource_variable_ops.assign_variable_op( handle, constant_op.constant([["a"]], dtype=dtypes.string))) self.evaluate(resource_variable_ops.resource_scatter_update( handle, [0], constant_op.constant([["b"]], dtype=dtypes.string))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.string) self.assertEqual(compat.as_bytes(self.evaluate(read)[0][0]), compat.as_bytes("b")) def testScatterUpdateStringScalar(self): handle = resource_variable_ops.var_handle_op( dtype=dtypes.string, shape=[1, 1]) self.evaluate( resource_variable_ops.assign_variable_op(handle, constant_op.constant( [["a"]], dtype=dtypes.string))) self.evaluate( resource_variable_ops.resource_scatter_update(handle, [0], constant_op.constant( "b", dtype=dtypes.string))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.string) self.assertEqual( compat.as_bytes(self.evaluate(read)[0][0]), compat.as_bytes("b")) # TODO(alive): get this to work in Eager mode. def testGPU(self): with self.test_session(use_gpu=True): abc = variable_scope.get_variable( "abc", shape=[1], initializer=init_ops.ones_initializer(), use_resource=True) self.evaluate(variables.global_variables_initializer()) self.assertEqual( self.evaluate( resource_variable_ops.var_is_initialized_op(abc.handle)), True) def testScatterBool(self): with context.eager_mode(): ref = resource_variable_ops.ResourceVariable( [False, True, False], trainable=False) indices = math_ops.range(3) updates = constant_op.constant([True, True, True]) state_ops.scatter_update(ref, indices, updates) self.assertAllEqual(ref.read_value(), [True, True, True]) @test_util.run_in_graph_and_eager_modes def testConstraintArg(self): constraint = lambda x: x v = resource_variable_ops.ResourceVariable( initial_value=lambda: 1, constraint=constraint, name="var0") self.assertEqual(v.constraint, constraint) constraint = 0 with self.assertRaises(ValueError): v = resource_variable_ops.ResourceVariable( initial_value=lambda: 1, constraint=constraint, name="var1") # TODO(alive): how should this work in Eager mode? def testInitFn(self): with self.cached_session(): v = resource_variable_ops.ResourceVariable( initial_value=lambda: 1, dtype=dtypes.float32) self.assertEqual(v.handle.op.colocation_groups(), v.initializer.inputs[1].op.colocation_groups()) def testHandleNumpy(self): with context.eager_mode(): with self.assertRaises(ValueError): resource_variable_ops.ResourceVariable( 1.0, name="handle-numpy").handle.numpy() def testCountUpTo(self): with context.eager_mode(): v = resource_variable_ops.ResourceVariable(0, name="upto") self.assertAllEqual(v.count_up_to(1), 0) with self.assertRaises(errors.OutOfRangeError): v.count_up_to(1) def testCountUpToFunction(self): with context.eager_mode(): v = resource_variable_ops.ResourceVariable(0, name="upto") self.assertAllEqual(state_ops.count_up_to(v, 1), 0) with self.assertRaises(errors.OutOfRangeError): state_ops.count_up_to(v, 1) @test_util.run_in_graph_and_eager_modes def testInitFnDtype(self): v = resource_variable_ops.ResourceVariable( initial_value=lambda: 1, dtype=dtypes.float32, name="var0") self.assertEqual(dtypes.float32, v.value().dtype) @test_util.run_in_graph_and_eager_modes def testInitFnNoDtype(self): v = resource_variable_ops.ResourceVariable(initial_value=lambda: 1, name="var2") self.assertEqual(dtypes.int32, v.value().dtype) @test_util.run_in_graph_and_eager_modes def testInitializeAllVariables(self): v = resource_variable_ops.ResourceVariable(1, dtype=dtypes.float32, name="var0") self.evaluate(variables.global_variables_initializer()) self.assertEqual(1.0, self.evaluate(v.value())) @test_util.run_in_graph_and_eager_modes def testOperatorOverload(self): v = resource_variable_ops.ResourceVariable(1.0, name="var0") self.evaluate(variables.global_variables_initializer()) self.assertEqual(2.0, self.evaluate(v + v)) @test_util.run_in_graph_and_eager_modes def testAssignMethod(self): v = resource_variable_ops.ResourceVariable(1.0, name="var0") self.evaluate(variables.global_variables_initializer()) self.evaluate(v.assign(2.0)) self.assertEqual(2.0, self.evaluate(v.value())) # Tests for the 'read_value' argument: assign_with_read = v.assign(3.0, read_value=True) self.assertEqual(3.0, self.evaluate(assign_with_read)) assign_without_read = v.assign(4.0, read_value=False) if context.executing_eagerly(): self.assertIsNone(assign_without_read) else: self.assertIsInstance(assign_without_read, ops.Operation) self.evaluate(assign_without_read) self.assertEqual(4.0, self.evaluate(v.value())) @test_util.run_in_graph_and_eager_modes def testLoad(self): v = resource_variable_ops.ResourceVariable(1.0, name="var0") self.evaluate(variables.global_variables_initializer()) v.load(2.0) self.assertEqual(2.0, self.evaluate(v.value())) def testVariableDefInitializedInstances(self): with ops.Graph().as_default(), self.cached_session() as sess: v_def = resource_variable_ops.ResourceVariable( initial_value=constant_op.constant(3.0)).to_proto() with ops.Graph().as_default(), self.cached_session() as sess: # v describes a VariableDef-based variable without an initial value. v = resource_variable_ops.ResourceVariable(variable_def=v_def) self.assertEqual(3.0, sess.run(v.initialized_value())) # initialized_value should not rerun the initializer_op if the variable # has already been initialized elsewhere. sess.run(v.assign(1.0)) self.assertEqual(1.0, v.initialized_value().eval()) v_def.ClearField("initial_value_name") with ops.Graph().as_default(), self.cached_session() as sess: # Restoring a legacy VariableDef proto that does not have # initial_value_name set should still work. v = resource_variable_ops.ResourceVariable(variable_def=v_def) # We should also be able to re-export the variable to a new meta graph. self.assertProtoEquals(v_def, v.to_proto()) # But attempts to use initialized_value will result in errors. with self.assertRaises(ValueError): sess.run(v.initialized_value()) def testTrainableInProto(self): with ops.Graph().as_default(): non_trainable_variable = resource_variable_ops.ResourceVariable( trainable=False, initial_value=constant_op.constant(10.0)) self.assertEqual( False, resource_variable_ops.ResourceVariable( variable_def=non_trainable_variable.to_proto()) .trainable) trainable_variable = resource_variable_ops.ResourceVariable( trainable=True, initial_value=constant_op.constant(10.0)) self.assertEqual( True, resource_variable_ops.ResourceVariable( variable_def=trainable_variable.to_proto()) .trainable) @test_util.run_in_graph_and_eager_modes def testSparseRead(self): init_value = np.reshape(np.arange(np.power(4, 3)), (4, 4, 4)) v = resource_variable_ops.ResourceVariable( constant_op.constant(init_value, dtype=dtypes.int32), name="var3") self.evaluate(variables.global_variables_initializer()) value = self.evaluate(v.sparse_read([0, 3, 1, 2])) self.assertAllEqual(init_value[[0, 3, 1, 2], ...], value) def testToFromProto(self): with self.cached_session(): v = resource_variable_ops.ResourceVariable(1.0) variables.global_variables_initializer().run() w = resource_variable_ops.ResourceVariable.from_proto(v.to_proto()) self.assertEquals(2, math_ops.add(w, 1).eval()) self.assertEquals(v._handle, w._handle) self.assertEquals(v._graph_element, w._graph_element) @test_util.run_in_graph_and_eager_modes def testAssignAddMethod(self): v = resource_variable_ops.ResourceVariable(1.0, name="var0") self.evaluate(variables.global_variables_initializer()) self.evaluate(v.assign_add(1.0)) self.assertEqual(2.0, self.evaluate(v.value())) # Tests for the 'read_value' argument: assign_with_read = v.assign_add(1.0, read_value=True) self.assertEqual(3.0, self.evaluate(assign_with_read)) assign_without_read = v.assign_add(1.0, read_value=False) if context.executing_eagerly(): self.assertIsNone(assign_without_read) else: self.assertIsInstance(assign_without_read, ops.Operation) self.evaluate(assign_without_read) self.assertEqual(4.0, self.evaluate(v.value())) @test_util.run_in_graph_and_eager_modes def testAssignSubMethod(self): v = resource_variable_ops.ResourceVariable(3.0, name="var0") self.evaluate(variables.global_variables_initializer()) self.evaluate(v.assign_sub(1.0)) self.assertEqual(2.0, self.evaluate(v.value())) # Tests for the 'read_value' argument: assign_with_read = v.assign_sub(1.0, read_value=True) self.assertEqual(1.0, self.evaluate(assign_with_read)) assign_without_read = v.assign_sub(1.0, read_value=False) if context.executing_eagerly(): self.assertIsNone(assign_without_read) else: self.assertIsInstance(assign_without_read, ops.Operation) self.evaluate(assign_without_read) self.assertEqual(0.0, self.evaluate(v.value())) @test_util.run_in_graph_and_eager_modes def testDestroyResource(self): v = resource_variable_ops.ResourceVariable(3.0, name="var0") self.evaluate(variables.global_variables_initializer()) self.assertEqual(3.0, self.evaluate(v.value())) self.evaluate(resource_variable_ops.destroy_resource_op(v.handle)) with self.assertRaises(errors.FailedPreconditionError): self.evaluate(v.value()) # Handle to a resource not actually created. handle = resource_variable_ops.var_handle_op(dtype=dtypes.int32, shape=[]) # Should raise no exception self.evaluate(resource_variable_ops.destroy_resource_op( handle, ignore_lookup_error=True)) def testAssignDifferentShapes(self): with self.cached_session() as sess, variable_scope.variable_scope( "foo", use_resource=True): var = variable_scope.get_variable("x", shape=[1, 1], dtype=dtypes.float32) placeholder = array_ops.placeholder(dtypes.float32) assign = var.assign(placeholder) sess.run( [assign], feed_dict={placeholder: np.zeros(shape=[2, 2], dtype=np.float32)}) def testAssignDifferentShapesEager(self): with context.eager_mode(): with variable_scope.variable_scope("foo"): var = variable_scope.get_variable("x", shape=[1, 1], dtype=dtypes.float32) with self.assertRaisesRegexp(ValueError, "Shapes.*and.*are incompatible"): assign = var.assign(np.zeros(shape=[2, 2])) self.evaluate(assign) def testDtypeAfterFromProto(self): v = resource_variable_ops.ResourceVariable(2.0) w = resource_variable_ops.ResourceVariable.from_proto(v.to_proto()) self.assertIsInstance(w.dtype, dtypes.DType) self.assertEqual(v.dtype, w.dtype) # TODO(alive): get caching to work in eager mode. def testCachingDevice(self): with ops.device("/job:server/task:1"): v = resource_variable_ops.ResourceVariable( 2.0, caching_device="/job:localhost") self.assertEqual("/job:localhost", v.value().device) with self.assertRaises(ValueError): _ = v.value().op.get_attr("_class") with ops.colocate_with(v.op): w = resource_variable_ops.ResourceVariable( 2.0, caching_device="/job:localhost") self.assertEqual("/job:localhost", w.value().device) with self.assertRaises(ValueError): _ = w.value().op.get_attr("_class") def testSharedName(self): with self.cached_session(): v = resource_variable_ops.ResourceVariable(300.0, name="var4") variables.global_variables_initializer().run() w = resource_variable_ops.var_handle_op( dtype=v.dtype.base_dtype, shape=v.get_shape(), shared_name="var4", # Needed in Eager since we get a unique container name by default. container=ops.get_default_graph()._container) w_read = resource_variable_ops.read_variable_op(w, v.dtype.base_dtype) self.assertEqual(300.0, w_read.eval()) x = resource_variable_ops.var_handle_op( dtype=v.dtype.base_dtype, shape=v.get_shape(), shared_name="var5", container=ops.get_default_graph()._container) with self.assertRaisesOpError("Resource .*/var5/.* does not exist"): resource_variable_ops.read_variable_op(x, v.dtype.base_dtype).eval() def testSharedNameWithNamescope(self): with self.cached_session(): with ops.name_scope("foo"): v = resource_variable_ops.ResourceVariable(300.0, name="var6") self.assertEqual("foo/var6", v._shared_name) # pylint: disable=protected-access self.assertEqual("foo/var6:0", v.name) self.evaluate(variables.global_variables_initializer()) w = resource_variable_ops.var_handle_op( dtype=v.dtype.base_dtype, shape=v.get_shape(), shared_name="foo/var6", # Needed in Eager since we get a unique container name by default. container=ops.get_default_graph()._container) w_read = resource_variable_ops.read_variable_op(w, v.dtype.base_dtype) self.assertEqual(300.0, self.evaluate(w_read)) @test_util.run_in_graph_and_eager_modes def testShape(self): v = resource_variable_ops.ResourceVariable( name="var4", initial_value=array_ops.ones(shape=[10, 20, 35])) self.assertEqual("(10, 20, 35)", str(v.shape)) self.assertEqual("(10, 20, 35)", str(v.get_shape())) self.assertEqual("(10, 20, 35)", str(v.value().shape)) self.assertEqual("(3, 20, 35)", str(v.sparse_read([0, 1, 2]).shape)) if not context.executing_eagerly(): self.assertEqual( "<unknown>", str(v.sparse_read(array_ops.placeholder(dtypes.int32)).shape)) def testSetInitialValue(self): with self.cached_session(): # Initialize variable with a value different from the initial value passed # in the constructor. v = resource_variable_ops.ResourceVariable(2.0) v.initializer.run(feed_dict={v.initial_value: 3.0}) self.assertEqual(3.0, v.value().eval()) def testControlFlowInitialization(self): """Expects an error if an initializer is in a control-flow scope.""" def cond(i, _): return i < 10 def body(i, _): zero = array_ops.zeros([], dtype=dtypes.int32) v = resource_variable_ops.ResourceVariable(initial_value=zero) return (i + 1, v.read_value()) with self.assertRaisesRegexp(ValueError, "inside a control-flow"): control_flow_ops.while_loop(cond, body, [0, 0]) def testVariableEager(self): with context.eager_mode(): init = array_ops.ones(shape=[10, 20, 35], dtype=dtypes.int32) constraint = lambda x: x with ops.name_scope("foo"): v = resource_variable_ops.ResourceVariable( name="var7", initial_value=init, caching_device="cpu:0", constraint=constraint) # Test properties self.assertEqual(dtypes.int32, v.dtype) self.assertEqual("foo/var7:0", v.name) self.assertAllEqual([10, 20, 35], v.shape.as_list()) self.assertTrue(isinstance(v.handle, ops.EagerTensor)) self.assertEqual(constraint, v.constraint) self.assertAllEqual(init.numpy(), v.read_value().numpy()) self.assertAllEqual(init.numpy(), v.value().numpy()) # Callable init. callable_init = lambda: init * 2 v2 = resource_variable_ops.ResourceVariable( initial_value=callable_init, name="var7") self.assertEqual("var7:0", v2.name) self.assertAllEqual(2 * init.numpy(), v2.read_value().numpy()) # Test assign_add. new_v2_val = v2.assign_add(v.read_value()) self.assertAllEqual(v.read_value().numpy() * 3, new_v2_val.numpy()) # Test assign_sub. new_v2_val = v2.assign_sub(v.read_value()) self.assertAllEqual(v.read_value().numpy() * 2, new_v2_val.numpy()) # Test assign. v2.assign(v.read_value()) self.assertAllEqual(v.read_value().numpy(), v2.read_value().numpy()) # Test load v2.load(2 * v.read_value()) self.assertAllEqual(2 * v.read_value().numpy(), v2.read_value().numpy()) # Test convert_to_tensor t = ops.convert_to_tensor(v) self.assertAllEqual(t.numpy(), v.read_value().numpy()) # Test operations self.assertAllEqual((v * 2).numpy(), (v + v).numpy()) def testContainerEager(self): with context.eager_mode(): v1 = resource_variable_ops.ResourceVariable(initial_value=lambda: 1, name="same") with ops.container("different"): v2 = resource_variable_ops.ResourceVariable(initial_value=lambda: 0, name="same") v2.assign(2) self.assertEqual(1, v1.read_value().numpy()) self.assertEqual(2, v2.read_value().numpy()) def testDestruction(self): with context.eager_mode(): var = resource_variable_ops.ResourceVariable(initial_value=1.0, name="var8") var_handle = var._handle del var with self.assertRaisesRegexp(errors.NotFoundError, r"Resource .* does not exist."): resource_variable_ops.destroy_resource_op(var_handle, ignore_lookup_error=False) def testScatterUpdate(self): with context.eager_mode(): v = resource_variable_ops.ResourceVariable([1.0, 2.0], name="update") state_ops.scatter_update(v, [1], [3.0]) self.assertAllEqual([1.0, 3.0], v.numpy()) def testScatterAddStateOps(self): with context.eager_mode(): v = resource_variable_ops.ResourceVariable([1.0, 2.0], name="add") state_ops.scatter_add(v, [1], [3]) self.assertAllEqual([1.0, 5.0], v.numpy()) def testScatterSubStateOps(self): with context.eager_mode(): v = resource_variable_ops.ResourceVariable([1.0, 2.0], name="sub") state_ops.scatter_sub(v, [1], [3]) self.assertAllEqual([1.0, -1.0], v.numpy()) def testScatterNdAddStateOps(self): with context.eager_mode(): v = resource_variable_ops.ResourceVariable( [1, 1, 1, 1, 1, 1, 1, 1], dtype=dtypes.float32, name="add") indices = constant_op.constant([[4], [3], [1], [7]], dtype=dtypes.int32) updates = constant_op.constant([9, 10, 11, 12], dtype=dtypes.float32) expected = np.array([1, 12, 1, 11, 10, 1, 1, 13]) state_ops.scatter_nd_add(v, indices, updates) self.assertAllClose(expected, v.numpy()) def testScatterUpdateCast(self): with context.eager_mode(): v = resource_variable_ops.ResourceVariable([1.0, 2.0], name="update") state_ops.scatter_update(v, [1], [3]) self.assertAllEqual([1.0, 3.0], v.numpy()) @test_util.run_in_graph_and_eager_modes def testScatterUpdateInvalidArgs(self): v = resource_variable_ops.ResourceVariable([0, 1, 2, 3], name="update") # The exact error and message differ between graph construction (where the # error is realized during shape inference at graph construction time) and # eager execution (where the error is realized during kernel execution). with self.assertRaisesRegexp(Exception, r"shape.*2.*3"): state_ops.scatter_update(v, [0, 1], [0, 1, 2]) @test_util.run_in_graph_and_eager_modes def testAssignIncompatibleShape(self): v = resource_variable_ops.ResourceVariable([0, 1, 2, 3]) self.evaluate(v.initializer) with self.assertRaisesRegexp(Exception, r"hapes must be equal"): self.assertAllEqual(self.evaluate(v.assign_add(1)), [1, 2, 3, 4]) @test_util.run_in_graph_and_eager_modes def testCopyToGraphUninitialized(self): v = resource_variable_ops.ResourceVariable([0, 1, 2, 3]) copy_to_graph = ops.Graph() with copy_to_graph.as_default(): # Intentionally testing v1 behavior copied = resource_variable_ops.copy_to_graph_uninitialized(v) self.assertEqual(v.name, copied.name) with self.session(copy_to_graph) as session: with self.assertRaises(errors.InvalidArgumentError): session.run(copied.initializer) class _MixedPrecisionVariableTest(test_util.TensorFlowTestCase): @test_util.run_in_graph_and_eager_modes() def test_dense_var_to_tensor_read_dtype_same_as_var_dtype(self): # read_dtype is same as dtype v = resource_variable_ops.ResourceVariable(1.0, dtype=dtypes.float32) v = resource_variable_ops._MixedPrecisionVariable(v, dtypes.float32) if not context.executing_eagerly(): v.initializer.run() # dtype is not read_dtype, return NotImplemented self.assertEqual( NotImplemented, v._dense_var_to_tensor(dtype=dtypes.float16)) self.assertEqual(NotImplemented, v._dense_var_to_tensor(dtype=dtypes.float16, as_ref=True)) # as_ref is False t = v._dense_var_to_tensor(as_ref=False) self.assertTrue(isinstance(t, ops.Tensor)) self.assertEqual(t.dtype, dtypes.float32) self.assertEqual(self.evaluate(t), 1.0) t = v._dense_var_to_tensor(dtype=dtypes.float32, as_ref=False) self.assertTrue(isinstance(t, ops.Tensor)) self.assertEqual(t.dtype, dtypes.float32) self.assertEqual(self.evaluate(t), 1.0) # as_ref is True self.assertEqual(NotImplemented, v._dense_var_to_tensor(as_ref=True)) self.assertEqual(NotImplemented, v._dense_var_to_tensor(dtype=dtypes.float32, as_ref=True)) @test_util.run_in_graph_and_eager_modes() def test_dense_var_to_tensor_read_dtype_different_from_var_dtype(self): # read_dtype is different from dtype v = resource_variable_ops.ResourceVariable(1.0, dtype=dtypes.float32) v = resource_variable_ops._MixedPrecisionVariable(v, dtypes.float16) if not context.executing_eagerly(): v.initializer.run() # as_ref is False t = v._dense_var_to_tensor(as_ref=False) self.assertTrue(isinstance(t, ops.Tensor)) self.assertEqual(t.dtype, dtypes.float16) self.assertEqual(self.evaluate(t), 1.0) t = v._dense_var_to_tensor(dtype=dtypes.float16, as_ref=False) self.assertTrue(isinstance(t, ops.Tensor)) self.assertEqual(t.dtype, dtypes.float16) self.assertEqual(self.evaluate(t), 1.0) # as_ref is True self.assertEqual(NotImplemented, v._dense_var_to_tensor(as_ref=True)) self.assertEqual(NotImplemented, v._dense_var_to_tensor(dtype=dtypes.float16, as_ref=True)) if __name__ == "__main__": test.main()
apache-2.0
SpiriLiao/linux
arch/ia64/scripts/unwcheck.py
13143
1714
#!/usr/bin/python # # Usage: unwcheck.py FILE # # This script checks the unwind info of each function in file FILE # and verifies that the sum of the region-lengths matches the total # length of the function. # # Based on a shell/awk script originally written by Harish Patil, # which was converted to Perl by Matthew Chapman, which was converted # to Python by David Mosberger. # import os import re import sys if len(sys.argv) != 2: print "Usage: %s FILE" % sys.argv[0] sys.exit(2) readelf = os.getenv("READELF", "readelf") start_pattern = re.compile("<([^>]*)>: \[0x([0-9a-f]+)-0x([0-9a-f]+)\]") rlen_pattern = re.compile(".*rlen=([0-9]+)") def check_func (func, slots, rlen_sum): if slots != rlen_sum: global num_errors num_errors += 1 if not func: func = "[%#x-%#x]" % (start, end) print "ERROR: %s: %lu slots, total region length = %lu" % (func, slots, rlen_sum) return num_funcs = 0 num_errors = 0 func = False slots = 0 rlen_sum = 0 for line in os.popen("%s -u %s" % (readelf, sys.argv[1])): m = start_pattern.match(line) if m: check_func(func, slots, rlen_sum) func = m.group(1) start = long(m.group(2), 16) end = long(m.group(3), 16) slots = 3 * (end - start) / 16 rlen_sum = 0L num_funcs += 1 else: m = rlen_pattern.match(line) if m: rlen_sum += long(m.group(1)) check_func(func, slots, rlen_sum) if num_errors == 0: print "No errors detected in %u functions." % num_funcs else: if num_errors > 1: err="errors" else: err="error" print "%u %s detected in %u functions." % (num_errors, err, num_funcs) sys.exit(1)
gpl-2.0
ToontownUprising/src
toontown/safezone/GSPlayground.py
3
4803
from pandac.PandaModules import * from toontown.toonbase import ToontownGlobals import Playground from toontown.launcher import DownloadForceAcknowledge from toontown.building import Elevator from toontown.toontowngui import TTDialog from toontown.toonbase import TTLocalizer from toontown.racing import RaceGlobals from direct.fsm import State class GSPlayground(Playground.Playground): def __init__(self, loader, parentFSM, doneEvent): Playground.Playground.__init__(self, loader, parentFSM, doneEvent) self.parentFSM = parentFSM self.startingBlockDoneEvent = 'startingBlockDone' self.fsm.addState(State.State('startingBlock', self.enterStartingBlock, self.exitStartingBlock, ['walk'])) state = self.fsm.getStateNamed('walk') state.addTransition('startingBlock') def load(self): Playground.Playground.load(self) def unload(self): Playground.Playground.unload(self) def enter(self, requestStatus): Playground.Playground.enter(self, requestStatus) blimp = base.cr.playGame.hood.loader.geom.find('**/GS_blimp') blimp.setPos(-70, 250, -70) blimpBase = NodePath('blimpBase') blimpBase.setPos(0, -200, 25) blimpBase.setH(-40) blimp.reparentTo(blimpBase) blimpRoot = NodePath('blimpRoot') blimpRoot.setPos(0, -70, 40) blimpRoot.reparentTo(base.cr.playGame.hood.loader.geom) blimpBase.reparentTo(blimpRoot) self.rotateBlimp = blimpRoot.hprInterval(360, Vec3(360, 0, 0)) self.rotateBlimp.loop() def exit(self): Playground.Playground.exit(self) self.rotateBlimp.finish() def doRequestLeave(self, requestStatus): self.fsm.request('trialerFA', [requestStatus]) def enterDFA(self, requestStatus): doneEvent = 'dfaDoneEvent' self.accept(doneEvent, self.enterDFACallback, [requestStatus]) self.dfa = DownloadForceAcknowledge.DownloadForceAcknowledge(doneEvent) if requestStatus['hoodId'] == ToontownGlobals.MyEstate: self.dfa.enter(base.cr.hoodMgr.getPhaseFromHood(ToontownGlobals.MyEstate)) else: self.dfa.enter(5) def enterTeleportIn(self, requestStatus): reason = requestStatus.get('reason') if reason == RaceGlobals.Exit_Barrier: requestStatus['nextState'] = 'popup' self.dialog = TTDialog.TTDialog(text=TTLocalizer.KartRace_RaceTimeout, command=self.__cleanupDialog, style=TTDialog.Acknowledge) elif reason == RaceGlobals.Exit_Slow: requestStatus['nextState'] = 'popup' self.dialog = TTDialog.TTDialog(text=TTLocalizer.KartRace_RacerTooSlow, command=self.__cleanupDialog, style=TTDialog.Acknowledge) elif reason == RaceGlobals.Exit_BarrierNoRefund: requestStatus['nextState'] = 'popup' self.dialog = TTDialog.TTDialog(text=TTLocalizer.KartRace_RaceTimeoutNoRefund, command=self.__cleanupDialog, style=TTDialog.Acknowledge) Playground.Playground.enterTeleportIn(self, requestStatus) def __cleanupDialog(self, value): if self.dialog: self.dialog.cleanup() self.dialog = None if hasattr(self, 'fsm'): self.fsm.request('walk', [1]) return def enterStartingBlock(self, distStartingBlock): import pdb pdb.set_trace() self.accept(self.startingBlockDoneEvent, self.handleStartingBlockDone) self.startingBlock = Elevator.Elevator(self.fsm.getStateNamed('startingBlock'), self.startingBlockDoneEvent, distStartingBlock) distStartingBlock.elevatorFSM = self.startingBlock self.startingBlock.load() self.startingBlock.enter() def exitStartingBlock(self): self.ignore(self.startingBlockDoneEvent) self.startingBlock.unload() self.startingBlock.exit() del self.startingBlock def detectedStartingBlockCollision(self, distStartingBlock): import pdb pdb.set_trace() self.fsm.request('startingBlock', [distStartingBlock]) def handleStartingBlockDone(self, doneStatus): self.notify.debug('handling StartingBlock done event') where = doneStatus['where'] if where == 'reject': self.fsm.request('walk') elif where == 'exit': self.fsm.request('walk') elif where == 'racetrack': self.doneStatus = doneStatus messenger.send(self.doneEvent) else: self.notify.error('Unknown mode: ' + where + ' in handleStartingBlockDone') def showPaths(self): from toontown.classicchars import CCharPaths from toontown.toonbase import TTLocalizer self.showPathPoints(CCharPaths.getPaths(TTLocalizer.Goofy, 1))
mit
nzavagli/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/simplejson-3.7.3/simplejson/tests/test_scanstring.py
139
7311
import sys from unittest import TestCase import simplejson as json import simplejson.decoder from simplejson.compat import b, PY3 class TestScanString(TestCase): # The bytes type is intentionally not used in most of these tests # under Python 3 because the decoder immediately coerces to str before # calling scanstring. In Python 2 we are testing the code paths # for both unicode and str. # # The reason this is done is because Python 3 would require # entirely different code paths for parsing bytes and str. # def test_py_scanstring(self): self._test_scanstring(simplejson.decoder.py_scanstring) def test_c_scanstring(self): if not simplejson.decoder.c_scanstring: return self._test_scanstring(simplejson.decoder.c_scanstring) def _test_scanstring(self, scanstring): if sys.maxunicode == 65535: self.assertEqual( scanstring(u'"z\U0001d120x"', 1, None, True), (u'z\U0001d120x', 6)) else: self.assertEqual( scanstring(u'"z\U0001d120x"', 1, None, True), (u'z\U0001d120x', 5)) self.assertEqual( scanstring('"\\u007b"', 1, None, True), (u'{', 8)) self.assertEqual( scanstring('"A JSON payload should be an object or array, not a string."', 1, None, True), (u'A JSON payload should be an object or array, not a string.', 60)) self.assertEqual( scanstring('["Unclosed array"', 2, None, True), (u'Unclosed array', 17)) self.assertEqual( scanstring('["extra comma",]', 2, None, True), (u'extra comma', 14)) self.assertEqual( scanstring('["double extra comma",,]', 2, None, True), (u'double extra comma', 21)) self.assertEqual( scanstring('["Comma after the close"],', 2, None, True), (u'Comma after the close', 24)) self.assertEqual( scanstring('["Extra close"]]', 2, None, True), (u'Extra close', 14)) self.assertEqual( scanstring('{"Extra comma": true,}', 2, None, True), (u'Extra comma', 14)) self.assertEqual( scanstring('{"Extra value after close": true} "misplaced quoted value"', 2, None, True), (u'Extra value after close', 26)) self.assertEqual( scanstring('{"Illegal expression": 1 + 2}', 2, None, True), (u'Illegal expression', 21)) self.assertEqual( scanstring('{"Illegal invocation": alert()}', 2, None, True), (u'Illegal invocation', 21)) self.assertEqual( scanstring('{"Numbers cannot have leading zeroes": 013}', 2, None, True), (u'Numbers cannot have leading zeroes', 37)) self.assertEqual( scanstring('{"Numbers cannot be hex": 0x14}', 2, None, True), (u'Numbers cannot be hex', 24)) self.assertEqual( scanstring('[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 21, None, True), (u'Too deep', 30)) self.assertEqual( scanstring('{"Missing colon" null}', 2, None, True), (u'Missing colon', 16)) self.assertEqual( scanstring('{"Double colon":: null}', 2, None, True), (u'Double colon', 15)) self.assertEqual( scanstring('{"Comma instead of colon", null}', 2, None, True), (u'Comma instead of colon', 25)) self.assertEqual( scanstring('["Colon instead of comma": false]', 2, None, True), (u'Colon instead of comma', 25)) self.assertEqual( scanstring('["Bad value", truth]', 2, None, True), (u'Bad value', 12)) for c in map(chr, range(0x00, 0x1f)): self.assertEqual( scanstring(c + '"', 0, None, False), (c, 2)) self.assertRaises( ValueError, scanstring, c + '"', 0, None, True) self.assertRaises(ValueError, scanstring, '', 0, None, True) self.assertRaises(ValueError, scanstring, 'a', 0, None, True) self.assertRaises(ValueError, scanstring, '\\', 0, None, True) self.assertRaises(ValueError, scanstring, '\\u', 0, None, True) self.assertRaises(ValueError, scanstring, '\\u0', 0, None, True) self.assertRaises(ValueError, scanstring, '\\u01', 0, None, True) self.assertRaises(ValueError, scanstring, '\\u012', 0, None, True) self.assertRaises(ValueError, scanstring, '\\u0123', 0, None, True) if sys.maxunicode > 65535: self.assertRaises(ValueError, scanstring, '\\ud834\\u"', 0, None, True) self.assertRaises(ValueError, scanstring, '\\ud834\\x0123"', 0, None, True) def test_issue3623(self): self.assertRaises(ValueError, json.decoder.scanstring, "xxx", 1, "xxx") self.assertRaises(UnicodeDecodeError, json.encoder.encode_basestring_ascii, b("xx\xff")) def test_overflow(self): # Python 2.5 does not have maxsize, Python 3 does not have maxint maxsize = getattr(sys, 'maxsize', getattr(sys, 'maxint', None)) assert maxsize is not None self.assertRaises(OverflowError, json.decoder.scanstring, "xxx", maxsize + 1) def test_surrogates(self): scanstring = json.decoder.scanstring def assertScan(given, expect, test_utf8=True): givens = [given] if not PY3 and test_utf8: givens.append(given.encode('utf8')) for given in givens: (res, count) = scanstring(given, 1, None, True) self.assertEqual(len(given), count) self.assertEqual(res, expect) assertScan( u'"z\\ud834\\u0079x"', u'z\ud834yx') assertScan( u'"z\\ud834\\udd20x"', u'z\U0001d120x') assertScan( u'"z\\ud834\\ud834\\udd20x"', u'z\ud834\U0001d120x') assertScan( u'"z\\ud834x"', u'z\ud834x') assertScan( u'"z\\udd20x"', u'z\udd20x') assertScan( u'"z\ud834x"', u'z\ud834x') # It may look strange to join strings together, but Python is drunk. # https://gist.github.com/etrepum/5538443 assertScan( u'"z\\ud834\udd20x12345"', u''.join([u'z\ud834', u'\udd20x12345'])) assertScan( u'"z\ud834\\udd20x"', u''.join([u'z\ud834', u'\udd20x'])) # these have different behavior given UTF8 input, because the surrogate # pair may be joined (in maxunicode > 65535 builds) assertScan( u''.join([u'"z\ud834', u'\udd20x"']), u''.join([u'z\ud834', u'\udd20x']), test_utf8=False) self.assertRaises(ValueError, scanstring, u'"z\\ud83x"', 1, None, True) self.assertRaises(ValueError, scanstring, u'"z\\ud834\\udd2x"', 1, None, True)
mit
sigma-random/RootTheBox
setup/xmlsetup.py
6
7231
# -*- coding: utf-8 -*- ''' Created on Aug 26, 2013 Copyright 2012 Root the Box 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. ------------------------------------------------------------------------------ This file wraps the Python scripted game setup API. It reads an XML file(s) and calls the API based on the it's contents. ''' import os import logging import defusedxml.cElementTree as ET # We have to import all of the classes to avoid mapper errors from setup.create_database import * from models import dbsession def get_child_by_tag(elem, tag_name): ''' Return child elements with a given tag ''' tags = filter( lambda child: child.tag == tag_name, elem.getchildren() ) return tags[0] if 0 < len(tags) else None def get_child_text(elem, tag_name): ''' Shorthand access to .text data ''' return get_child_by_tag(elem, tag_name).text def create_levels(levels): ''' Create GameLevel objects based on XML data ''' logging.info("Found %s game level(s)" % levels.get('count')) for index, level_elem in enumerate(levels.getchildren()): # GameLevel 0 is created automatically by the bootstrap if get_child_text(level_elem, 'number') != '0': try: number = get_child_text(level_elem, 'number') if GameLevel.by_number(number) is None: game_level = GameLevel() game_level.number = number game_level.buyout = get_child_text(level_elem, 'buyout') dbsession.add(game_level) else: logging.info("GameLevel %d already exists, skipping" % number) except: logging.exception("Failed to import game level #%d" % (index + 1)) dbsession.flush() game_levels = GameLevel.all() for index, game_level in enumerate(game_levels): if index + 1 < len(game_levels): game_level.next_level_id = game_levels[index + 1].id logging.info("%r -> %r" % (game_level, game_levels[index + 1])) dbsession.add(game_level) dbsession.commit() def create_hints(parent, box): ''' Create flag objects for a box ''' logging.info("Found %s hint(s)" % parent.get('count')) for index, hint_elem in enumerate(parent.getchildren()): try: hint = Hint(box_id=box.id) hint.price = get_child_text(hint_elem, 'price') hint.description = get_child_text(hint_elem, 'description') dbsession.add(hint) except: logging.exception("Failed to import hint #%d" % (index + 1)) def create_flags(parent, box): ''' Create flag objects for a box ''' logging.info("Found %s flag(s)" % parent.get('count')) for index, flag_elem in enumerate(parent.getchildren()): try: name = get_child_text(flag_elem, 'name') flag = Flag(box_id=box.id) flag.name = name flag.token = get_child_text(flag_elem, 'token') flag.value = get_child_text(flag_elem, 'value') flag.description = get_child_text(flag_elem, 'description') flag.capture_message = get_child_text(flag_elem, 'capture_message') flag.type = flag_elem.get('type') dbsession.add(flag) except: logging.exception("Failed to import flag #%d" % (index + 1)) def create_boxes(parent, corporation): ''' Create boxes for a corporation ''' logging.info("Found %s boxes" % parent.get('count')) for index, box_elem in enumerate(parent.getchildren()): try: name = get_child_text(box_elem, 'name') game_level = GameLevel.by_number(box_elem.get('gamelevel')) if game_level is None: logging.warning("GameLevel does not exist for box %s, skipping" % name) elif Box.by_name(name) is None: box = Box(corporation_id=corporation.id) box.name = name box.game_level_id = game_level.id box.difficulty = get_child_text(box_elem, 'difficulty') box.description = get_child_text(box_elem, 'description') box.operating_system = get_child_text(box_elem, 'operatingsystem') box.avatar = get_child_text(box_elem, 'avatar').decode('base64') box.garbage = get_child_text(box_elem, 'garbage') dbsession.add(box) dbsession.flush() create_flags(get_child_by_tag(box_elem, 'flags'), box) create_hints(get_child_by_tag(box_elem, 'hints'), box) else: logging.info("Box with name %s already exists, skipping" % name) except: logging.exception("Failed to import box %d" % (index + 1)) def create_corps(corps): ''' Create Corporation objects based on XML data ''' logging.info("Found %s corporation(s)" % corps.get('count')) for index, corp_elem in enumerate(corps): try: corporation = Corporation() corporation.name = get_child_text(corp_elem, 'name') dbsession.add(corporation) dbsession.flush() create_boxes(get_child_by_tag(corp_elem, 'boxes'), corporation) except: logging.exception("Faild to create corporation #%d" % (index + 1)) def _xml_file_import(filename): ''' Parse and import a single XML file ''' logging.debug("Processing: %s" % filename) try: tree = ET.parse(filename) xml_root = tree.getroot() levels = get_child_by_tag(xml_root, "gamelevels") create_levels(levels) corporations = get_child_by_tag(xml_root, "corporations") create_corps(corporations) logging.debug("Done processing: %s" % filename) dbsession.commit() return True except: dbsession.rollback() logging.exception("Exception raised while parsing %s, rolling back changes" % filename) return False def import_xml(target): ''' Import XML file or directory of files ''' target = os.path.abspath(target) if not os.path.exists(target): logging.error("Error: Target does not exist (%s) " % target) elif os.path.isdir(target): # Import any .xml files in the target directory logging.debug("%s is a directory ..." % target) ls = filter(lambda fname: fname.lower().endswith('.xml'), os.listdir(target)) logging.debug("Found %d XML file(s) ..." % len(ls)) results = [_xml_file_import(target + '/' + fxml) for fxml in ls] return False not in results else: # Import a single file return _xml_file_import(target)
apache-2.0
davidzchen/tensorflow
tensorflow/python/distribute/test_util_test.py
2
2627
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for test utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized from tensorflow.python.distribute import combinations from tensorflow.python.distribute import strategy_combinations from tensorflow.python.distribute import test_util from tensorflow.python.eager import def_function from tensorflow.python.eager import test from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops @combinations.generate( combinations.combine( strategy=[ strategy_combinations.multi_worker_mirrored_2x1_cpu, strategy_combinations.multi_worker_mirrored_2x1_gpu, strategy_combinations.multi_worker_mirrored_2x2_gpu, ] + strategy_combinations.strategies_minus_tpu, mode=['eager', 'graph'])) class GatherTest(test.TestCase, parameterized.TestCase): def testOne(self, strategy): @def_function.function def f(): return array_ops.ones((), dtypes.float32) results = test_util.gather(strategy, strategy.run(f)) self.assertAllEqual( self.evaluate(results), [1.] * strategy.num_replicas_in_sync) def testNest(self, strategy): @def_function.function def f(): return { 'foo': array_ops.ones((), dtypes.float32), 'bar': [ array_ops.zeros((), dtypes.float32), array_ops.ones((), dtypes.float32), ] } results = test_util.gather(strategy, strategy.run(f)) self.assertAllEqual( self.evaluate(results['foo']), [1.] * strategy.num_replicas_in_sync) self.assertAllEqual( self.evaluate(results['bar'][0]), [0.] * strategy.num_replicas_in_sync) self.assertAllEqual( self.evaluate(results['bar'][1]), [1.] * strategy.num_replicas_in_sync) if __name__ == '__main__': combinations.main()
apache-2.0
40223134/w16b_test
static/Brython3.1.1-20150328-091302/Lib/signal.py
743
1646
"""This module provides mechanisms to use signal handlers in Python. Functions: alarm() -- cause SIGALRM after a specified time [Unix only] setitimer() -- cause a signal (described below) after a specified float time and the timer may restart then [Unix only] getitimer() -- get current value of timer [Unix only] signal() -- set the action for a given signal getsignal() -- get the signal action for a given signal pause() -- wait until a signal arrives [Unix only] default_int_handler() -- default SIGINT handler signal constants: SIG_DFL -- used to refer to the system default handler SIG_IGN -- used to ignore the signal NSIG -- number of defined signals SIGINT, SIGTERM, etc. -- signal numbers itimer constants: ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon expiration ITIMER_VIRTUAL -- decrements only when the process is executing, and delivers SIGVTALRM upon expiration ITIMER_PROF -- decrements both when the process is executing and when the system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, this timer is usually used to profile the time spent by the application in user and kernel space. SIGPROF is delivered upon expiration. *** IMPORTANT NOTICE *** A signal handler function is called with two arguments: the first is the signal number, the second is the interrupted stack frame.""" CTRL_BREAK_EVENT=1 CTRL_C_EVENT=0 NSIG=23 SIGABRT=22 SIGBREAK=21 SIGFPE=8 SIGILL=4 SIGINT=2 SIGSEGV=11 SIGTERM=15 SIG_DFL=0 SIG_IGN=1 def signal(signalnum, handler) : pass
agpl-3.0
mdietrichc2c/OCB
openerp/__init__.py
100
3416
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """ OpenERP core library.""" #---------------------------------------------------------- # Running mode flags (gevent, prefork) #---------------------------------------------------------- # Is the server running with gevent. import sys evented = False if sys.modules.get("gevent") is not None: evented = True # Is the server running in pefork mode (e.g. behind Gunicorn). # If this is True, the processes have to communicate some events, # e.g. database update or cache invalidation. Each process has also # its own copy of the data structure and we don't need to care about # locks between threads. multi_process = False #---------------------------------------------------------- # libc UTC hack #---------------------------------------------------------- # Make sure the OpenERP server runs in UTC. This is especially necessary # under Windows as under Linux it seems the real import of time is # sufficiently deferred so that setting the TZ environment variable # in openerp.cli.server was working. import os os.environ['TZ'] = 'UTC' # Set the timezone... import time # ... *then* import time. del os del time #---------------------------------------------------------- # Shortcuts #---------------------------------------------------------- # The hard-coded super-user id (a.k.a. administrator, or root user). SUPERUSER_ID = 1 def registry(database_name): """ Return the model registry for the given database. If the registry does not exist yet, it is created on the fly. """ return modules.registry.RegistryManager.get(database_name) #---------------------------------------------------------- # Imports #---------------------------------------------------------- import addons import conf import loglevels import modules import netsvc import osv import pooler import release import report import service import sql_db import tools import workflow #---------------------------------------------------------- # Model classes, fields, api decorators, and translations #---------------------------------------------------------- from . import models from . import fields from . import api from openerp.tools.translate import _ #---------------------------------------------------------- # Other imports, which may require stuff from above #---------------------------------------------------------- import cli import http # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
fengjingchao/zookeeper
src/contrib/huebrowser/zkui/src/zkui/utils.py
114
1120
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from zkui import settings from django.http import Http404 def get_cluster_or_404(id): try: id = int(id) if not (0 <= id < len(settings.CLUSTERS)): raise ValueError, 'Undefined cluster id.' except (TypeError, ValueError): raise Http404() cluster = settings.CLUSTERS[id] cluster['id'] = id return cluster
apache-2.0
lgscofield/odoo
addons/website_customer/controllers/main.py
251
4306
# -*- coding: utf-8 -*- import openerp from openerp import SUPERUSER_ID from openerp.addons.web import http from openerp.addons.website.models.website import unslug from openerp.tools.translate import _ from openerp.addons.web.http import request import werkzeug.urls class WebsiteCustomer(http.Controller): _references_per_page = 20 @http.route([ '/customers', '/customers/page/<int:page>', '/customers/country/<int:country_id>', '/customers/country/<country_name>-<int:country_id>', '/customers/country/<int:country_id>/page/<int:page>', '/customers/country/<country_name>-<int:country_id>/page/<int:page>', ], type='http', auth="public", website=True) def customers(self, country_id=0, page=0, country_name='', **post): cr, uid, context = request.cr, request.uid, request.context country_obj = request.registry['res.country'] partner_obj = request.registry['res.partner'] partner_name = post.get('search', '') domain = [('website_published', '=', True), ('assigned_partner_id', '!=', False)] if partner_name: domain += [ '|', ('name', 'ilike', post.get("search")), ('website_description', 'ilike', post.get("search")) ] # group by country, based on customers found with the search(domain) countries = partner_obj.read_group( cr, openerp.SUPERUSER_ID, domain, ["id", "country_id"], groupby="country_id", orderby="country_id", context=request.context) country_count = partner_obj.search( cr, openerp.SUPERUSER_ID, domain, count=True, context=request.context) if country_id: domain += [('country_id', '=', country_id)] if not any(x['country_id'][0] == country_id for x in countries if x['country_id']): country = country_obj.read(cr, uid, country_id, ['name'], context) if country: countries.append({ 'country_id_count': 0, 'country_id': (country_id, country['name']) }) countries.sort(key=lambda d: d['country_id'] and d['country_id'][1]) countries.insert(0, { 'country_id_count': country_count, 'country_id': (0, _("All Countries")) }) # search customers to display partner_count = partner_obj.search_count(cr, openerp.SUPERUSER_ID, domain, context=request.context) # pager url = '/customers' if country_id: url += '/country/%s' % country_id pager = request.website.pager( url=url, total=partner_count, page=page, step=self._references_per_page, scope=7, url_args=post ) partner_ids = partner_obj.search(request.cr, openerp.SUPERUSER_ID, domain, offset=pager['offset'], limit=self._references_per_page, context=request.context) google_map_partner_ids = ','.join(map(str, partner_ids)) partners = partner_obj.browse(request.cr, openerp.SUPERUSER_ID, partner_ids, request.context) values = { 'countries': countries, 'current_country_id': country_id or 0, 'partners': partners, 'google_map_partner_ids': google_map_partner_ids, 'pager': pager, 'post': post, 'search_path': "?%s" % werkzeug.url_encode(post), } return request.website.render("website_customer.index", values) # Do not use semantic controller due to SUPERUSER_ID @http.route(['/customers/<partner_id>'], type='http', auth="public", website=True) def partners_detail(self, partner_id, **post): _, partner_id = unslug(partner_id) if partner_id: partner = request.registry['res.partner'].browse(request.cr, SUPERUSER_ID, partner_id, context=request.context) if partner.exists() and partner.website_published: values = {} values['main_object'] = values['partner'] = partner return request.website.render("website_customer.details", values) return self.customers(**post)
agpl-3.0
globocom/database-as-a-service
dbaas/maintenance/async_jobs/base.py
1
5453
from copy import copy from notification.models import TaskHistory from util import get_worker_name from workflow.workflow import steps_for_instances, rollback_for_instances_full __all__ = ('BaseJob',) class BaseJob(object): step_manger_class = None get_steps_method = None success_msg = '' error_msg = '' success_auto_rollback_msg = '' error_auto_rollback_msg = '' def __init__(self, request, database, task, since_step=None, step_manager=None, scheduled_task=None, auto_rollback=False, auto_cleanup=False): self.request = request self.database = database self.task = self.register_task_history(task) self.step_manager = self._create_step_manager( previous_step_manager=step_manager, scheduled_task=scheduled_task, database=database, task=self.task ) self.current_step = self.step_manager.current_step self.auto_rollback = auto_rollback self.auto_cleanup = auto_cleanup self.scheduled_task = scheduled_task @property def steps(self): if self.get_steps_method is None: raise Exception(('You must set your get_steps method name ' 'class in variable get_steps_method')) get_steps_func = getattr(self.database.infra, self.get_steps_method) return get_steps_func() @property def instances(self): raise NotImplementedError('You must override this method') def register_task_history(self, task): return TaskHistory.register( request=self.request, task_history=task, user=task.user, worker_name=get_worker_name() ) def _create_step_manager(self, previous_step_manager, scheduled_task, database, task): if self.step_manger_class is None: raise Exception(('You must set your step_manager class in variable' 'step_manager_class')) step_manager = self.step_manger_class() if previous_step_manager is None: previous_step_manager = self.step_manger_class.objects.filter( can_do_retry=True, database=database, status=self.step_manger_class.ERROR ).last() if previous_step_manager: step_manager = copy(previous_step_manager) step_manager.id = None step_manager.started_at = None step_manager.current_step = previous_step_manager.current_step step_manager.task_schedule = ( previous_step_manager.task_schedule ) step_manager.database = database step_manager.task = task if scheduled_task: step_manager.task_schedule = scheduled_task step_manager.set_running() step_manager.save() return step_manager def reload_step_manager(self): self.step_manager = self.step_manger_class.objects.get( id=self.step_manager.id ) def rollback(self, steps, instances, new_task, rollback_step_manager): return rollback_for_instances_full( self.steps, self.instances, new_task, rollback_step_manager.get_current_step, rollback_step_manager.update_step, rollback_step_manager ) def run_auto_cleanup_if_configured(self, step_manager=None, force=False): if self.auto_cleanup or force: step_manager = step_manager or self.step_manager if hasattr(step_manager, 'cleanup'): step_manager.cleanup(self.instances) def run_auto_rollback_if_configured(self): if self.auto_rollback: new_task = copy(self.task) new_task.id = None new_task.details = '' new_task.task_name += '_rollback' new_task.task_status = new_task.STATUS_RUNNING new_task.save() rollback_step_manager = copy(self.step_manager) rollback_step_manager.id = None rollback_step_manager.task_schedule = None rollback_step_manager.can_do_retry = 0 rollback_step_manager.save() result = self.rollback( self.steps, self.instances, new_task, rollback_step_manager ) if result: rollback_step_manager.set_success() self.task.set_status_success( self.success_auto_rollback_msg ) else: self.run_auto_cleanup_if_configured( rollback_step_manager, force=True ) rollback_step_manager.set_error() self.task.set_status_error(self.error_auto_rollback_msg) def run(self): result = steps_for_instances( self.steps, self.instances, self.task, self.step_manager.update_step, self.current_step, step_manager=self.step_manager ) self.reload_step_manager() if result: self.step_manager.set_success() self.task.set_status_success(self.success_msg) else: self.step_manager.set_error() self.task.set_status_error(self.error_msg) self.run_auto_rollback_if_configured() self.run_auto_cleanup_if_configured()
bsd-3-clause
deathping1994/sendmail-api
venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/sbcharsetprober.py
2927
4793
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import sys from . import constants from .charsetprober import CharSetProber from .compat import wrap_ord SAMPLE_SIZE = 64 SB_ENOUGH_REL_THRESHOLD = 1024 POSITIVE_SHORTCUT_THRESHOLD = 0.95 NEGATIVE_SHORTCUT_THRESHOLD = 0.05 SYMBOL_CAT_ORDER = 250 NUMBER_OF_SEQ_CAT = 4 POSITIVE_CAT = NUMBER_OF_SEQ_CAT - 1 #NEGATIVE_CAT = 0 class SingleByteCharSetProber(CharSetProber): def __init__(self, model, reversed=False, nameProber=None): CharSetProber.__init__(self) self._mModel = model # TRUE if we need to reverse every pair in the model lookup self._mReversed = reversed # Optional auxiliary prober for name decision self._mNameProber = nameProber self.reset() def reset(self): CharSetProber.reset(self) # char order of last character self._mLastOrder = 255 self._mSeqCounters = [0] * NUMBER_OF_SEQ_CAT self._mTotalSeqs = 0 self._mTotalChar = 0 # characters that fall in our sampling range self._mFreqChar = 0 def get_charset_name(self): if self._mNameProber: return self._mNameProber.get_charset_name() else: return self._mModel['charsetName'] def feed(self, aBuf): if not self._mModel['keepEnglishLetter']: aBuf = self.filter_without_english_letters(aBuf) aLen = len(aBuf) if not aLen: return self.get_state() for c in aBuf: order = self._mModel['charToOrderMap'][wrap_ord(c)] if order < SYMBOL_CAT_ORDER: self._mTotalChar += 1 if order < SAMPLE_SIZE: self._mFreqChar += 1 if self._mLastOrder < SAMPLE_SIZE: self._mTotalSeqs += 1 if not self._mReversed: i = (self._mLastOrder * SAMPLE_SIZE) + order model = self._mModel['precedenceMatrix'][i] else: # reverse the order of the letters in the lookup i = (order * SAMPLE_SIZE) + self._mLastOrder model = self._mModel['precedenceMatrix'][i] self._mSeqCounters[model] += 1 self._mLastOrder = order if self.get_state() == constants.eDetecting: if self._mTotalSeqs > SB_ENOUGH_REL_THRESHOLD: cf = self.get_confidence() if cf > POSITIVE_SHORTCUT_THRESHOLD: if constants._debug: sys.stderr.write('%s confidence = %s, we have a' 'winner\n' % (self._mModel['charsetName'], cf)) self._mState = constants.eFoundIt elif cf < NEGATIVE_SHORTCUT_THRESHOLD: if constants._debug: sys.stderr.write('%s confidence = %s, below negative' 'shortcut threshhold %s\n' % (self._mModel['charsetName'], cf, NEGATIVE_SHORTCUT_THRESHOLD)) self._mState = constants.eNotMe return self.get_state() def get_confidence(self): r = 0.01 if self._mTotalSeqs > 0: r = ((1.0 * self._mSeqCounters[POSITIVE_CAT]) / self._mTotalSeqs / self._mModel['mTypicalPositiveRatio']) r = r * self._mFreqChar / self._mTotalChar if r >= 1.0: r = 0.99 return r
apache-2.0
Chilledheart/vbox
src/VBox/ValidationKit/testmanager/config.py
2
6083
# -*- coding: utf-8 -*- # $Id$ """ Test Manager Configuration. """ __copyright__ = \ """ Copyright (C) 2012-2014 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation, in version 2 as it comes in the "COPYING" file of the VirtualBox OSE distribution. VirtualBox OSE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. The contents of this file may alternatively be used under the terms of the Common Development and Distribution License Version 1.0 (CDDL) only, as it comes in the "COPYING.CDDL" file of the VirtualBox OSE distribution, in which case the provisions of the CDDL are applicable instead of those of the GPL. You may elect to license modified versions of this file under the terms and conditions of either the GPL or the CDDL or both. """ __version__ = "$Revision$" import os; ## Test Manager version string. g_ksVersion = 'v0.0.2'; ## Test Manager revision string. g_ksRevision = ('$Revision$')[11:-2]; ## Enable VBox specific stuff. g_kfVBoxSpecific = True; ## @name Used by the TMDatabaseConnection class. # @{ g_ksDatabaseName = 'testmanager'; g_ksDatabaseAddress = None; g_ksDatabasePort = None; g_ksDatabaseUser = 'postgres'; g_ksDatabasePassword = ''; ## @} ## @name User handling. ## @{ ## Whether login names are case insensitive (True) or case sensitive (False). ## @note Implemented by inserting lower case names into DB and lower case ## bind variables in WHERE clauses. g_kfLoginNameCaseInsensitive = True; ## @} ## @name File locations ## @{ ## The TestManager directory. g_ksTestManagerDir = os.path.dirname(os.path.abspath(__file__)); ## The Validation Kit directory. g_ksValidationKitDir = os.path.dirname(g_ksTestManagerDir); ## The TestManager htdoc directory. g_ksTmHtDocDir = os.path.join(g_ksTestManagerDir, 'htdocs'); ## The TestManager download directory (under htdoc somewhere), for validationkit zips. g_ksTmDownloadDir = os.path.join(g_ksTmHtDocDir, 'download'); ## The base URL relative path of the TM download directory (g_ksTmDownloadDir). g_ksTmDownloadBaseUrlRel = 'htdocs/downloads'; ## The root of the file area (referred to as TM_FILE_DIR in database docs). g_ksFileAreaRootDir = '/var/tmp/testmanager' ## The root of the file area with the zip files (best put on a big storage server). g_ksZipFileAreaRootDir = '/var/tmp/testmanager2' ## URL prefix for trac log viewer. g_ksTracLogUrlPrefix = 'https://linserv.de.oracle.com/vbox/log/' ## URL prefix for trac log viewer. g_ksTracChangsetUrlFmt = 'https://linserv.de.oracle.com/%(sRepository)s/changeset/%(iRevision)s' ## URL prefix for unprefixed build logs. g_ksBuildLogUrlPrefix = '' ## URL prefix for unprefixed build binaries. g_ksBuildBinUrlPrefix = '/builds/' ## The local path prefix for unprefixed build binaries. (Host file system, not web server.) g_ksBuildBinRootDir = '/mnt/builds/' ## File on the build binary share that can be used to check that it's mounted. g_ksBuildBinRootFile = 'builds.txt' ## @} ## The time to wait for a gang to gather (in seconds). g_kcSecGangGathering = 600; ## The max time allowed to spend looking for a new task (in seconds). g_kcSecMaxNewTask = 60; ## @name Test result limits. ## In general, we will fail the test when reached and stop accepting further results. ## @{ ## The max number of test results per test set. g_kcMaxTestResultsPerTS = 4096; ## The max number of test results (children) per test result. g_kcMaxTestResultsPerTR = 512; ## The max number of test result values per test set. g_kcMaxTestValuesPerTS = 4096; ## The max number of test result values per test result. g_kcMaxTestValuesPerTR = 256; ## The max number of test result message per test result. g_kcMaxTestMsgsPerTR = 4; ## The max test result nesting depth. g_kcMaxTestResultDepth = 8; ## The max length of a test result name. g_kcchMaxTestResultName = 64; ## The max length of a test result value name. g_kcchMaxTestValueName = 48; ## The max length of a test result message. g_kcchMaxTestMsg = 128; ## The max size of the main log file. g_kcMbMaxMainLog = 32; ## The max size of an uploaded file (individual). g_kcMbMaxUploadSingle = 16; ## The max size of all uploaded file. g_kcMbMaxUploadTotal = 128; ## The max number of files that can be uploaded. g_kcMaxUploads = 256; ## @} ## @name Debug Features ## @{ ## Enables extra DB exception information. g_kfDebugDbXcpt = True; ## Where to write the glue debug. # None indicates apache error log, string indicates a file. #g_ksSrcGlueDebugLogDst = '/tmp/testmanager-srv-glue.log'; g_ksSrcGlueDebugLogDst = None; ## Whether to enable CGI trace back in the server glue. g_kfSrvGlueCgiTb = False; ## Enables glue debug output. g_kfSrvGlueDebug = False; ## Timestamp the glue debug output. g_kfSrvGlueDebugTS = True; ## Enables task scheduler debug output to g_ksSrcGlueDebugLogDst. g_kfSrvGlueDebugScheduler = False; ## Enables the SQL trace back. g_kfWebUiSqlTrace = False; ## Enables the explain in the SQL trace back. g_kfWebUiSqlTraceExplain = False; ## Whether the postgresql version supports the TIMING option on EXPLAIN (>= 9.2). g_kfWebUiSqlTraceExplainTiming = False; ## Display time spent processing the page. g_kfWebUiProcessedIn = True; ## Enables WebUI debug output. g_kfWebUiDebug = False; ## Enables WebUI SQL debug output print() calls (requires g_kfWebUiDebug). g_kfWebUiSqlDebug = False; ## Enables the debug panel at the bottom of the page. g_kfWebUiDebugPanel = True; ## Profile cgi/admin.py. g_kfProfileAdmin = False; ## Profile cgi/index.py. g_kfProfileIndex = False; ## When not None, g_ksTestBoxDispXpctLog = '/tmp/testmanager-testboxdisp-xcpt.log' ## @}
gpl-2.0
Azulinho/ansible
test/units/modules/network/cumulus/test_nclu.py
132
9512
# -*- coding: utf-8 -*- # (c) 2016, Cumulus Networks <ce-ceng@cumulusnetworks.com> # # This file is part of Ansible # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. import os.path import unittest from ansible.modules.network.cumulus import nclu class FakeModule(object): """Fake NCLU module to check the logic of the ansible module. We have two sets of tests: fake and real. Real tests only run if NCLU is installed on the testing machine (it should be a Cumulus VX VM or something like that). Fake tests are used to test the logic of the ansible module proper - that the right things are done when certain feedback is received. Real tests are used to test regressions against versions of NCLU. This FakeModule mimics the output that is used for screenscraping. If the real output differs, the real tests will catch that. To prepare a VX: sudo apt-get update sudo apt-get install python-setuptools git gcc python-dev libssl-dev sudo easy_install pip sudo pip install ansible nose coverage # git the module and cd to the directory nosetests --with-coverage --cover-package=nclu --cover-erase --cover-branches If a real test fails, it means that there is a risk of a version split, and that changing the module will break for old versions of NCLU if not careful. """ def __init__(self, **kwargs): self.reset() def exit_json(self, **kwargs): self.exit_code = kwargs def fail_json(self, **kwargs): self.fail_code = kwargs def run_command(self, command): """Run an NCLU command""" self.command_history.append(command) if command == "/usr/bin/net pending": return (0, self.pending, "") elif command == "/usr/bin/net abort": self.pending = "" return (0, "", "") elif command.startswith("/usr/bin/net commit"): if self.pending: self.last_commit = self.pending self.pending = "" return (0, "", "") else: return (0, "commit ignored...there were no pending changes", "") elif command == "/usr/bin/net show commit last": return (0, self.last_commit, "") else: self.pending += command return self.mocks.get(command, (0, "", "")) def mock_output(self, command, _rc, output, _err): """Prepare a command to mock certain output""" self.mocks[command] = (_rc, output, _err) def reset(self): self.params = {} self.exit_code = {} self.fail_code = {} self.command_history = [] self.mocks = {} self.pending = "" self.last_commit = "" def skipUnlessNcluInstalled(original_function): if os.path.isfile('/usr/bin/net'): return original_function else: return unittest.skip('only run if nclu is installed') class TestNclu(unittest.TestCase): def test_command_helper(self): module = FakeModule() module.mock_output("/usr/bin/net add int swp1", 0, "", "") result = nclu.command_helper(module, 'add int swp1', 'error out') self.assertEqual(module.command_history[-1], "/usr/bin/net add int swp1") self.assertEqual(result, "") def test_command_helper_error_code(self): module = FakeModule() module.mock_output("/usr/bin/net fake fail command", 1, "", "") result = nclu.command_helper(module, 'fake fail command', 'error out') self.assertEqual(module.fail_code, {'msg': "error out"}) def test_command_helper_error_msg(self): module = FakeModule() module.mock_output("/usr/bin/net fake fail command", 0, "ERROR: Command not found", "") result = nclu.command_helper(module, 'fake fail command', 'error out') self.assertEqual(module.fail_code, {'msg': "error out"}) def test_command_helper_no_error_msg(self): module = FakeModule() module.mock_output("/usr/bin/net fake fail command", 0, "ERROR: Command not found", "") result = nclu.command_helper(module, 'fake fail command') self.assertEqual(module.fail_code, {'msg': "ERROR: Command not found"}) def test_empty_run(self): module = FakeModule() changed, output = nclu.run_nclu(module, None, None, False, False, False, "") self.assertEqual(module.command_history, ['/usr/bin/net pending', '/usr/bin/net pending']) self.assertEqual(module.fail_code, {}) self.assertEqual(changed, False) def test_command_list(self): module = FakeModule() changed, output = nclu.run_nclu(module, ['add int swp1', 'add int swp2'], None, False, False, False, "") self.assertEqual(module.command_history, ['/usr/bin/net pending', '/usr/bin/net add int swp1', '/usr/bin/net add int swp2', '/usr/bin/net pending']) self.assertNotEqual(len(module.pending), 0) self.assertEqual(module.fail_code, {}) self.assertEqual(changed, True) def test_command_list_commit(self): module = FakeModule() changed, output = nclu.run_nclu(module, ['add int swp1', 'add int swp2'], None, True, False, False, "committed") self.assertEqual(module.command_history, ['/usr/bin/net pending', '/usr/bin/net add int swp1', '/usr/bin/net add int swp2', '/usr/bin/net pending', "/usr/bin/net commit description 'committed'", '/usr/bin/net show commit last']) self.assertEqual(len(module.pending), 0) self.assertEqual(module.fail_code, {}) self.assertEqual(changed, True) def test_command_atomic(self): module = FakeModule() changed, output = nclu.run_nclu(module, ['add int swp1', 'add int swp2'], None, False, True, False, "atomically") self.assertEqual(module.command_history, ['/usr/bin/net abort', '/usr/bin/net pending', '/usr/bin/net add int swp1', '/usr/bin/net add int swp2', '/usr/bin/net pending', "/usr/bin/net commit description 'atomically'", '/usr/bin/net show commit last']) self.assertEqual(len(module.pending), 0) self.assertEqual(module.fail_code, {}) self.assertEqual(changed, True) def test_command_abort_first(self): module = FakeModule() module.pending = "dirty" nclu.run_nclu(module, None, None, False, False, True, "") self.assertEqual(len(module.pending), 0) def test_command_template_commit(self): module = FakeModule() changed, output = nclu.run_nclu(module, None, " add int swp1\n add int swp2", True, False, False, "committed") self.assertEqual(module.command_history, ['/usr/bin/net pending', '/usr/bin/net add int swp1', '/usr/bin/net add int swp2', '/usr/bin/net pending', "/usr/bin/net commit description 'committed'", '/usr/bin/net show commit last']) self.assertEqual(len(module.pending), 0) self.assertEqual(module.fail_code, {}) self.assertEqual(changed, True) def test_commit_ignored(self): module = FakeModule() changed, output = nclu.run_nclu(module, None, None, True, False, False, "ignore me") self.assertEqual(module.command_history, ['/usr/bin/net pending', '/usr/bin/net pending', "/usr/bin/net commit description 'ignore me'", '/usr/bin/net abort']) self.assertEqual(len(module.pending), 0) self.assertEqual(module.fail_code, {}) self.assertEqual(changed, False)
gpl-3.0
hovo1990/deviser
generator/bindings_files/DowncastPackagesFile.py
1
16916
#!/usr/bin/env python # # @file DowncastPackagesFile.py # @brief class for generating downcast packages file # @author Frank Bergmann # @author Sarah Keating # # <!-------------------------------------------------------------------------- # # Copyright (c) 2013-2015 by the California Institute of Technology # (California, USA), the European Bioinformatics Institute (EMBL-EBI, UK) # and the University of Heidelberg (Germany), with support from the National # Institutes of Health (USA) under grant R01GM070923. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, 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. # # Neither the name of the California Institute of Technology (Caltech), nor # of the European Bioinformatics Institute (EMBL-EBI), nor of the University # of Heidelberg, nor the names of any contributors, may be used to endorse # or promote products derived from this software without specific prior # written permission. # ------------------------------------------------------------------------ --> from base_files import BaseCppFile from util import strFunctions, global_variables class DowncastPackagesFile(): """Class for downcast Packages files""" def __init__(self, name, package, binding, elements, plugins=None, local=False): if not plugins: plugins = [] self.binding = binding self.package = package.lower() self.cap_package = self.package.upper() self.up_package = strFunctions.upper_first(self.package) self.local = local if self.local and len(name) > 0: self.fileout = BaseCppFile.BaseCppFile(name, 'i', None) self.fileout.brief_description = 'Casting to most specific ' \ 'packages object for ' \ '{0}'.format(binding) elif binding == 'csharp' or binding == 'java': self.fileout = BaseCppFile.BaseCppFile(name, 'i', None) self.fileout.brief_description = 'Casting to most specific ' \ 'packages object for ' \ '{0}'.format(binding) else: self.fileout = BaseCppFile.BaseCppFile(name, 'cpp', None) self.fileout.brief_description = 'Casting to most specific ' \ 'packages object for ' \ '{0}'.format(binding) self.elements = elements self.plugins = plugins self.language = global_variables.language self.cap_language = global_variables.language.upper() self.base = global_variables.std_base ######################################################################## # Write binding specific code # write the local-downcast-packages-{}.cpp for # javascript, perl,python,r,ruby def write_binding_specific_cpp_code(self): self.fileout.skip_line(2) self.fileout.write_line('#ifdef USE_{0}'.format(self.cap_package)) line = 'else if (pkgName == \"{0}\")'.format(self.package) self.fileout.write_line(line) self.fileout.write_line('{') self.fileout.up_indent() self.fileout.write_line('switch ( sb->getTypeCode() )') self.fileout.write_line('{') self.fileout.up_indent() self.fileout.write_line('case {0}_LIST_OF:'.format(self.cap_language)) self.fileout.up_indent() self.fileout.write_line('name = sb->getElementName();') code = self.create_list_of_block() self.fileout.write_implementation_block(code['code_type'], code['code']) self.fileout.skip_line() self.fileout.write_line('return SWIGTYPE_p_ListOf;') self.fileout.skip_line() self.fileout.down_indent() self.write_element_types() self.fileout.write_line('default:') self.fileout.up_indent() self.fileout.write_line('return SWIGTYPE_p_{0};'.format(self.base)) self.fileout.down_indent() self.fileout.write_line('}') self.fileout.down_indent() self.fileout.write_line('}') self.fileout.skip_line() self.fileout.write_line('#endif // USE_{0}'.format(self.cap_package)) self.fileout.skip_line() # write the local-packages-{}.i for csharp/java def write_binding_specific_i_code(self): self.fileout.skip_line(2) self.fileout.write_line('#ifdef USE_{0}'.format(self.cap_package)) if self.binding == 'csharp': code = 'cscode' public = 'public override' args = 'IntPtr cPtr, bool owner' equals = '.Equals(IntPtr.Zero)' else: code = 'javacode' public = 'public' args = 'long cPtr, boolean owner' equals = ' == 0' self.fileout.write_line('%typemap({0}) {1}' 'Extension'.format(code, self.up_package)) self.fileout.write_line('%{') self.fileout.up_indent() self.write_plugin_downcast(public, args, equals) self.fileout.skip_line() self.write_element_downcast(public, args, equals) self.fileout.down_indent() self.fileout.skip_line() self.fileout.write_line('%}') self.fileout.skip_line() self.write_covariant_clone() self.fileout.skip_line() self.write_covariant_list_of() self.fileout.skip_line() self.write_exception_list() self.fileout.skip_line() self.write_base_classes_cast() self.fileout.skip_line() self.fileout.write_line('#endif // USE_{0}'.format(self.cap_package)) self.fileout.skip_line() # write the local-{}.i for # javascript, perl,python,r,ruby def write_local_file(self): self.fileout.skip_line(2) self.fileout.write_line('#ifdef USE_{0}'.format(self.cap_package)) self.fileout.skip_line() self.write_exception_list() self.fileout.skip_line() self.write_base_classes_cast() self.fileout.skip_line() self.fileout.write_line('#endif // USE_{0}'.format(self.cap_package)) self.fileout.skip_line() ######################################################################### # Function used by write_binding_specific_i_code def write_plugin_downcast(self, public, args, equals): self.fileout.write_line('{0} {1}Plugin Downcast{1}' 'Plugin({2})'.format(public, self.base, args)) self.fileout.write_line('{') self.fileout.up_indent() self.fileout.write_line('if (cPtr{0}) return null;'.format(equals)) self.fileout.skip_line() self.fileout.write_line('{0}Plugin sbp = new {0}Plugin' '(cPtr, false);'.format(self.base)) self.fileout.write_line('{0} sb = sbp.getParent{1}' 'Object();'.format(self.base, self.cap_language)) self.fileout.skip_line() self.fileout.write_line('switch ( sb.getTypeCode() )') self.fileout.write_line('{') self.fileout.up_indent() for plugin in self.plugins: cap_base = plugin['sbase'].upper() up_base = strFunctions.upper_first(plugin['sbase']) self.fileout.write_line('case (int) lib{0}.{1}_' '{2}:'.format(self.language, self.cap_language, cap_base)) self.fileout.up_indent() self.fileout.write_line(' return new {0}{1}Plugin' '(cPtr, owner);'.format(self.up_package, up_base)) self.fileout.down_indent() self.fileout.skip_line() self.fileout.write_line('default:') self.fileout.up_indent() self.fileout.write_line('return new {0}Plugin(cPtr, ' 'owner);'.format(self.base)) self.fileout.down_indent() self.fileout.down_indent() self.fileout.write_line('}') self.fileout.down_indent() self.fileout.write_line('}') def write_element_downcast(self, public, args, equals): string = 'string' if self.binding == 'csharp' else 'String' self.fileout.write_line('{0} {1} Downcast{1}({2})'.format(public, self.base, args)) self.fileout.write_line('{') self.fileout.up_indent() self.fileout.write_line('if (cPtr{0}) return null;'.format(equals)) self.fileout.skip_line() self.fileout.write_line('{0} sb = new {0}(cPtr, ' 'false);'.format(self.base)) self.fileout.write_line('switch ( sb.getTypeCode() )') self.fileout.write_line('{') self.fileout.up_indent() self.fileout.write_line('case (int) lib{0}.{1}_' 'LIST_OF:'.format(self.language, self.cap_language)) self.fileout.up_indent() self.fileout.write_line('{0} name = sb.getElementName();'.format(string)) code = self.create_list_of_block(self.binding) self.fileout.write_implementation_block(code['code_type'], code['code']) self.fileout.skip_line() self.fileout.write_line('return new ListOf(cPtr, owner);') self.fileout.skip_line() self.fileout.down_indent() for element in self.elements: self.fileout.write_line('case (int) lib{0}.' '{1}:'.format(self.language, element['typecode'])) self.fileout.up_indent() self.fileout.write_line(' return new {0}(cPtr, ' 'owner);'.format(element['name'])) self.fileout.down_indent() self.fileout.skip_line() self.fileout.write_line('default:') self.fileout.up_indent() self.fileout.write_line('return new {0}(cPtr, owner);'.format(self.base)) self.fileout.down_indent() self.fileout.down_indent() self.fileout.write_line('}') self.fileout.down_indent() self.fileout.write_line('}') def write_covariant_clone(self): rtype = 'COVARIANT_RTYPE_CLONE' self.write_specific_line(rtype, '{0}Extension'.format(self.up_package)) for element in self.elements: self.write_specific_line(rtype, element['name']) for element in self.elements: if element['hasListOf']: name = strFunctions.list_of_name(element['name']) self.write_specific_line(rtype, name) def write_exception_list(self): rtype = '{0}CONSTRUCTOR_EXCEPTION'.format(self.cap_language) self.write_specific_line(rtype, '{0}Pkg' 'Namespaces'.format(self.up_package)) for element in self.elements: self.write_specific_line(rtype, element['name']) for element in self.elements: if element['hasListOf']: name = strFunctions.list_of_name(element['name']) self.write_specific_line(rtype, name) def write_covariant_list_of(self): rtype = 'COVARIANT_RTYPE_LISTOF_GET_REMOVE' for element in self.elements: if element['hasListOf']: self.write_specific_line(rtype, element['name']) def write_specific_line(self, rtype, ctype): self.fileout.write_line('{0}({1})'.format(rtype, ctype)) def write_base_classes_cast(self): if self.local: my_map = 'out' call = '' elif self.binding == 'csharp': my_map = '\"csout\"' call = '$imcall' else: my_map = '\"javaout\"' call = '$jnicall' for element in self.elements: if element['abstract']: name = element['name'] self.write_cast(name, call, my_map) def write_cast(self, name, call, my_map): if self.local: self.fileout.write_line('/**') self.fileout.write_line_verbatim(' * Convert {0} objects into the ' 'most specific object ' 'possible.'.format(name)) self.fileout.write_line(' */') else: self.fileout.write_line('//') self.fileout.write_line('// Convert {0} objects into the most ' 'specific ' 'object possible.'.format(name)) self.fileout.write_line('//') self.fileout.write_line('%typemap({0}) {1}*'.format(my_map, name)) self.fileout.write_line('{') self.fileout.up_indent() if self.local: self.fileout.write_line('$result = SWIG_NewPointerObj($1, ' 'GetDowncastSwigTypeForPackage($1, ' '\"{0}\"), $owner | ' '%newpointer_flags);'.format(self.package)) else: self.fileout.write_line('return ({0}) lib{1}.Downcast{2}({3}, ' '$owner);'.format(name, self.language, self.base, call)) self.fileout.down_indent() self.fileout.write_line('}') self.fileout.skip_line() ######################################################################## def write_element_types(self): for element in self.elements: self.fileout.write_line('case {0}:'.format(element['typecode'])) self.fileout.up_indent() self.fileout.write_line('return SWIGTYPE_p_' '{0};'.format(element['name'])) self.fileout.down_indent() self.fileout.skip_line() def create_list_of_block(self, b_type=''): line = [] count = 0 for element in self.elements: if element['hasListOf']: count += 1 up_loname = strFunctions.list_of_name(element['name']) loname = strFunctions.lower_first(up_loname) if len(line) > 0: line.append('else if') if b_type == 'java': line.append('name.equals(\"{0}\")'.format(loname)) else: line.append('name == \"{0}\"'.format(loname)) if b_type == 'java' or b_type == 'csharp': line.append('return new {0}(cPtr, owner)'.format(up_loname)) else: line.append('return SWIGTYPE_p_{0}'.format(up_loname)) if count == 0: code = self.create_code_block('blank', []) elif count == 1: code = self.create_code_block('if', line) else: code = self.create_code_block('else_if', line) return code ######################################################################## # Write file def write_file(self): self.fileout.write_file() if self.local: self.write_local_file() elif self.binding == 'csharp' or self.binding == 'java': self.write_binding_specific_i_code() else: self.write_binding_specific_cpp_code() def close_file(self): if self.fileout: self.fileout.close_file() @staticmethod def create_code_block(code_type, lines): code = dict({'code_type': code_type, 'code': lines}) return code
lgpl-2.1
jensv/fluxtubestability
external_stability.py
1
5083
# -*- coding: utf-8 -*- """ Created on Mon Sep 08 20:42:30 2014 @author: Jens von der Linden Calculate dW and determine external stability. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import from future.builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str, super, zip) """Python 3.x compatibility""" import scipy.special as spec from scipy.interpolate import splev import analytic_condition as ac def external_stability(params, xi, xi_der, dim_less=False): r""" Returns external external stability and dW. """ a = params['a'] b_z = splev(a, params['b_z']) b_theta = splev(a, params['b_theta']) m = params['m'] k = params['k'] magnetic_potential_energy_ratio = params['magnetic_potential_energy_ratio'] if params['b'] == 'infinity': lambda_term = lambda_infinity(**{'a': a, 'k': k, 'm': m}) else: assert isinstance(params['b'], float), "b must be 'infinity' or of \ type float." lambda_term = lambda_boundary(**{'a': a, 'b': b, 'k': k, 'm': m}) f_term = capital_f(**{'a': a, 'k': k, 'm': m, 'b_theta': b_theta, 'b_z': b_z}) f_adjoint_term = f_adjoint(**{'a': a, 'k': k, 'm': m, 'b_theta': b_theta, 'b_z': b_z}) k_0_sq_term = k_0(**{'k': k, 'm': m, 'a': a}) term1 = f_term**2*a*xi_der/(k_0_sq_term*xi) term2 = f_term*f_adjoint_term/(k_0_sq_term) term3 = a**2*f_term**2*lambda_term delta_w = (term1+term2*term3)*xi**2 if dim_less: delta_w = magnetic_potential_energy_ratio * delta_w stable = delta_w > 0 return stable, delta_w def lambda_infinity(a, k, m): r""" Return lambda term for wall at infinity. """ k_a = spec.kv(m, abs(k)*a) k_a_prime = spec.kvp(m, abs(k)*a) return -k_a/(abs(k*a)*k_a_prime) def lambda_boundary(a, b, k, m): r""" Return lambda term for wall at radius b. """ k_a = spec.kv(m, abs(k)*a) k_a_prime = spec.kvp(m, abs(k)*a) k_b_prime = spec.kvp(m, abs(k)*b) i_a = spec.iv(m, abs(k)*a) i_a_prime = spec.ivp(m, abs(k)*a) i_b_prime = spec.ivp(m, abs(k)*b) factor1 = -k_a/(abs(k*a)*k_a_prime) factor2_num = 1. - k_b_prime*i_a/(i_b_prime*k_a) factor2_denom = 1. - k_b_prime*i_a_prime/(i_b_prime*k_a_prime) return factor1*factor2_num/factor2_denom def k_0(k, m, a): r""" Return k_0 term. """ return k**2 + m**2 / a**2 def f_adjoint(a, k, m, b_theta, b_z): r""" Return adjoint F. """ return k*b_z - m*b_theta/a def capital_f(a, k, m, b_theta, b_z): r""" Return F. """ return k*b_z + m*b_theta/a def external_stability_from_notes(params, xi, xi_der, dim_less=False): a = params['a'] b_z = splev(a, params['b_z']) b_theta = splev(a, params['b_theta']) m = params['m'] k_bar = params['k'] magnetic_potential_energy_ratio = params['magnetic_potential_energy_ratio'] term_params = {'a': a, 'k_bar': k_bar, 'm': m, 'b_z': b_z, 'b_theta': b_theta, 'xi': xi, 'xi_der': xi_der} delta_w = (plasma_term_from_notes(**term_params) - vacuum_term_from_notes(**term_params)) if dim_less: delta_w = magnetic_potential_energy_ratio * delta_w stable = delta_w > 0 return stable, delta_w def plasma_term_from_notes(a, k_bar, m, b_z, b_theta, xi, xi_der): r""" Returns plasma energy term as in my derivation. """ f_term = a*(k_bar*b_z + m*b_theta)**2/(k_bar**2 + m**2) h_term = (k_bar**2*b_z**2 - m**2*b_theta**2)/(k_bar**2 + m**2) return xi**2 * (f_term*xi_der / xi + h_term) def vacuum_term_from_notes(a, k_bar, m, b_z, b_theta, xi, xi_der): r""" Returns vacuum energy term as in my derivation. """ k_a = spec.kv(m, abs(k_bar)) k_a_prime = spec.kvp(m, abs(k_bar)) term1 = (k_bar*b_z + m*b_theta)**2 term2 = xi**2/k_bar*k_a/k_a_prime return term1*term2 def external_stability_from_analytic_condition(params, xi, xi_der, without_sing=True, dim_less=False): r""" Returns delta_w as given in the analytic condition. Optionally remove singularity by mutiplying by xi^2. Note ---- When xi goes to zero, this condition is singular due to the delta=xi'/xi term. """ a = params['a'] b_z = splev(a, params['b_z']) b_theta_vacuum = splev(a, params['b_theta']) m = -params['m'] k_bar = params['k'] lambda_bar = 2*b_theta_vacuum / (b_z*a) delta = xi_der*a / xi if without_sing: dW = ac.conditions_without_interface_wo_sing(k_bar, lambda_bar, m, xi, xi_der, a) else: dW = ac.conditions_without_interface(k_bar, lambda_bar, m, delta) stable = dW > 0 return stable, dW
mit
JKRP/geonode
geonode/contrib/slack/enumerations.py
22
6907
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2012 OpenPlans # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### SLACK_MESSAGE_TEMPLATES = { "layer_new": { "attachments": [{ "title": "{title}", "title_link": "{url_detail}", "fallback": "A new {type} {title} has been added to {sitename} by {owner_name}. {url_detail}", "text": "A new {type} <{url_detail}|{title}> has been added to " "<{baseurl}|{sitename}> by <{owner_url}|{owner_name}>.", "thumb_url": "{thumbnail_url}", "fields": [{ "title": "Zipped Shapefile", "value": "<{url_shp}|Download>", "short": True }, { "title": "GeoJSON", "value": "<{url_geojson}|Download>", "short": True }, { "title": "View in Google Earth", "value": "<{url_netkml}|Download>", "short": True }, { "title": "View on Map", "value": "<{url_map}|View>", "short": True }], "color": "#000099" }] }, "layer_edit": { "attachments": [{ "title": "{title}", "title_link": "{url_detail}", "fallback": "The {type} {title} has been modified on {sitename} by {owner_name}. {url_detail}", "text": "The {type} <{url_detail}|{title}> has been modified on " "<{baseurl}|{sitename}> by <{owner_url}|{owner_name}>.", "thumb_url": "{thumbnail_url}", "fields": [{ "title": "Zipped Shapefile", "value": "<{url_shp}|Download>", "short": True }, { "title": "GeoJSON", "value": "<{url_geojson}|Download>", "short": True }, { "title": "View in Google Earth", "value": "<{url_netkml}|Download>", "short": True }, { "title": "View on Map", "value": "<{url_map}|View>", "short": True }], "color": "#000099" }] }, "layer_delete": { "attachments": [{ "title": "{title}", "fallback": "The {type} {title} has been deleted from {sitename}. {baseurl}", "text": "The {type} {title} has been deleted from <{baseurl}|{sitename}>.", "color": "#FF0000" }] }, "map_new": { "attachments": [{ "title": "{title}", "title_link": "{url_detail}", "fallback": "A new {type} {title} has been added to {sitename} by {owner_name}. {url_detail}", "text": "A new {type} <{url_detail}|{title}> has been added to " "<{baseurl}|{sitename}> by <{owner_url}|{owner_name}>.", "thumb_url": "{thumbnail_url}", "fields": [{ "title": "View Map", "value": "<{url_view}|View>", "short": True }, { "title": "Download Map", "value": "<{url_download}|Download>", "short": True }], "color": "#000099" }] }, "map_edit": { "attachments": [{ "title": "{title}", "title_link": "{url_detail}", "fallback": "The {type} {title} has been modified on {sitename} by {owner_name}. {url_detail}", "text": "The {type} <{url_detail}|{title}> has been modified on " "<{baseurl}|{sitename}> by <{owner_url}|{owner_name}>.", "thumb_url": "{thumbnail_url}", "fields": [{ "title": "View Map", "value": "<{url_view}|View>", "short": True }, { "title": "Download Map", "value": "<{url_download}|Download>", "short": True }], "color": "#000099" }] }, "map_delete": { "attachments": [{ "title": "{title}", "fallback": "The {type} {title} has been deleted from {sitename}. {baseurl}", "text": "The {type} {title} has been deleted from <{baseurl}|{sitename}>.", "color": "#FF0000" }] }, "document_new": { "attachments": [{ "title": "{title}", "title_link": "{url_detail}", "fallback": "A new {type} {title} has been added to {sitename} by {owner_name}. {url_detail}", "text": "A new {type} <{url_detail}|{title}> has been added to " "<{baseurl}|{sitename}> by <{owner_url}|{owner_name}>.", "thumb_url": "{thumbnail_url}", "fields": [{ "title": "Download Document", "value": "<{url_download}|Download>", "short": True }], "color": "#000099" }] }, "document_edit": { "attachments": [{ "title": "{title}", "title_link": "{url_detail}", "fallback": "The {type} {title} has been modified on {sitename} by {owner_name}. {url_detail}", "text": "The {type} <{url_detail}|{title}> has been modified on " "<{baseurl}|{sitename}> by <{owner_url}|{owner_name}>.", "thumb_url": "{thumbnail_url}", "fields": [{ "title": "Download Document", "value": "<{url_download}|Download>", "short": True }], "color": "#000099" }] }, "document_delete": { "attachments": [{ "title": "{title}", "fallback": "The {type} {title} has been deleted from {sitename}. {baseurl}", "text": "The {type} {title} has been deleted from <{baseurl}|{sitename}>.", "color": "#FF0000" }] } }
gpl-3.0
mbernasocchi/inasafe
safe/gui/tools/wizard/step_fc70_extent.py
8
5051
# coding=utf-8 """InaSAFE Wizard Step Extent Selection.""" import logging from safe import messaging as m from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog from safe.gui.tools.help.extent_selector_help import extent_mode_content from safe.gui.tools.wizard.wizard_step import WizardStep from safe.gui.tools.wizard.wizard_step import get_wizard_step_ui_class from safe.utilities.i18n import tr __copyright__ = "Copyright 2016, The InaSAFE Project" __license__ = "GPL version 3" __email__ = "info@inasafe.org" __revision__ = '$Format:%H$' FORM_CLASS = get_wizard_step_ui_class(__file__) LOGGER = logging.getLogger('InaSAFE') class StepFcExtent(WizardStep, FORM_CLASS): """InaSAFE Wizard Step Extent Selection.""" def __init__(self, parent=None): """Constructor for the tab. :param parent: parent - widget to use as parent (Wizard Dialog). :type parent: QWidget """ WizardStep.__init__(self, parent) self.swExtent = None self.extent_dialog = None def is_ready_to_next_step(self): """Check if the step is complete. If so, there is no reason to block the Next button. :returns: True if new step may be enabled. :rtype: bool """ return True def get_next_step(self): """Find the proper step when user clicks the Next button. :returns: The step to be switched to. :rtype: WizardStep instance or None """ if self.validate_extent(): new_step = self.parent.step_fc_summary else: new_step = self.parent.step_fc_extent_disjoint return new_step def validate_extent(self): """Check if the selected extent intersects source data. :returns: true if extent intersects both layers, false if is disjoint. :rtype: boolean """ # TODO: Until we define have good extent behavior, always return True return True def start_capture_coordinates(self): """Enter the coordinate capture mode.""" self.parent.hide() def stop_capture_coordinates(self): """Exit the coordinate capture mode.""" self.extent_dialog._populate_coordinates() self.extent_dialog.canvas.setMapTool( self.extent_dialog.previous_map_tool) self.parent.show() def write_extent(self): """After the extent selection, save the extent and disconnect signals. """ self.extent_dialog.accept() self.extent_dialog.clear_extent.disconnect( self.parent.dock.extent.clear_user_analysis_extent) self.extent_dialog.extent_defined.disconnect( self.parent.dock.define_user_analysis_extent) self.extent_dialog.capture_button.clicked.disconnect( self.start_capture_coordinates) self.extent_dialog.tool.rectangle_created.disconnect( self.stop_capture_coordinates) def set_widgets(self): """Set widgets on the Extent tab.""" self.extent_dialog = ExtentSelectorDialog( self.parent.iface, self.parent.iface.mainWindow(), extent=self.parent.dock.extent.user_extent, crs=self.parent.dock.extent.crs) self.extent_dialog.tool.rectangle_created.disconnect( self.extent_dialog.stop_capture) self.extent_dialog.clear_extent.connect( self.parent.dock.extent.clear_user_analysis_extent) self.extent_dialog.extent_defined.connect( self.parent.dock.define_user_analysis_extent) self.extent_dialog.capture_button.clicked.connect( self.start_capture_coordinates) self.extent_dialog.tool.rectangle_created.connect( self.stop_capture_coordinates) self.extent_dialog.label.setText(tr( 'Please specify extent of your analysis:')) if self.swExtent: self.swExtent.hide() self.swExtent = self.extent_dialog.main_stacked_widget self.layoutAnalysisExtent.addWidget(self.swExtent) @property def step_name(self): """Get the human friendly name for the wizard step. :returns: The name of the wizard step. :rtype: str """ # noinspection SqlDialectInspection,SqlNoDataSourceInspection return tr('Extent Selection') def help_content(self): """Return the content of help for this step wizard. We only needs to re-implement this method in each wizard step. :returns: A message object contains help. :rtype: m.Message """ message = m.Message() message.add(m.Paragraph(tr( 'In this wizard step: {step_name} you will be allowed to specify ' 'which geographical region should be used for your analysis. ' 'There are a number of different modes that can be used which are ' 'described below:' ).format(step_name=self.step_name))) message.add(extent_mode_content()) return message
gpl-3.0
ryfeus/lambda-packs
LightGBM_sklearn_scipy_numpy/source/setuptools/__init__.py
49
5700
"""Extensions to the 'distutils' for large or complex distributions""" import os import functools import distutils.core import distutils.filelist from distutils.util import convert_path from fnmatch import fnmatchcase from setuptools.extern.six.moves import filter, map import setuptools.version from setuptools.extension import Extension from setuptools.dist import Distribution, Feature from setuptools.depends import Require from . import monkey __all__ = [ 'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require', 'find_packages', ] __version__ = setuptools.version.__version__ bootstrap_install_from = None # If we run 2to3 on .py files, should we also convert docstrings? # Default: yes; assume that we can detect doctests reliably run_2to3_on_doctests = True # Standard package names for fixer packages lib2to3_fixer_packages = ['lib2to3.fixes'] class PackageFinder(object): """ Generate a list of all Python packages found within a directory """ @classmethod def find(cls, where='.', exclude=(), include=('*',)): """Return a list all Python packages found within directory 'where' 'where' is the root directory which will be searched for packages. It should be supplied as a "cross-platform" (i.e. URL-style) path; it will be converted to the appropriate local path syntax. 'exclude' is a sequence of package names to exclude; '*' can be used as a wildcard in the names, such that 'foo.*' will exclude all subpackages of 'foo' (but not 'foo' itself). 'include' is a sequence of package names to include. If it's specified, only the named packages will be included. If it's not specified, all found packages will be included. 'include' can contain shell style wildcard patterns just like 'exclude'. """ return list(cls._find_packages_iter( convert_path(where), cls._build_filter('ez_setup', '*__pycache__', *exclude), cls._build_filter(*include))) @classmethod def _find_packages_iter(cls, where, exclude, include): """ All the packages found in 'where' that pass the 'include' filter, but not the 'exclude' filter. """ for root, dirs, files in os.walk(where, followlinks=True): # Copy dirs to iterate over it, then empty dirs. all_dirs = dirs[:] dirs[:] = [] for dir in all_dirs: full_path = os.path.join(root, dir) rel_path = os.path.relpath(full_path, where) package = rel_path.replace(os.path.sep, '.') # Skip directory trees that are not valid packages if ('.' in dir or not cls._looks_like_package(full_path)): continue # Should this package be included? if include(package) and not exclude(package): yield package # Keep searching subdirectories, as there may be more packages # down there, even if the parent was excluded. dirs.append(dir) @staticmethod def _looks_like_package(path): """Does a directory look like a package?""" return os.path.isfile(os.path.join(path, '__init__.py')) @staticmethod def _build_filter(*patterns): """ Given a list of patterns, return a callable that will be true only if the input matches at least one of the patterns. """ return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns) class PEP420PackageFinder(PackageFinder): @staticmethod def _looks_like_package(path): return True find_packages = PackageFinder.find def _install_setup_requires(attrs): # Note: do not use `setuptools.Distribution` directly, as # our PEP 517 backend patch `distutils.core.Distribution`. dist = distutils.core.Distribution(dict( (k, v) for k, v in attrs.items() if k in ('dependency_links', 'setup_requires') )) # Honor setup.cfg's options. dist.parse_config_files(ignore_option_errors=True) if dist.setup_requires: dist.fetch_build_eggs(dist.setup_requires) def setup(**attrs): # Make sure we have any requirements needed to interpret 'attrs'. _install_setup_requires(attrs) return distutils.core.setup(**attrs) setup.__doc__ = distutils.core.setup.__doc__ _Command = monkey.get_unpatched(distutils.core.Command) class Command(_Command): __doc__ = _Command.__doc__ command_consumes_arguments = False def __init__(self, dist, **kw): """ Construct the command for dist, updating vars(self) with any keyword parameters. """ _Command.__init__(self, dist) vars(self).update(kw) def reinitialize_command(self, command, reinit_subcommands=0, **kw): cmd = _Command.reinitialize_command(self, command, reinit_subcommands) vars(cmd).update(kw) return cmd def _find_all_simple(path): """ Find all files under 'path' """ results = ( os.path.join(base, file) for base, dirs, files in os.walk(path, followlinks=True) for file in files ) return filter(os.path.isfile, results) def findall(dir=os.curdir): """ Find all files under 'dir' and return the list of full filenames. Unless dir is '.', return full filenames with dir prepended. """ files = _find_all_simple(dir) if dir == os.curdir: make_rel = functools.partial(os.path.relpath, start=dir) files = map(make_rel, files) return list(files) monkey.patch_all()
mit
marcosbontempo/algar
workspace/pcef/diameter/libDiameter.py
1
28177
#!/usr/bin/env python ################################################################## # Copyright (c) 2012, Sergej Srepfler <sergej.srepfler@gmail.com> # February 2012 - Nov 2012 # Version 0.3.1, Last change on Nov 17, 2012 # This software is distributed under the terms of BSD license. ################################################################## # All functions needed to build/decode diameter messages import xml.dom.minidom as minidom import struct import codecs import socket import sys import logging import time # Diameter Header fields DIAMETER_FLAG_MANDATORY = 0x40 DIAMETER_FLAG_VENDOR = 0x80 DIAMETER_HDR_REQUEST = 0x80 DIAMETER_HDR_PROXIABLE = 0x40 DIAMETER_HDR_ERROR = 0x20 DIAMETER_HDR_RETRANSMIT = 0x10 # Include common routines for all modules ERROR = -1 # Hopefully let's keep dictionary definition compatibile class AVPItem: def __init__(self): self.code=0 self.name="" self.vendor=0 self.type="" self.mandatory="" class HDRItem: def __init__(self): self.ver=0 self.flags=0 self.len=0 self.cmd=0 self.appId=0 self.HobByHop=0 self.EndToEnd=0 self.msg="" #---------------------------------------------------------------------- utf8encoder=codecs.getencoder("utf_8") utf8decoder=codecs.getdecoder("utf_8") #---------------------------------------------------------------------- # Dictionary routines # Load simplified dictionary from <file> def LoadDictionary(file): global dict_avps global dict_vendors global dict_commands global asString global asUTF8 global asU32 global asI32 global asU64 global asI64 global asF32 global asF64 global asIPAddress global asIP global asTime doc = minidom.parse(file) node = doc.documentElement dict_avps = doc.getElementsByTagName("avp") dict_vendors = doc.getElementsByTagName("vendor") dict_commands=doc.getElementsByTagName("command") # Now lets process typedefs asString=["OctetString"] asUTF8=["UTF8String"] asI32=["Integer32"] asU32=["Unsigned32"] asF32=["Float32"] asI64=["Integer64"] asU64=["Unsigned64"] asF64=["Float64"] asIPAddress=["IPAddress"] asIP=["IP"] asTime=["Time"] dict_typedefs=doc.getElementsByTagName("typedef") for td in dict_typedefs: tName=td.getAttribute("name") tType=td.getAttribute("type") if tType in asString: asString.append(tName) if tType in asUTF8: asUTF8.append(tName) if tType in asU32: asU32.append(tName) if tType in asI32: asI32.append(tName) if tType in asI64: asI64.append(tName) if tType in asU64: asU64.append(tName) if tType in asF32: asF32.append(tName) if tType in asF64: asF64.append(tName) if tType in asIPAddress: asIPAddress.append(tName) if tType in asIP: asIP.append(tName) if tType in asTime: asTime.append(tName) # Find AVP definition in dictionary: User-Name->1 # on finish A contains all data def dictAVPname2code(A,avpname,avpvalue): global dict_avps dbg="Searching dictionary for N",avpname,"V",avpvalue logging.debug(dbg) for avp in dict_avps: A.name = avp.getAttribute("name") A.code = avp.getAttribute("code") A.mandatory=avp.getAttribute("mandatory") A.type = avp.getAttribute("type") vId = avp.getAttribute("vendor-id") if avpname==A.name: if vId=="": A.vendor=0 else: A.vendor=dictVENDORid2code(vId) return dbg="Searching dictionary failed for N",avpname,"V",avpvalue bailOut(dbg) # Find AVP definition in dictionary: 1->User-Name # on finish A contains all data def dictAVPcode2name(A,avpcode,vendorcode): global dict_avps dbg="Searching dictionary for ","C",avpcode,"V",vendorcode logging.debug(dbg) A.vendor=dictVENDORcode2id(int(vendorcode)) for avp in dict_avps: A.name = avp.getAttribute("name") A.type = avp.getAttribute("type") A.code = int(avp.getAttribute("code")) A.mandatory=avp.getAttribute("mandatory") vId = avp.getAttribute("vendor-id") if int(avpcode)==A.code: if vId=="": vId="None" if vId==A.vendor: return logging.info("Unsuccessful search") A.code=avpcode A.name="Unknown Attr-"+str(A.code)+" (Vendor:"+A.vendor+")" A.type="OctetString" return # Find Vendor definition in dictionary: 10415->TGPP def dictVENDORcode2id(code): global dict_vendors dbg="Searching Vendor dictionary for C",code logging.debug(dbg) for vendor in dict_vendors: vCode=vendor.getAttribute("code") vId=vendor.getAttribute("vendor-id") if code==int(vCode): return vId dbg="Searching Vendor dictionary failed for C",code bailOut(dbg) # Find Vendor definition in dictionary: TGPP->10415 def dictVENDORid2code(vendor_id): global dict_vendors dbg="Searching Vendor dictionary for V",vendor_id logging.debug(dbg) for vendor in dict_vendors: Code=vendor.getAttribute("code") vId=vendor.getAttribute("vendor-id") if vendor_id==vId: return int(Code) dbg="Searching Vendor dictionary failed for V",vendor_id bailOut(dbg) # Find Command definition in dictionary: Capabilities-Exchange->257 def dictCOMMANDname2code(name): global dict_commands for command in dict_commands: cName=command.getAttribute("name") cCode=command.getAttribute("code") if cName==name: return int(cCode) dbg="Searching CMD dictionary failed for N",name bailOut(dbg) # Find Command definition in dictionary: 257->Capabilities-Exchange def dictCOMMANDcode2name(flags,code): global dict_commands cmd=ERROR for command in dict_commands: cName=command.getAttribute("name") cCode=command.getAttribute("code") if code==int(cCode): cmd=cName if cmd==ERROR: return cmd if flags&DIAMETER_HDR_REQUEST==DIAMETER_HDR_REQUEST: dbg=cmd+" Request" else: dbg=cmd+" Answer" return dbg #---------------------------------------------------------------------- # These are defined on Unix python.socket, but not on Windows # Pack/Unpack IP address def inet_pton(address_family, ip_string): #Convert an IP address from text represenation to binary form if address_family == socket.AF_INET: return socket.inet_aton(ip_string) elif address_family == socket.AF_INET6: # IPv6: The use of "::" indicates one or more groups of 16 bits of zeros. # We deal with this form of wildcard using a special marker. JOKER = "*" while "::" in ip_string: ip_string = ip_string.replace("::", ":" + JOKER + ":") joker_pos = None # The last part of an IPv6 address can be an IPv4 address ipv4_addr = None if "." in ip_string: ipv4_addr = ip_string.split(":")[-1] result = "" parts = ip_string.split(":") for part in parts: if part == JOKER: # Wildcard is only allowed once if joker_pos is None: joker_pos = len(result) else: bailOut("Illegal syntax for IP address") elif part == ipv4_addr: # FIXME: Make sure IPv4 can only be last part # FIXME: inet_aton allows IPv4 addresses with less than 4 octets result += socket.inet_aton(ipv4_addr) else: # Each part must be 16bit. Add missing zeroes before decoding. try: result += part.rjust(4, "0").decode("hex") except TypeError: bailOut("Illegal syntax for IP address") # If there's a wildcard, fill up with zeros to reach 128bit (16 bytes) if JOKER in ip_string: result = (result[:joker_pos] + "\x00" * (16 - len(result)) + result[joker_pos:]) if len(result) != 16: bailOut("Illegal syntax for IP address") return result else: bailOut("Address family not supported") def inet_ntop(address_family, packed_ip): #Convert an IP address from binary form into text represenation if address_family == socket.AF_INET: return socket.inet_ntoa(packed_ip) elif address_family == socket.AF_INET6: # IPv6 addresses have 128bits (16 bytes) if len(packed_ip) != 16: bailOut("Illegal syntax for IP address") parts = [] for left in [0, 2, 4, 6, 8, 10, 12, 14]: try: value = struct.unpack("!H", packed_ip[left:left+2])[0] hexstr = hex(value)[2:] except TypeError: bailOut("Illegal syntax for IP address") parts.append(hexstr.lstrip("0").lower()) result = ":".join(parts) while ":::" in result: result = result.replace(":::", "::") # Leaving out leading and trailing zeros is only allowed with :: if result.endswith(":") and not result.endswith("::"): result = result + "0" if result.startswith(":") and not result.startswith("::"): result = "0" + result return result else: bailOut("Address family not supported yet") #Pack IP address def pack_address(address): # This has issue on Windows platform # addrs=socket.getaddrinfo(address, None) # This is NOT a proper code, but it will do for now # unfortunately, getaddrinfo does not work on windows with IPv6 if address.find('.')!=ERROR: raw = inet_pton(socket.AF_INET,address); d=struct.pack('!h4s',1,raw) return d if address.find(':')!=ERROR: raw = inet_pton(socket.AF_INET6,address); d=struct.pack('!h16s',2,raw) return d dbg='Malformed IP' bailOut(dbg) #---------------------------------------------------------------------- # # Decoding section # def decode_Integer32(data): ret=struct.unpack("!I",data.decode("hex"))[0] return int(ret) def decode_Integer64(data): ret=struct.unpack("!Q",data.decode("hex"))[0] return int(ret) def decode_Unsigned32(data): ret=struct.unpack("!I",data.decode("hex"))[0] return int(ret) def decode_Unsigned64(data): ret=struct.unpack("!Q",data.decode("hex"))[0] return int(ret) def decode_Float32(data): ret=struct.unpack("!f",data.decode("hex"))[0] return ret def decode_Float64(data): ret=struct.unpack("!d",data.decode("hex"))[0] return ret def decode_Address(data): if len(data)<=16: data=data[4:12] ret=inet_ntop(socket.AF_INET,data.decode("hex")) else: data=data[4:36] ret=inet_ntop(socket.AF_INET6,data.decode("hex")) return ret def decode_IP(data): if len(data)<=16: ret=inet_ntop(socket.AF_INET,data.decode("hex")) else: ret=inet_ntop(socket.AF_INET6,data.decode("hex")) return ret def decode_OctetString(data,dlen): fs="!"+str(dlen-8)+"s" dbg="Deconding String with format:",fs logging.debug(dbg) ret=struct.unpack(fs,data.decode("hex")[0:dlen-8])[0] return ret #Hex Comments #0x00..0x7F Only byte of a 1-byte character encoding #0x80..0xBF Continuation characters (1-3 continuation characters) #0xC0..0xDF First byte of a 2-byte character encoding #0xE0..0xEF First byte of a 3-byte character encoding #0xF0..0xF4 First byte of a 4-byte character encoding #Note:0xF5-0xFF cannot occur def decode_UTF8String(data,dlen): fs="!"+str(dlen-8)+"s" dbg="Decoding UTF8 format:",fs logging.debug(dbg) ret=struct.unpack(fs,data.decode("hex")[0:dlen-8])[0] utf8=utf8decoder(ret) return utf8[0] def decode_Grouped(data): dbg="Decoding Grouped:" ret=[] for gmsg in splitMsgAVPs(data): ret.append(decodeAVP(gmsg)) return ret #AVP_Time contains a second count since 1900 def decode_Time(data): seconds_between_1900_and_1970 = ((70*365)+17)*86400 ret=struct.unpack("!I",data.decode("hex"))[0] return int(ret)-seconds_between_1900_and_1970 #---------------------------------------------------------------------- # Quit program with error def bailOut(msg): logging.error(msg) sys.exit(1) #Split message into parts (remove field from remaining body) def chop_msg(msg,size): return (msg[0:size],msg[size:]) #---------------------------------------------------------------------- # 0 1 2 3 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | AVP Code | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # |V M P r r r r r| AVP Length | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | Vendor-ID (opt) | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | Data ... # +-+-+-+-+-+-+-+-+ # Common finish routine for all encoded AVPs # Result is properly encoded AVP as hex string (padding is added separately) def encode_finish(A,flags,pktlen,data): ret=data if A.vendor!=0: ret=("%08X" % int(A.vendor)) + ret flags|=DIAMETER_FLAG_VENDOR pktlen+=4 dbg="Packing","C:",A.code,"F:",flags,"V:",A.vendor,"L:",pktlen,"D:",ret logging.debug(dbg) ret=("%08X"%int(A.code))+("%02X"%int(flags))+("%06X"%pktlen)+ret return ret def encode_OctetString(A,flags,data): fs="!"+str(len(data))+"s" dbg="Encoding String format:",fs logging.debug(dbg) ret=struct.pack(fs,data).encode("hex") pktlen=8+len(ret)/2 return encode_finish(A,flags,pktlen,ret) def encode_UTF8String(A,flags,data): utf8data=utf8encoder(data)[0] fs="!"+str(len(utf8data))+"s" dbg="Encoding UTF8",utf8data,"L",len(utf8data),"F",fs logging.debug(dbg) ret=struct.pack(fs,utf8data).encode("hex") pktlen=8+len(ret)/2 return encode_finish(A,flags,pktlen,ret) def encode_Integer32(A,flags,data): r=struct.pack("!I",data) ret=r.encode("hex") pktlen=12 return encode_finish(A,flags,pktlen,ret) def encode_Unsigned32(A,flags,data): r=struct.pack("!I",int(data)) ret=r.encode("hex") pktlen=12 return encode_finish(A,flags,pktlen,ret) def encode_Float32(A,flags,data): ret=struct.pack("!f",data).encode("hex") pktlen=12 return encode_finish(A,flags,pktlen,ret) def encode_Integer64(A,flags,data): ret=struct.pack("!Q",data).encode("hex") pktlen=16 return encode_finish(A,flags,pktlen,ret) def encode_Unsigned64(A,flags,data): ret=struct.pack("!Q",data).encode("hex") pktlen=16 return encode_finish(A,flags,pktlen,ret) def encode_Float64(A,flags,data): ret=struct.pack("!d",data).encode("hex") pktlen=16 return encode_finish(A,flags,pktlen,ret) def encode_Address(A,flags,data): ret=pack_address(data).encode("hex") pktlen=8+len(ret)/2 return encode_finish(A,flags,pktlen,ret) def encode_IP(A,flags,data): ret=pack_address(data).encode("hex")[4:] pktlen=8+len(ret)/2 return encode_finish(A,flags,pktlen,ret) def encode_Enumerated(A,flags,data): global dict_avps if isinstance(data,str): # Replace with enum code value for avp in dict_avps: Name = avp.getAttribute("name") if Name==A.name: for e in avp.getElementsByTagName("enum"): if data==e.getAttribute("name"): return encode_Integer32(A,flags,int(e.getAttribute("code"))) dbg="Enum name=",data,"not found for AVP",A.name bailOut(dbg) else: return encode_Integer32(A,flags,data) #AVP_Time contains a second count since 1900 #But unix counts time from EPOCH (1.1.1970) def encode_Time(A,flags,data): seconds_between_1900_and_1970 = ((70*365)+17)*86400 r=struct.pack("!I",data+seconds_between_1900_and_1970) ret=r.encode("hex") pktlen=12 return encode_finish(A,flags,pktlen,ret) #---------------------------------------------------------------------- #Set mandatory flag as specified in dictionary def checkMandatory(mandatory): flags=0 if mandatory=="must": flags|=DIAMETER_FLAG_MANDATORY return flags def do_encode(A,flags,data): if A.type in asUTF8: return encode_UTF8String(A,flags,data) if A.type in asI32: return encode_Integer32(A,flags,data) if A.type in asU32: return encode_Unsigned32(A,flags,data) if A.type in asI64: return encode_Integer64(A,flags,data) if A.type in asU64: return encode_Unsigned64(A,flags,data) if A.type in asF32: return encode_Float32(A,flags,data) if A.type in asF64: return encode_Float64(A,flags,data) if A.type in asIPAddress: return encode_Address(A,flags,data) if A.type in asIP: return encode_IP(A,flags,data) if A.type in asTime: return encode_Time(A,flags,data) if A.type=="Enumerated": return encode_Enumerated(A,flags,data) # default is OctetString return encode_OctetString(A,flags,data) # Find AVP Definition in dictionary and encode it def getAVPDef(AVP_Name,AVP_Value): A=AVPItem() dictAVPname2code(A,AVP_Name,AVP_Value) if A.name=="": logging.error("AVP with that name not found") return "" if A.code==0: logging.error("AVP Code not found") return "" if A.type=="": logging.error("AVP type not defined") return "" if A.vendor<0: logging.error("Vendor ID does not match") return "" else: data=AVP_Value dbg="AVP dictionary def","N",A.name,"C",A.code,"M",A.mandatory,"T",A.type,"V",A.vendor,"D",data logging.debug(dbg) flags=checkMandatory(A.mandatory) return do_encode(A,flags,data) ################################ # Main encoding routine def encodeAVP(AVP_Name,AVP_Value): if type(AVP_Value).__name__=='list': p='' for x in AVP_Value: while len(x)/2<calc_padding(len(x)/2): x=x+'00' p=p+x msg=getAVPDef(AVP_Name,p.decode("hex")) else: msg=getAVPDef(AVP_Name,AVP_Value) dbg="AVP",AVP_Name,AVP_Value,"Encoded as:",msg logging.info(dbg) return msg # Calculate message padding def calc_padding(msg_len): return (msg_len+3)&~3 #---------------------------------------------------------------------- ################################ # Main decoding routine # Input: single AVP as HEX string def decodeAVP(msg): (scode,msg)=chop_msg(msg,8) (sflag,msg)=chop_msg(msg,2) (slen,msg)=chop_msg(msg,6) dbg="Decoding ","C",scode,"F",sflag,"L",slen,"D",msg logging.debug(dbg) mcode=struct.unpack("!I",scode.decode("hex"))[0] mflags=ord(sflag.decode("hex")) data_len=struct.unpack("!I","\00"+slen.decode("hex"))[0] mvid=0 if mflags & DIAMETER_FLAG_VENDOR: (svid,msg)=chop_msg(msg,8) mvid=struct.unpack("!I",svid.decode("hex"))[0] data_len-=4 A=AVPItem() dictAVPcode2name(A,mcode,mvid) dbg="Read","N",A.name,"T",A.type,"C",A.code,"F",mflags,"L",data_len,"V",A.vendor,mvid,"D",msg logging.debug(dbg) ret="" decoded=False if A.type in asI32: logging.debug("Decoding Integer32") ret= decode_Integer32(msg) decoded=True if A.type in asI64: decoded=True logging.debug("Decoding Integer64") ret= decode_Integer64(msg) if A.type in asU32: decoded=True logging.debug("Decoding Unsigned32") ret= decode_Unsigned32(msg) if A.type in asU64: decoded=True logging.debug("Decoding Unsigned64") ret= decode_Unsigned64(msg) if A.type in asF32: decoded=True logging.debug("Decoding Float32") ret= decode_Float32(msg) if A.type in asF64: decoded=True logging.debug("Decoding Float64") ret= decode_Float64(msg) if A.type in asUTF8: decoded=True logging.debug("Decoding UTF8String") ret= decode_UTF8String(msg,data_len) if A.type in asIPAddress: decoded=True logging.debug("Decoding IPAddress") ret= decode_Address(msg) if A.type in asIP: decoded=True logging.debug("Decoding IP") ret= decode_IP(msg) if A.type in asTime: decoded=True logging.debug("Decoding Time") ret= decode_Time(msg) if A.type=="Grouped": decoded=True logging.debug("Decoding Grouped") ret= decode_Grouped(msg) if not decoded: # default is OctetString logging.debug("Decoding OctetString") ret= decode_OctetString(msg,data_len) dbg="Decoded as",A.name,ret logging.info(dbg) return (A.name,ret) # Search for AVP in undecoded list # Return value if exist, ERROR if not def findAVP(what,list): for avp in list: if isinstance(avp,tuple): (Name,Value)=avp else: (Name,Value)=decodeAVP(avp) if Name==what: return Value return ERROR #---------------------------------------------------------------------- # 0 1 2 3 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | Version | Message Length | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | command flags | Command-Code | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | Application-ID | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | Hop-by-Hop Identifier | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | End-to-End Identifier | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | AVPs ... # +-+-+-+-+-+-+-+-+-+-+-+-+- # Join AVPs (add padding) def joinAVPs(avps): data="" for avp in avps: while len(avp)/2<calc_padding(len(avp)/2): avp=avp+"00" data=data+avp return data # Set flags to desired state def setFlags(H,flag): H.flags|=flag return # Create diameter Request from <avps> and fields from Header H def createReq(H,avps): H.flags|=DIAMETER_HDR_REQUEST return createRes(H,avps) # Create diameter Response from <avps> and fields from Header H def createRes(H,avps): # first add all avps into single string data=joinAVPs(avps) # since all data is hex ecoded, divide by 2 and add header length H.len=len(data)/2+20 ret="01"+"%06X" % H.len+"%02X"%int(H.flags) + "%06X"%int(H.cmd) ret=ret+"%08X"%H.appId+"%08X"%H.HopByHop+ "%08X"%H.EndToEnd+data dbg="Header fields","L",H.len,"F",H.flags,"C",H.cmd,"A",H.appId,"H",H.HopByHop,"E",H.EndToEnd logging.debug(dbg) dbg="Diameter hdr+data",ret logging.debug(dbg) return ret # Set Hop-by-Hop and End-to-End fields to sane values def initializeHops(H): # Not by RFC, but close enough try: initializeHops.Hop_by_Hop+=1 initializeHops.End_to_End+=1 except: initializeHops.Hop_by_Hop=int(time.time()) initializeHops.End_to_End=(initializeHops.Hop_by_Hop%32768)*32768 H.HopByHop=initializeHops.Hop_by_Hop H.EndToEnd=initializeHops.End_to_End return #---------------------------------------------------------------------- # Main message decoding routine # Input: diameter message as HEX string # Result: class H with splitted message (header+message) # AVPs in message are NOT splitted def stripHdr(H,msg): dbg="Incoming Diameter msg",msg logging.info(dbg) if len(msg)==0: return ERROR (sver,msg)=chop_msg(msg,2) (slen,msg)=chop_msg(msg,6) (sflag,msg)=chop_msg(msg,2) (scode,msg)=chop_msg(msg,6) (sapp,msg)=chop_msg(msg,8) (shbh,msg)=chop_msg(msg,8) (sete,msg)=chop_msg(msg,8) dbg="Split hdr","V",sver,"L",slen,"F",sflag,"C",scode,"A",sapp,"H",shbh,"E",sete,"D",msg logging.debug(dbg) H.ver=ord(sver.decode("hex")) H.flags=ord(sflag.decode("hex")) H.len=struct.unpack("!I","\00"+slen.decode("hex"))[0] H.cmd=struct.unpack("!I","\00"+scode.decode("hex"))[0] H.appId=struct.unpack("!I",sapp.decode("hex"))[0] H.HopByHop=struct.unpack("!I",shbh.decode("hex"))[0] H.EndToEnd=struct.unpack("!I",sete.decode("hex"))[0] dbg="Read","V",H.ver,"L",H.len,"F",H.flags,"C",H.cmd,"A",H.appId,"H",H.HopByHop,"E",H.EndToEnd logging.debug(dbg) dbg=dictCOMMANDcode2name(H.flags,H.cmd) logging.info(dbg) H.msg=msg return # Split AVPs from message # Input: H.msg as hex string # Result: list of undecoded AVPs def splitMsgAVPs(msg): ret=[] dbg="Incoming avps",msg logging.debug(dbg) while len(msg)<>0: slen="00"+msg[10:16] mlen=struct.unpack("!I",slen.decode("hex"))[0] #Increase to boundary plen=calc_padding(mlen) (avp,msg)=chop_msg(msg,2*plen) dbg="Single AVP","L",mlen,plen,"D",avp logging.info(dbg) ret.append(avp) return ret #---------------------------------------------------------------------- # Connect to host:port (TCP) def Connect(host,port): # Create a socket (SOCK_STREAM means a TCP socket) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) return sock #---------------------------------------------------------------------- # DateTime routines def getCurrentDateTime(): t=time.localtime() return t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec # converts seconds since epoch to date def epoch2date(sec): t=time.localtime(sec) return t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec # converts to seconds since epoch def date2epoch(tYear,tMon,tDate,tHr,tMin,tSec): t=time.strptime("{0} {1} {2} {3} {4} {5}".format(tYear,tMon,tDate,tHr,tMin,tSec),"%Y %m %d %H %M %S") return time.mktime(t) ###################################################### # History # Ver 0.1 - Feb 06, 2012 - initial version # Ver 0.1.1 - Feb 07, 2012 - commands moved into dictionary # Ver 0.1.2 - Feb 11, 2012 - internal reorganization, code cleanup # Ver 0.2.0 - Feb 17, 2012 - EAP-Payload decoder # Ver 0.2.1 - Feb 19, 2012 - EAP-Payload + AKA/AKA' C calculations # Ver 0.2.2 - Feb 23, 2012 - Testing client AKA/AKA' # Ver 0.2.3 - Feb 25, 2012 - Multiple bugfixes, logging # Ver 0.2.4 - Mar 05, 2012 - Simplified dictionary, AVP types in sets # Ver 0.2.5 - Mar 14, 2012 - Windows support (socket.inet_ntop, inet_pton) # Ver 0.2.6 - Mar 18, 2012 - inet_ntop&pton now supports IPv6 on all platforms # Ver 0.2.7 - May 12, 2012 - Grouped, Float support # Ver 0.2.8 - May 25, 2012 - EAP functions moved to separate source # Ver 0.3.1 - Nov 12, 2012 - bugfix in encoding grouped list (fixed wrong length) # - ipv6 encoding bugfix, comments added # - logging levels modified, Time support added # - Enumerated now supports named values # - Fixed IP handling (now supports IP & IPAddress packing)
gpl-2.0
jordiclariana/ansible
lib/ansible/utils/module_docs_fragments/vyos.py
28
2874
# # (c) 2015, Peter Sprygada <psprygada@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. class ModuleDocFragment(object): # Standard files documentation fragment DOCUMENTATION = """ options: host: description: - Specifies the DNS host name or address for connecting to the remote device over the specified transport. The value of host is used as the destination address for the transport. required: true port: description: - Specifies the port to use when building the connection to the remote device. required: false default: 22 username: description: - Configures the username to use to authenticate the connection to the remote device. This value is used to authenticate the SSH session. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_USERNAME) will be used instead. required: false password: description: - Specifies the password to use to authenticate the connection to the remote device. This value is used to authenticate the SSH session. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_PASSWORD) will be used instead. required: false default: null timeout: description: - Specifies the timeout in seconds for communicating with the network device for either connecting or sending commands. If the timeout is exceeded before the operation is completed, the module will error. require: false default: 10 ssh_keyfile: description: - Specifies the SSH key to use to authenticate the connection to the remote device. This value is the path to the key used to authenticate the SSH session. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_SSH_KEYFILE) will be used instead. required: false provider: description: - Convenience method that allows all I(vyos) arguments to be passed as a dict object. All constraints (required, choices, etc) must be met either by individual arguments or values in this dict. required: false default: null """
gpl-3.0
Xeralux/tensorflow
tensorflow/contrib/eager/python/examples/rnn_colorbot/rnn_colorbot_test.py
22
2230
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.contrib.eager.python import tfe from tensorflow.contrib.eager.python.examples.rnn_colorbot import rnn_colorbot LABEL_DIMENSION = 5 def device(): return "/device:GPU:0" if tfe.num_gpus() else "/device:CPU:0" def random_dataset(): batch_size = 64 time_steps = 10 alphabet = 50 chars = tf.one_hot( tf.random_uniform( [batch_size, time_steps], minval=0, maxval=alphabet, dtype=tf.int32), alphabet) sequence_length = tf.constant( [time_steps for _ in range(batch_size)], dtype=tf.int64) labels = tf.random_normal([batch_size, LABEL_DIMENSION]) return tf.data.Dataset.from_tensors((labels, chars, sequence_length)) class RNNColorbotTest(tf.test.TestCase): def testTrainOneEpoch(self): model = rnn_colorbot.RNNColorbot( rnn_cell_sizes=[256, 128, 64], label_dimension=LABEL_DIMENSION, keep_prob=1.0) optimizer = tf.train.AdamOptimizer(learning_rate=.01) dataset = random_dataset() with tf.device(device()): rnn_colorbot.train_one_epoch(model, optimizer, dataset) def testTest(self): model = rnn_colorbot.RNNColorbot( rnn_cell_sizes=[256], label_dimension=LABEL_DIMENSION, keep_prob=1.0) dataset = random_dataset() with tf.device(device()): rnn_colorbot.test(model, dataset) if __name__ == "__main__": tfe.enable_eager_execution() tf.test.main()
apache-2.0
closeio/flask-admin
flask_admin/tests/mongoengine/test_basic.py
7
34515
from nose.tools import eq_, ok_ from nose.plugins.skip import SkipTest # Skip test on PY3 from flask_admin._compat import PY2, as_unicode if not PY2: raise SkipTest('MongoEngine is not Python 3 compatible') from wtforms import fields, validators from flask_admin import form from flask_admin.contrib.mongoengine import ModelView from . import setup from datetime import datetime class CustomModelView(ModelView): def __init__(self, model, name=None, category=None, endpoint=None, url=None, **kwargs): for k, v in kwargs.iteritems(): setattr(self, k, v) super(CustomModelView, self).__init__(model, name, category, endpoint, url) def create_models(db): class Model1(db.Document): test1 = db.StringField(max_length=20) test2 = db.StringField(max_length=20) test3 = db.StringField() test4 = db.StringField() datetime_field = db.DateTimeField() def __str__(self): return self.test1 class Model2(db.Document): string_field = db.StringField() int_field = db.IntField() float_field = db.FloatField() bool_field = db.BooleanField() model1 = db.ReferenceField(Model1) Model1.objects.delete() Model2.objects.delete() return Model1, Model2 def fill_db(Model1, Model2): Model1('test1_val_1', 'test2_val_1').save() Model1('test1_val_2', 'test2_val_2').save() Model1('test1_val_3', 'test2_val_3').save() Model1('test1_val_4', 'test2_val_4').save() Model1(None, 'empty_obj').save() Model2('string_field_val_1', None, None, True).save() Model2('string_field_val_2', None, None, False).save() Model2('string_field_val_3', 5000, 25.9).save() Model2('string_field_val_4', 9000, 75.5).save() Model2('string_field_val_5', 6169453081680413441).save() Model1('datetime_obj1', datetime_field=datetime(2014,4,3,1,9,0)).save() Model1('datetime_obj2', datetime_field=datetime(2013,3,2,0,8,0)).save() def test_model(): app, db, admin = setup() Model1, Model2 = create_models(db) view = CustomModelView(Model1) admin.add_view(view) eq_(view.model, Model1) eq_(view.name, 'Model1') eq_(view.endpoint, 'model1') eq_(view._primary_key, 'id') ok_('test1' in view._sortable_columns) ok_('test2' in view._sortable_columns) ok_('test3' in view._sortable_columns) ok_('test4' in view._sortable_columns) ok_(view._create_form_class is not None) ok_(view._edit_form_class is not None) eq_(view._search_supported, False) eq_(view._filters, None) eq_(view._create_form_class.test1.field_class, fields.StringField) eq_(view._create_form_class.test2.field_class, fields.StringField) eq_(view._create_form_class.test3.field_class, fields.TextAreaField) eq_(view._create_form_class.test4.field_class, fields.TextAreaField) # Make some test clients client = app.test_client() rv = client.get('/admin/model1/') eq_(rv.status_code, 200) rv = client.get('/admin/model1/new/') eq_(rv.status_code, 200) rv = client.post('/admin/model1/new/', data=dict(test1='test1large', test2='test2')) eq_(rv.status_code, 302) model = Model1.objects.first() eq_(model.test1, 'test1large') eq_(model.test2, 'test2') eq_(model.test3, '') eq_(model.test4, '') rv = client.get('/admin/model1/') eq_(rv.status_code, 200) ok_('test1large' in rv.data) url = '/admin/model1/edit/?id=%s' % model.id rv = client.get(url) eq_(rv.status_code, 200) rv = client.post(url, data=dict(test1='test1small', test2='test2large')) eq_(rv.status_code, 302) model = Model1.objects.first() eq_(model.test1, 'test1small') eq_(model.test2, 'test2large') eq_(model.test3, '') eq_(model.test4, '') url = '/admin/model1/delete/?id=%s' % model.id rv = client.post(url) eq_(rv.status_code, 302) eq_(Model1.objects.count(), 0) def test_column_editable_list(): app, db, admin = setup() Model1, Model2 = create_models(db) view = CustomModelView(Model1, column_editable_list=['test1', 'datetime_field']) admin.add_view(view) fill_db(Model1, Model2) client = app.test_client() # Test in-line edit field rendering rv = client.get('/admin/model1/') data = rv.data.decode('utf-8') ok_('data-role="x-editable"' in data) # Form - Test basic in-line edit functionality obj1 = Model1.objects.get(test1 = 'test1_val_3') rv = client.post('/admin/model1/ajax/update/', data={ 'list_form_pk': str(obj1.id), 'test1': 'change-success-1', }) data = rv.data.decode('utf-8') ok_('Record was successfully saved.' == data) # confirm the value has changed rv = client.get('/admin/model1/') data = rv.data.decode('utf-8') ok_('change-success-1' in data) # Test validation error obj2 = Model1.objects.get(test1 = 'datetime_obj1') rv = client.post('/admin/model1/ajax/update/', data={ 'list_form_pk': str(obj2.id), 'datetime_field': 'problematic-input', }) eq_(rv.status_code, 500) # Test invalid primary key rv = client.post('/admin/model1/ajax/update/', data={ 'list_form_pk': '1000', 'test1': 'problematic-input', }) data = rv.data.decode('utf-8') eq_(rv.status_code, 500) # Test editing column not in column_editable_list rv = client.post('/admin/model1/ajax/update/', data={ 'list_form_pk': '1', 'test2': 'problematic-input', }) data = rv.data.decode('utf-8') ok_('problematic-input' not in data) # Test in-line editing for relations view = CustomModelView(Model2, column_editable_list=['model1']) admin.add_view(view) obj3 = Model2.objects.get(string_field = 'string_field_val_1') rv = client.post('/admin/model2/ajax/update/', data={ 'list_form_pk': str(obj3.id), 'model1': str(obj1.id), }) data = rv.data.decode('utf-8') ok_('Record was successfully saved.' == data) # confirm the value has changed rv = client.get('/admin/model2/') data = rv.data.decode('utf-8') ok_('test1_val_1' in data) def test_details_view(): app, db, admin = setup() Model1, Model2 = create_models(db) view_no_details = CustomModelView(Model1) admin.add_view(view_no_details) # fields are scaffolded view_w_details = CustomModelView(Model2, can_view_details=True) admin.add_view(view_w_details) # show only specific fields in details w/ column_details_list string_field_view = CustomModelView(Model2, can_view_details=True, column_details_list=["string_field"], endpoint="sf_view") admin.add_view(string_field_view) fill_db(Model1, Model2) client = app.test_client() m1_id = Model1.objects.first().id m2_id = Model2.objects.first().id # ensure link to details is hidden when can_view_details is disabled rv = client.get('/admin/model1/') data = rv.data.decode('utf-8') ok_('/admin/model1/details/' not in data) # ensure link to details view appears rv = client.get('/admin/model2/') data = rv.data.decode('utf-8') ok_('/admin/model2/details/' in data) # test redirection when details are disabled url = '/admin/model1/details/?url=%2Fadmin%2Fmodel1%2F&id=' + str(m1_id) rv = client.get(url) eq_(rv.status_code, 302) # test if correct data appears in details view when enabled url = '/admin/model2/details/?url=%2Fadmin%2Fmodel2%2F&id=' + str(m2_id) rv = client.get(url) data = rv.data.decode('utf-8') ok_('String Field' in data) ok_('string_field_val_1' in data) ok_('Int Field' in data) # test column_details_list url = '/admin/sf_view/details/?url=%2Fadmin%2Fsf_view%2F&id=' + str(m2_id) rv = client.get(url) data = rv.data.decode('utf-8') ok_('String Field' in data) ok_('string_field_val_1' in data) ok_('Int Field' not in data) def test_column_filters(): app, db, admin = setup() Model1, Model2 = create_models(db) # fill DB with values fill_db(Model1, Model2) # Test string filter view = CustomModelView(Model1, column_filters=['test1']) admin.add_view(view) eq_(len(view._filters), 7) eq_([(f['index'], f['operation']) for f in view._filter_groups[u'Test1']], [ (0, 'contains'), (1, 'not contains'), (2, 'equals'), (3, 'not equal'), (4, 'empty'), (5, 'in list'), (6, 'not in list'), ]) # Make some test clients client = app.test_client() # string - equals rv = client.get('/admin/model1/?flt0_0=test1_val_1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('test2_val_1' in data) ok_('test1_val_2' not in data) # string - not equal rv = client.get('/admin/model1/?flt0_1=test1_val_1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('test2_val_1' not in data) ok_('test1_val_2' in data) # string - contains rv = client.get('/admin/model1/?flt0_2=test1_val_1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('test2_val_1' in data) ok_('test1_val_2' not in data) # string - not contains rv = client.get('/admin/model1/?flt0_3=test1_val_1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('test2_val_1' not in data) ok_('test1_val_2' in data) # string - empty rv = client.get('/admin/model1/?flt0_4=1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('empty_obj' in data) ok_('test1_val_1' not in data) ok_('test1_val_2' not in data) # string - not empty rv = client.get('/admin/model1/?flt0_4=0') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('empty_obj' not in data) ok_('test1_val_1' in data) ok_('test1_val_2' in data) # string - in list rv = client.get('/admin/model1/?flt0_5=test1_val_1%2Ctest1_val_2') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('test2_val_1' in data) ok_('test2_val_2' in data) ok_('test1_val_3' not in data) ok_('test1_val_4' not in data) # string - not in list rv = client.get('/admin/model1/?flt0_6=test1_val_1%2Ctest1_val_2') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('test2_val_1' not in data) ok_('test2_val_2' not in data) ok_('test1_val_3' in data) ok_('test1_val_4' in data) # Test numeric filter view = CustomModelView(Model2, column_filters=['int_field']) admin.add_view(view) eq_([(f['index'], f['operation']) for f in view._filter_groups[u'Int Field']], [ (0, 'equals'), (1, 'not equal'), (2, 'greater than'), (3, 'smaller than'), (4, 'empty'), (5, 'in list'), (6, 'not in list'), ]) # integer - equals rv = client.get('/admin/model2/?flt0_0=5000') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_3' in data) ok_('string_field_val_4' not in data) # integer - equals (huge number) rv = client.get('/admin/model2/?flt0_0=6169453081680413441') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_5' in data) ok_('string_field_val_4' not in data) # integer - equals - test validation rv = client.get('/admin/model2/?flt0_0=badval') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('Invalid Filter Value' in data) # integer - not equal rv = client.get('/admin/model2/?flt0_1=5000') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_3' not in data) ok_('string_field_val_4' in data) # integer - greater rv = client.get('/admin/model2/?flt0_2=6000') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_3' not in data) ok_('string_field_val_4' in data) # integer - smaller rv = client.get('/admin/model2/?flt0_3=6000') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_3' in data) ok_('string_field_val_4' not in data) # integer - empty rv = client.get('/admin/model2/?flt0_4=1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' in data) ok_('string_field_val_2' in data) ok_('string_field_val_3' not in data) ok_('string_field_val_4' not in data) # integer - not empty rv = client.get('/admin/model2/?flt0_4=0') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' not in data) ok_('string_field_val_2' not in data) ok_('string_field_val_3' in data) ok_('string_field_val_4' in data) # integer - in list rv = client.get('/admin/model2/?flt0_5=5000%2C9000') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' not in data) ok_('string_field_val_2' not in data) ok_('string_field_val_3' in data) ok_('string_field_val_4' in data) # integer - in list (huge number) rv = client.get('/admin/model2/?flt0_5=6169453081680413441') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' not in data) ok_('string_field_val_5' in data) # integer - in list - test validation rv = client.get('/admin/model2/?flt0_5=5000%2Cbadval') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('Invalid Filter Value' in data) # integer - not in list rv = client.get('/admin/model2/?flt0_6=5000%2C9000') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' in data) ok_('string_field_val_2' in data) ok_('string_field_val_3' not in data) ok_('string_field_val_4' not in data) # Test boolean filter view = CustomModelView(Model2, column_filters=['bool_field'], endpoint="_bools") admin.add_view(view) eq_([(f['index'], f['operation']) for f in view._filter_groups[u'Bool Field']], [ (0, 'equals'), (1, 'not equal'), ]) # boolean - equals - Yes rv = client.get('/admin/_bools/?flt0_0=1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' in data) ok_('string_field_val_2' not in data) #ok_('string_field_val_3' not in data) # boolean - equals - No rv = client.get('/admin/_bools/?flt0_0=0') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' not in data) ok_('string_field_val_2' in data) #ok_('string_field_val_3' in data) # boolean - not equals - Yes rv = client.get('/admin/_bools/?flt0_1=1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' not in data) ok_('string_field_val_2' in data) #ok_('string_field_val_3' in data) # boolean - not equals - No rv = client.get('/admin/_bools/?flt0_1=0') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' in data) ok_('string_field_val_2' not in data) #ok_('string_field_val_3' not in data) # Test float filter view = CustomModelView(Model2, column_filters=['float_field'], endpoint="_float") admin.add_view(view) eq_([(f['index'], f['operation']) for f in view._filter_groups[u'Float Field']], [ (0, 'equals'), (1, 'not equal'), (2, 'greater than'), (3, 'smaller than'), (4, 'empty'), (5, 'in list'), (6, 'not in list'), ]) # float - equals rv = client.get('/admin/_float/?flt0_0=25.9') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_3' in data) ok_('string_field_val_4' not in data) # float - equals - test validation rv = client.get('/admin/_float/?flt0_0=badval') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('Invalid Filter Value' in data) # float - not equal rv = client.get('/admin/_float/?flt0_1=25.9') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_3' not in data) ok_('string_field_val_4' in data) # float - greater rv = client.get('/admin/_float/?flt0_2=60.5') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_3' not in data) ok_('string_field_val_4' in data) # float - smaller rv = client.get('/admin/_float/?flt0_3=60.5') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_3' in data) ok_('string_field_val_4' not in data) # float - empty rv = client.get('/admin/_float/?flt0_4=1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' in data) ok_('string_field_val_2' in data) ok_('string_field_val_3' not in data) ok_('string_field_val_4' not in data) # float - not empty rv = client.get('/admin/_float/?flt0_4=0') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' not in data) ok_('string_field_val_2' not in data) ok_('string_field_val_3' in data) ok_('string_field_val_4' in data) # float - in list rv = client.get('/admin/_float/?flt0_5=25.9%2C75.5') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' not in data) ok_('string_field_val_2' not in data) ok_('string_field_val_3' in data) ok_('string_field_val_4' in data) # float - in list - test validation rv = client.get('/admin/_float/?flt0_5=25.9%2Cbadval') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('Invalid Filter Value' in data) # float - not in list rv = client.get('/admin/_float/?flt0_6=25.9%2C75.5') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('string_field_val_1' in data) ok_('string_field_val_2' in data) ok_('string_field_val_3' not in data) ok_('string_field_val_4' not in data) # Test datetime filter view = CustomModelView(Model1, column_filters=['datetime_field'], endpoint="_datetime") admin.add_view(view) eq_([(f['index'], f['operation']) for f in view._filter_groups[u'Datetime Field']], [ (0, 'equals'), (1, 'not equal'), (2, 'greater than'), (3, 'smaller than'), (4, 'between'), (5, 'not between'), (6, 'empty'), ]) # datetime - equals rv = client.get('/admin/_datetime/?flt0_0=2014-04-03+01%3A09%3A00') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('datetime_obj1' in data) ok_('datetime_obj2' not in data) # datetime - not equal rv = client.get('/admin/_datetime/?flt0_1=2014-04-03+01%3A09%3A00') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('datetime_obj1' not in data) ok_('datetime_obj2' in data) # datetime - greater rv = client.get('/admin/_datetime/?flt0_2=2014-04-03+01%3A08%3A00') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('datetime_obj1' in data) ok_('datetime_obj2' not in data) # datetime - smaller rv = client.get('/admin/_datetime/?flt0_3=2014-04-03+01%3A08%3A00') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('datetime_obj1' not in data) ok_('datetime_obj2' in data) # datetime - between rv = client.get('/admin/_datetime/?flt0_4=2014-04-02+00%3A00%3A00+to+2014-11-20+23%3A59%3A59') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('datetime_obj1' in data) ok_('datetime_obj2' not in data) # datetime - not between rv = client.get('/admin/_datetime/?flt0_5=2014-04-02+00%3A00%3A00+to+2014-11-20+23%3A59%3A59') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('datetime_obj1' not in data) ok_('datetime_obj2' in data) # datetime - empty rv = client.get('/admin/_datetime/?flt0_6=1') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('test1_val_1' in data) ok_('datetime_obj1' not in data) ok_('datetime_obj2' not in data) # datetime - not empty rv = client.get('/admin/_datetime/?flt0_6=0') eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_('test1_val_1' not in data) ok_('datetime_obj1' in data) ok_('datetime_obj2' in data) def test_default_sort(): app, db, admin = setup() M1, _ = create_models(db) M1(test1='c').save() M1(test1='b').save() M1(test1='a').save() eq_(M1.objects.count(), 3) view = CustomModelView(M1, column_default_sort='test1') admin.add_view(view) _, data = view.get_list(0, None, None, None, None) eq_(data[0].test1, 'a') eq_(data[1].test1, 'b') eq_(data[2].test1, 'c') def test_extra_fields(): app, db, admin = setup() Model1, _ = create_models(db) view = CustomModelView( Model1, form_extra_fields={ 'extra_field': fields.StringField('Extra Field') } ) admin.add_view(view) client = app.test_client() rv = client.get('/admin/model1/new/') eq_(rv.status_code, 200) # Check presence and order data = rv.data.decode('utf-8') ok_('Extra Field' in data) pos1 = data.find('Extra Field') pos2 = data.find('Test1') ok_(pos2 < pos1) def test_extra_field_order(): app, db, admin = setup() Model1, _ = create_models(db) view = CustomModelView( Model1, form_extra_fields={ 'extra_field': fields.StringField('Extra Field') } ) admin.add_view(view) client = app.test_client() rv = client.get('/admin/model1/new/') eq_(rv.status_code, 200) # Check presence and order data = rv.data.decode('utf-8') ok_('Extra Field' in data) pos1 = data.find('Extra Field') pos2 = data.find('Test1') ok_(pos2 < pos1) def test_custom_form_base(): app, db, admin = setup() class TestForm(form.BaseForm): pass Model1, _ = create_models(db) view = CustomModelView( Model1, form_base_class=TestForm ) admin.add_view(view) ok_(hasattr(view._create_form_class, 'test1')) create_form = view.create_form() ok_(isinstance(create_form, TestForm)) def test_subdocument_config(): app, db, admin = setup() class Comment(db.EmbeddedDocument): name = db.StringField(max_length=20, required=True) value = db.StringField(max_length=20) class Model1(db.Document): test1 = db.StringField(max_length=20) subdoc = db.EmbeddedDocumentField(Comment) # Check only view1 = CustomModelView( Model1, form_subdocuments = { 'subdoc': { 'form_columns': ('name',) } } ) ok_(hasattr(view1._create_form_class, 'subdoc')) form = view1.create_form() ok_('name' in dir(form.subdoc.form)) ok_('value' not in dir(form.subdoc.form)) # Check exclude view2 = CustomModelView( Model1, form_subdocuments = { 'subdoc': { 'form_excluded_columns': ('value',) } } ) form = view2.create_form() ok_('name' in dir(form.subdoc.form)) ok_('value' not in dir(form.subdoc.form)) def test_subdocument_class_config(): app, db, admin = setup() from flask_admin.contrib.mongoengine import EmbeddedForm class Comment(db.EmbeddedDocument): name = db.StringField(max_length=20, required=True) value = db.StringField(max_length=20) class Model1(db.Document): test1 = db.StringField(max_length=20) subdoc = db.EmbeddedDocumentField(Comment) class EmbeddedConfig(EmbeddedForm): form_columns = ('name',) # Check only view1 = CustomModelView( Model1, form_subdocuments = { 'subdoc': EmbeddedConfig() } ) form = view1.create_form() ok_('name' in dir(form.subdoc.form)) ok_('value' not in dir(form.subdoc.form)) def test_nested_subdocument_config(): app, db, admin = setup() # Check recursive class Comment(db.EmbeddedDocument): name = db.StringField(max_length=20, required=True) value = db.StringField(max_length=20) class Nested(db.EmbeddedDocument): name = db.StringField(max_length=20, required=True) comment = db.EmbeddedDocumentField(Comment) class Model1(db.Document): test1 = db.StringField(max_length=20) nested = db.EmbeddedDocumentField(Nested) view1 = CustomModelView( Model1, form_subdocuments = { 'nested': { 'form_subdocuments': { 'comment': { 'form_columns': ('name',) } } } } ) form = view1.create_form() ok_('name' in dir(form.nested.form.comment.form)) ok_('value' not in dir(form.nested.form.comment.form)) def test_nested_list_subdocument(): app, db, admin = setup() class Comment(db.EmbeddedDocument): name = db.StringField(max_length=20, required=True) value = db.StringField(max_length=20) class Model1(db.Document): test1 = db.StringField(max_length=20) subdoc = db.ListField(db.EmbeddedDocumentField(Comment)) # Check only view1 = CustomModelView( Model1, form_subdocuments = { 'subdoc': { 'form_subdocuments': { None: { 'form_columns': ('name',) } } } } ) form = view1.create_form() inline_form = form.subdoc.unbound_field.args[2] ok_('name' in dir(inline_form)) ok_('value' not in dir(inline_form)) def test_nested_sortedlist_subdocument(): app, db, admin = setup() class Comment(db.EmbeddedDocument): name = db.StringField(max_length=20, required=True) value = db.StringField(max_length=20) class Model1(db.Document): test1 = db.StringField(max_length=20) subdoc = db.SortedListField(db.EmbeddedDocumentField(Comment)) # Check only view1 = CustomModelView( Model1, form_subdocuments = { 'subdoc': { 'form_subdocuments': { None: { 'form_columns': ('name',) } } } } ) form = view1.create_form() inline_form = form.subdoc.unbound_field.args[2] ok_('name' in dir(inline_form)) ok_('value' not in dir(inline_form)) def test_sortedlist_subdocument_validation(): app, db, admin = setup() class Comment(db.EmbeddedDocument): name = db.StringField(max_length=20, required=True) value = db.StringField(max_length=20) class Model1(db.Document): test1 = db.StringField(max_length=20) subdoc = db.SortedListField(db.EmbeddedDocumentField(Comment)) view = CustomModelView(Model1) admin.add_view(view) client = app.test_client() rv = client.post('/admin/model1/new/', data={'test1': 'test1large', 'subdoc-0-name': 'comment', 'subdoc-0-value': 'test'}) eq_(rv.status_code, 302) rv = client.post('/admin/model1/new/', data={'test1': 'test1large', 'subdoc-0-name': '', 'subdoc-0-value': 'test'}) eq_(rv.status_code, 200) ok_('This field is required' in rv.data) def test_list_subdocument_validation(): app, db, admin = setup() class Comment(db.EmbeddedDocument): name = db.StringField(max_length=20, required=True) value = db.StringField(max_length=20) class Model1(db.Document): test1 = db.StringField(max_length=20) subdoc = db.ListField(db.EmbeddedDocumentField(Comment)) view = CustomModelView(Model1) admin.add_view(view) client = app.test_client() rv = client.post('/admin/model1/new/', data={'test1': 'test1large', 'subdoc-0-name': 'comment', 'subdoc-0-value': 'test'}) eq_(rv.status_code, 302) rv = client.post('/admin/model1/new/', data={'test1': 'test1large', 'subdoc-0-name': '', 'subdoc-0-value': 'test'}) eq_(rv.status_code, 200) ok_('This field is required' in rv.data) def test_ajax_fk(): app, db, admin = setup() Model1, Model2 = create_models(db) view = CustomModelView( Model2, url='view', form_ajax_refs={ 'model1': { 'fields': ('test1', 'test2') } } ) admin.add_view(view) ok_(u'model1' in view._form_ajax_refs) model = Model1(test1=u'first') model.save() model2 = Model1(test1=u'foo', test2=u'bar').save() # Check loader loader = view._form_ajax_refs[u'model1'] mdl = loader.get_one(model.id) eq_(mdl.test1, model.test1) items = loader.get_list(u'fir') eq_(len(items), 1) eq_(items[0].id, model.id) items = loader.get_list(u'bar') eq_(len(items), 1) eq_(items[0].test1, u'foo') # Check form generation form = view.create_form() eq_(form.model1.__class__.__name__, u'AjaxSelectField') with app.test_request_context('/admin/view/'): ok_(u'value=""' not in form.model1()) form.model1.data = model needle = u'data-json="[&quot;%s&quot;, &quot;first&quot;]"' % as_unicode(model.id) ok_(needle in form.model1()) ok_(u'value="%s"' % as_unicode(model.id) in form.model1()) # Check querying client = app.test_client() req = client.get(u'/admin/view/ajax/lookup/?name=model1&query=foo') eq_(req.data, u'[["%s", "foo"]]' % model2.id) # Check submitting client.post('/admin/view/new/', data={u'model1': as_unicode(model.id)}) mdl = Model2.objects.first() ok_(mdl is not None) ok_(mdl.model1 is not None) eq_(mdl.model1.id, model.id) eq_(mdl.model1.test1, u'first') def test_nested_ajax_refs(): app, db, admin = setup() # Check recursive class Comment(db.Document): name = db.StringField(max_length=20, required=True) value = db.StringField(max_length=20) class Nested(db.EmbeddedDocument): name = db.StringField(max_length=20, required=True) comment = db.ReferenceField(Comment) class Model1(db.Document): test1 = db.StringField(max_length=20) nested = db.EmbeddedDocumentField(Nested) view1 = CustomModelView( Model1, form_subdocuments = { 'nested': { 'form_ajax_refs': { 'comment': { 'fields': ['name'] } } } } ) form = view1.create_form() eq_(type(form.nested.form.comment).__name__, 'AjaxSelectField') ok_('nested-comment' in view1._form_ajax_refs) def test_form_flat_choices(): app, db, admin = setup() class Model(db.Document): name = db.StringField(max_length=20, choices=('a', 'b', 'c')) view = CustomModelView(Model) admin.add_view(view) form = view.create_form() eq_(form.name.choices, [('a', 'a'), ('b', 'b'), ('c', 'c')]) def test_form_args(): app, db, admin = setup() class Model(db.Document): test = db.StringField(required=True) shared_form_args = {'test': {'validators': [validators.Regexp('test')]}} view = CustomModelView(Model, form_args=shared_form_args) admin.add_view(view) # ensure shared field_args don't create duplicate validators create_form = view.create_form() eq_(len(create_form.test.validators), 2) edit_form = view.edit_form() eq_(len(edit_form.test.validators), 2) def test_form_args_embeddeddoc(): app, db, admin = setup() class Info(db.EmbeddedDocument): name = db.StringField() age = db.StringField() class Model(db.Document): info = db.EmbeddedDocumentField('Info') timestamp = db.DateTimeField() view = CustomModelView( Model, form_args= { 'info': {'label': 'Information'}, 'timestamp': {'label': 'Last Updated Time'} } ) admin.add_view(view) form = view.create_form() eq_(form.timestamp.label.text, 'Last Updated Time') # This is the failure eq_(form.info.label.text, 'Information') def test_simple_list_pager(): app, db, admin = setup() Model1, _ = create_models(db) class TestModelView(CustomModelView): simple_list_pager = True def get_count_query(self): assert False view = TestModelView(Model1) admin.add_view(view) count, data = view.get_list(0, None, None, None, None) ok_(count is None) def test_export_csv(): app, db, admin = setup() Model1, Model2 = create_models(db) view = CustomModelView(Model1, can_export=True, column_list=['test1', 'test2'], export_max_rows=2, endpoint='row_limit_2') admin.add_view(view) for x in range(5): fill_db(Model1, Model2) client = app.test_client() # test export_max_rows rv = client.get('/admin/row_limit_2/export/csv/') data = rv.data.decode('utf-8') eq_(rv.status_code, 200) ok_("Test1,Test2\r\n" "test1_val_1,test2_val_1\r\n" "test1_val_2,test2_val_2\r\n" == data) view = CustomModelView(Model1, can_export=True, column_list=['test1', 'test2'], endpoint='no_row_limit') admin.add_view(view) # test row limit without export_max_rows rv = client.get('/admin/no_row_limit/export/csv/') data = rv.data.decode('utf-8') eq_(rv.status_code, 200) ok_(len(data.splitlines()) > 21)
bsd-3-clause
brightcove/shaka-player
third_party/gjslint/python-gflags-2.0/tests/gflags_unittest.py
100
79202
#!/usr/bin/env python # Copyright (c) 2007, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. "Unittest for gflags.py module" __pychecker__ = "no-local" # for unittest import cStringIO import sys import os import shutil import gflags from flags_modules_for_testing import module_foo from flags_modules_for_testing import module_bar from flags_modules_for_testing import module_baz FLAGS=gflags.FLAGS import gflags_googletest as googletest # TODO(csilvers): add a wrapper function around FLAGS(argv) that # verifies the input is a list or tuple. This avoids bugs where we # make argv a string instead of a list, by mistake. class FlagsUnitTest(googletest.TestCase): "Flags Unit Test" def setUp(self): # make sure we are using the old, stupid way of parsing flags. FLAGS.UseGnuGetOpt(False) def test_flags(self): ############################################## # Test normal usage with no (expected) errors. # Define flags number_test_framework_flags = len(FLAGS.RegisteredFlags()) repeatHelp = "how many times to repeat (0-5)" gflags.DEFINE_integer("repeat", 4, repeatHelp, lower_bound=0, short_name='r') gflags.DEFINE_string("name", "Bob", "namehelp") gflags.DEFINE_boolean("debug", 0, "debughelp") gflags.DEFINE_boolean("q", 1, "quiet mode") gflags.DEFINE_boolean("quack", 0, "superstring of 'q'") gflags.DEFINE_boolean("noexec", 1, "boolean flag with no as prefix") gflags.DEFINE_integer("x", 3, "how eXtreme to be") gflags.DEFINE_integer("l", 0x7fffffff00000000, "how long to be") gflags.DEFINE_list('letters', 'a,b,c', "a list of letters") gflags.DEFINE_list('numbers', [1, 2, 3], "a list of numbers") gflags.DEFINE_enum("kwery", None, ['who', 'what', 'why', 'where', 'when'], "?") # Specify number of flags defined above. The short_name defined # for 'repeat' counts as an extra flag. number_defined_flags = 11 + 1 self.assertEqual(len(FLAGS.RegisteredFlags()), number_defined_flags + number_test_framework_flags) assert FLAGS.repeat == 4, "integer default values not set:" + FLAGS.repeat assert FLAGS.name == 'Bob', "default values not set:" + FLAGS.name assert FLAGS.debug == 0, "boolean default values not set:" + FLAGS.debug assert FLAGS.q == 1, "boolean default values not set:" + FLAGS.q assert FLAGS.x == 3, "integer default values not set:" + FLAGS.x assert FLAGS.l == 0x7fffffff00000000, ("integer default values not set:" + FLAGS.l) assert FLAGS.letters == ['a', 'b', 'c'], ("list default values not set:" + FLAGS.letters) assert FLAGS.numbers == [1, 2, 3], ("list default values not set:" + FLAGS.numbers) assert FLAGS.kwery is None, ("enum default None value not set:" + FLAGS.kwery) flag_values = FLAGS.FlagValuesDict() assert flag_values['repeat'] == 4 assert flag_values['name'] == 'Bob' assert flag_values['debug'] == 0 assert flag_values['r'] == 4 # short for repeat assert flag_values['q'] == 1 assert flag_values['quack'] == 0 assert flag_values['x'] == 3 assert flag_values['l'] == 0x7fffffff00000000 assert flag_values['letters'] == ['a', 'b', 'c'] assert flag_values['numbers'] == [1, 2, 3] assert flag_values['kwery'] is None # Verify string form of defaults assert FLAGS['repeat'].default_as_str == "'4'" assert FLAGS['name'].default_as_str == "'Bob'" assert FLAGS['debug'].default_as_str == "'false'" assert FLAGS['q'].default_as_str == "'true'" assert FLAGS['quack'].default_as_str == "'false'" assert FLAGS['noexec'].default_as_str == "'true'" assert FLAGS['x'].default_as_str == "'3'" assert FLAGS['l'].default_as_str == "'9223372032559808512'" assert FLAGS['letters'].default_as_str == "'a,b,c'" assert FLAGS['numbers'].default_as_str == "'1,2,3'" # Verify that the iterator for flags yields all the keys keys = list(FLAGS) keys.sort() reg_flags = FLAGS.RegisteredFlags() reg_flags.sort() self.assertEqual(keys, reg_flags) # Parse flags # .. empty command line argv = ('./program',) argv = FLAGS(argv) assert len(argv) == 1, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" # .. non-empty command line argv = ('./program', '--debug', '--name=Bob', '-q', '--x=8') argv = FLAGS(argv) assert len(argv) == 1, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" assert FLAGS['debug'].present == 1 FLAGS['debug'].present = 0 # Reset assert FLAGS['name'].present == 1 FLAGS['name'].present = 0 # Reset assert FLAGS['q'].present == 1 FLAGS['q'].present = 0 # Reset assert FLAGS['x'].present == 1 FLAGS['x'].present = 0 # Reset # Flags list self.assertEqual(len(FLAGS.RegisteredFlags()), number_defined_flags + number_test_framework_flags) assert 'name' in FLAGS.RegisteredFlags() assert 'debug' in FLAGS.RegisteredFlags() assert 'repeat' in FLAGS.RegisteredFlags() assert 'r' in FLAGS.RegisteredFlags() assert 'q' in FLAGS.RegisteredFlags() assert 'quack' in FLAGS.RegisteredFlags() assert 'x' in FLAGS.RegisteredFlags() assert 'l' in FLAGS.RegisteredFlags() assert 'letters' in FLAGS.RegisteredFlags() assert 'numbers' in FLAGS.RegisteredFlags() # has_key assert FLAGS.has_key('name') assert not FLAGS.has_key('name2') assert 'name' in FLAGS assert 'name2' not in FLAGS # try deleting a flag del FLAGS.r self.assertEqual(len(FLAGS.RegisteredFlags()), number_defined_flags - 1 + number_test_framework_flags) assert not 'r' in FLAGS.RegisteredFlags() # .. command line with extra stuff argv = ('./program', '--debug', '--name=Bob', 'extra') argv = FLAGS(argv) assert len(argv) == 2, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" assert argv[1]=='extra', "extra argument not preserved" assert FLAGS['debug'].present == 1 FLAGS['debug'].present = 0 # Reset assert FLAGS['name'].present == 1 FLAGS['name'].present = 0 # Reset # Test reset argv = ('./program', '--debug') argv = FLAGS(argv) assert len(argv) == 1, "wrong number of arguments pulled" assert argv[0] == './program', "program name not preserved" assert FLAGS['debug'].present == 1 assert FLAGS['debug'].value FLAGS.Reset() assert FLAGS['debug'].present == 0 assert not FLAGS['debug'].value # Test that reset restores default value when default value is None. argv = ('./program', '--kwery=who') argv = FLAGS(argv) assert len(argv) == 1, "wrong number of arguments pulled" assert argv[0] == './program', "program name not preserved" assert FLAGS['kwery'].present == 1 assert FLAGS['kwery'].value == 'who' FLAGS.Reset() assert FLAGS['kwery'].present == 0 assert FLAGS['kwery'].value == None # Test integer argument passing argv = ('./program', '--x', '0x12345') argv = FLAGS(argv) self.assertEquals(FLAGS.x, 0x12345) self.assertEquals(type(FLAGS.x), int) argv = ('./program', '--x', '0x1234567890ABCDEF1234567890ABCDEF') argv = FLAGS(argv) self.assertEquals(FLAGS.x, 0x1234567890ABCDEF1234567890ABCDEF) self.assertEquals(type(FLAGS.x), long) # Treat 0-prefixed parameters as base-10, not base-8 argv = ('./program', '--x', '012345') argv = FLAGS(argv) self.assertEquals(FLAGS.x, 12345) self.assertEquals(type(FLAGS.x), int) argv = ('./program', '--x', '0123459') argv = FLAGS(argv) self.assertEquals(FLAGS.x, 123459) self.assertEquals(type(FLAGS.x), int) argv = ('./program', '--x', '0x123efg') try: argv = FLAGS(argv) raise AssertionError("failed to detect invalid hex argument") except gflags.IllegalFlagValue: pass # Test boolean argument parsing gflags.DEFINE_boolean("test0", None, "test boolean parsing") argv = ('./program', '--notest0') argv = FLAGS(argv) assert FLAGS.test0 == 0 gflags.DEFINE_boolean("test1", None, "test boolean parsing") argv = ('./program', '--test1') argv = FLAGS(argv) assert FLAGS.test1 == 1 FLAGS.test0 = None argv = ('./program', '--test0=false') argv = FLAGS(argv) assert FLAGS.test0 == 0 FLAGS.test1 = None argv = ('./program', '--test1=true') argv = FLAGS(argv) assert FLAGS.test1 == 1 FLAGS.test0 = None argv = ('./program', '--test0=0') argv = FLAGS(argv) assert FLAGS.test0 == 0 FLAGS.test1 = None argv = ('./program', '--test1=1') argv = FLAGS(argv) assert FLAGS.test1 == 1 # Test booleans that already have 'no' as a prefix FLAGS.noexec = None argv = ('./program', '--nonoexec', '--name', 'Bob') argv = FLAGS(argv) assert FLAGS.noexec == 0 FLAGS.noexec = None argv = ('./program', '--name', 'Bob', '--noexec') argv = FLAGS(argv) assert FLAGS.noexec == 1 # Test unassigned booleans gflags.DEFINE_boolean("testnone", None, "test boolean parsing") argv = ('./program',) argv = FLAGS(argv) assert FLAGS.testnone == None # Test get with default gflags.DEFINE_boolean("testget1", None, "test parsing with defaults") gflags.DEFINE_boolean("testget2", None, "test parsing with defaults") gflags.DEFINE_boolean("testget3", None, "test parsing with defaults") gflags.DEFINE_integer("testget4", None, "test parsing with defaults") argv = ('./program','--testget1','--notestget2') argv = FLAGS(argv) assert FLAGS.get('testget1', 'foo') == 1 assert FLAGS.get('testget2', 'foo') == 0 assert FLAGS.get('testget3', 'foo') == 'foo' assert FLAGS.get('testget4', 'foo') == 'foo' # test list code lists = [['hello','moo','boo','1'], [],] gflags.DEFINE_list('testlist', '', 'test lists parsing') gflags.DEFINE_spaceseplist('testspacelist', '', 'tests space lists parsing') for name, sep in (('testlist', ','), ('testspacelist', ' '), ('testspacelist', '\n')): for lst in lists: argv = ('./program', '--%s=%s' % (name, sep.join(lst))) argv = FLAGS(argv) self.assertEquals(getattr(FLAGS, name), lst) # Test help text flagsHelp = str(FLAGS) assert flagsHelp.find("repeat") != -1, "cannot find flag in help" assert flagsHelp.find(repeatHelp) != -1, "cannot find help string in help" # Test flag specified twice argv = ('./program', '--repeat=4', '--repeat=2', '--debug', '--nodebug') argv = FLAGS(argv) self.assertEqual(FLAGS.get('repeat', None), 2) self.assertEqual(FLAGS.get('debug', None), 0) # Test MultiFlag with single default value gflags.DEFINE_multistring('s_str', 'sing1', 'string option that can occur multiple times', short_name='s') self.assertEqual(FLAGS.get('s_str', None), [ 'sing1', ]) # Test MultiFlag with list of default values multi_string_defs = [ 'def1', 'def2', ] gflags.DEFINE_multistring('m_str', multi_string_defs, 'string option that can occur multiple times', short_name='m') self.assertEqual(FLAGS.get('m_str', None), multi_string_defs) # Test flag specified multiple times with a MultiFlag argv = ('./program', '--m_str=str1', '-m', 'str2') argv = FLAGS(argv) self.assertEqual(FLAGS.get('m_str', None), [ 'str1', 'str2', ]) # Test single-letter flags; should support both single and double dash argv = ('./program', '-q', '-x8') argv = FLAGS(argv) self.assertEqual(FLAGS.get('q', None), 1) self.assertEqual(FLAGS.get('x', None), 8) argv = ('./program', '--q', '--x', '9', '--noqu') argv = FLAGS(argv) self.assertEqual(FLAGS.get('q', None), 1) self.assertEqual(FLAGS.get('x', None), 9) # --noqu should match '--noquack since it's a unique prefix self.assertEqual(FLAGS.get('quack', None), 0) argv = ('./program', '--noq', '--x=10', '--qu') argv = FLAGS(argv) self.assertEqual(FLAGS.get('q', None), 0) self.assertEqual(FLAGS.get('x', None), 10) self.assertEqual(FLAGS.get('quack', None), 1) #################################### # Test flag serialization code: oldtestlist = FLAGS.testlist oldtestspacelist = FLAGS.testspacelist argv = ('./program', FLAGS['test0'].Serialize(), FLAGS['test1'].Serialize(), FLAGS['testnone'].Serialize(), FLAGS['s_str'].Serialize()) argv = FLAGS(argv) self.assertEqual(FLAGS['test0'].Serialize(), '--notest0') self.assertEqual(FLAGS['test1'].Serialize(), '--test1') self.assertEqual(FLAGS['testnone'].Serialize(), '') self.assertEqual(FLAGS['s_str'].Serialize(), '--s_str=sing1') testlist1 = ['aa', 'bb'] testspacelist1 = ['aa', 'bb', 'cc'] FLAGS.testlist = list(testlist1) FLAGS.testspacelist = list(testspacelist1) argv = ('./program', FLAGS['testlist'].Serialize(), FLAGS['testspacelist'].Serialize()) argv = FLAGS(argv) self.assertEqual(FLAGS.testlist, testlist1) self.assertEqual(FLAGS.testspacelist, testspacelist1) testlist1 = ['aa some spaces', 'bb'] testspacelist1 = ['aa', 'bb,some,commas,', 'cc'] FLAGS.testlist = list(testlist1) FLAGS.testspacelist = list(testspacelist1) argv = ('./program', FLAGS['testlist'].Serialize(), FLAGS['testspacelist'].Serialize()) argv = FLAGS(argv) self.assertEqual(FLAGS.testlist, testlist1) self.assertEqual(FLAGS.testspacelist, testspacelist1) FLAGS.testlist = oldtestlist FLAGS.testspacelist = oldtestspacelist #################################### # Test flag-update: def ArgsString(): flagnames = FLAGS.RegisteredFlags() flagnames.sort() nonbool_flags = ['--%s %s' % (name, FLAGS.get(name, None)) for name in flagnames if not isinstance(FLAGS[name], gflags.BooleanFlag)] truebool_flags = ['--%s' % (name) for name in flagnames if isinstance(FLAGS[name], gflags.BooleanFlag) and FLAGS.get(name, None)] falsebool_flags = ['--no%s' % (name) for name in flagnames if isinstance(FLAGS[name], gflags.BooleanFlag) and not FLAGS.get(name, None)] return ' '.join(nonbool_flags + truebool_flags + falsebool_flags) argv = ('./program', '--repeat=3', '--name=giants', '--nodebug') FLAGS(argv) self.assertEqual(FLAGS.get('repeat', None), 3) self.assertEqual(FLAGS.get('name', None), 'giants') self.assertEqual(FLAGS.get('debug', None), 0) self.assertEqual(ArgsString(), "--kwery None " "--l 9223372032559808512 " "--letters ['a', 'b', 'c'] " "--m ['str1', 'str2'] --m_str ['str1', 'str2'] " "--name giants " "--numbers [1, 2, 3] " "--repeat 3 " "--s ['sing1'] --s_str ['sing1'] " "" "" "--testget4 None --testlist [] " "--testspacelist [] --x 10 " "--noexec --quack " "--test1 " "--testget1 --tmod_baz_x " "--no? --nodebug --nohelp --nohelpshort --nohelpxml --noq " "" "--notest0 --notestget2 --notestget3 --notestnone") argv = ('./program', '--debug', '--m_str=upd1', '-s', 'upd2') FLAGS(argv) self.assertEqual(FLAGS.get('repeat', None), 3) self.assertEqual(FLAGS.get('name', None), 'giants') self.assertEqual(FLAGS.get('debug', None), 1) # items appended to existing non-default value lists for --m/--m_str # new value overwrites default value (not appended to it) for --s/--s_str self.assertEqual(ArgsString(), "--kwery None " "--l 9223372032559808512 " "--letters ['a', 'b', 'c'] " "--m ['str1', 'str2', 'upd1'] " "--m_str ['str1', 'str2', 'upd1'] " "--name giants " "--numbers [1, 2, 3] " "--repeat 3 " "--s ['upd2'] --s_str ['upd2'] " "" "" "--testget4 None --testlist [] " "--testspacelist [] --x 10 " "--debug --noexec --quack " "--test1 " "--testget1 --tmod_baz_x " "--no? --nohelp --nohelpshort --nohelpxml --noq " "" "--notest0 --notestget2 --notestget3 --notestnone") #################################### # Test all kind of error conditions. # Duplicate flag detection try: gflags.DEFINE_boolean("run", 0, "runhelp", short_name='q') raise AssertionError("duplicate flag detection failed") except gflags.DuplicateFlag: pass # Duplicate short flag detection try: gflags.DEFINE_boolean("zoom1", 0, "runhelp z1", short_name='z') gflags.DEFINE_boolean("zoom2", 0, "runhelp z2", short_name='z') raise AssertionError("duplicate short flag detection failed") except gflags.DuplicateFlag, e: self.assertTrue("The flag 'z' is defined twice. " in e.args[0]) self.assertTrue("First from" in e.args[0]) self.assertTrue(", Second from" in e.args[0]) # Duplicate mixed flag detection try: gflags.DEFINE_boolean("short1", 0, "runhelp s1", short_name='s') gflags.DEFINE_boolean("s", 0, "runhelp s2") raise AssertionError("duplicate mixed flag detection failed") except gflags.DuplicateFlag, e: self.assertTrue("The flag 's' is defined twice. " in e.args[0]) self.assertTrue("First from" in e.args[0]) self.assertTrue(", Second from" in e.args[0]) # Check that duplicate flag detection detects definition sites # correctly. flagnames = ["repeated"] original_flags = gflags.FlagValues() gflags.DEFINE_boolean(flagnames[0], False, "Flag about to be repeated.", flag_values=original_flags) duplicate_flags = module_foo.DuplicateFlags(flagnames) try: original_flags.AppendFlagValues(duplicate_flags) except gflags.DuplicateFlagError, e: self.assertTrue("flags_unittest" in str(e)) self.assertTrue("module_foo" in str(e)) # Make sure allow_override works try: gflags.DEFINE_boolean("dup1", 0, "runhelp d11", short_name='u', allow_override=0) flag = FLAGS.FlagDict()['dup1'] self.assertEqual(flag.default, 0) gflags.DEFINE_boolean("dup1", 1, "runhelp d12", short_name='u', allow_override=1) flag = FLAGS.FlagDict()['dup1'] self.assertEqual(flag.default, 1) except gflags.DuplicateFlag: raise AssertionError("allow_override did not permit a flag duplication") # Make sure allow_override works try: gflags.DEFINE_boolean("dup2", 0, "runhelp d21", short_name='u', allow_override=1) flag = FLAGS.FlagDict()['dup2'] self.assertEqual(flag.default, 0) gflags.DEFINE_boolean("dup2", 1, "runhelp d22", short_name='u', allow_override=0) flag = FLAGS.FlagDict()['dup2'] self.assertEqual(flag.default, 1) except gflags.DuplicateFlag: raise AssertionError("allow_override did not permit a flag duplication") # Make sure allow_override doesn't work with None default try: gflags.DEFINE_boolean("dup3", 0, "runhelp d31", short_name='u3', allow_override=0) flag = FLAGS.FlagDict()['dup3'] self.assertEqual(flag.default, 0) gflags.DEFINE_boolean("dup3", None, "runhelp d32", short_name='u3', allow_override=1) raise AssertionError('Cannot override a flag with a default of None') except gflags.DuplicateFlagCannotPropagateNoneToSwig: pass # Make sure that re-importing a module does not cause a DuplicateFlagError # to be raised. try: sys.modules.pop( "flags_modules_for_testing.module_baz") import flags_modules_for_testing.module_baz except gflags.DuplicateFlagError: raise AssertionError("Module reimport caused flag duplication error") # Make sure that when we override, the help string gets updated correctly gflags.DEFINE_boolean("dup3", 0, "runhelp d31", short_name='u', allow_override=1) gflags.DEFINE_boolean("dup3", 1, "runhelp d32", short_name='u', allow_override=1) self.assert_(str(FLAGS).find('runhelp d31') == -1) self.assert_(str(FLAGS).find('runhelp d32') != -1) # Make sure AppendFlagValues works new_flags = gflags.FlagValues() gflags.DEFINE_boolean("new1", 0, "runhelp n1", flag_values=new_flags) gflags.DEFINE_boolean("new2", 0, "runhelp n2", flag_values=new_flags) self.assertEqual(len(new_flags.FlagDict()), 2) old_len = len(FLAGS.FlagDict()) FLAGS.AppendFlagValues(new_flags) self.assertEqual(len(FLAGS.FlagDict())-old_len, 2) self.assertEqual("new1" in FLAGS.FlagDict(), True) self.assertEqual("new2" in FLAGS.FlagDict(), True) # Then test that removing those flags works FLAGS.RemoveFlagValues(new_flags) self.assertEqual(len(FLAGS.FlagDict()), old_len) self.assertFalse("new1" in FLAGS.FlagDict()) self.assertFalse("new2" in FLAGS.FlagDict()) # Make sure AppendFlagValues works with flags with shortnames. new_flags = gflags.FlagValues() gflags.DEFINE_boolean("new3", 0, "runhelp n3", flag_values=new_flags) gflags.DEFINE_boolean("new4", 0, "runhelp n4", flag_values=new_flags, short_name="n4") self.assertEqual(len(new_flags.FlagDict()), 3) old_len = len(FLAGS.FlagDict()) FLAGS.AppendFlagValues(new_flags) self.assertEqual(len(FLAGS.FlagDict())-old_len, 3) self.assertTrue("new3" in FLAGS.FlagDict()) self.assertTrue("new4" in FLAGS.FlagDict()) self.assertTrue("n4" in FLAGS.FlagDict()) self.assertEqual(FLAGS.FlagDict()['n4'], FLAGS.FlagDict()['new4']) # Then test removing them FLAGS.RemoveFlagValues(new_flags) self.assertEqual(len(FLAGS.FlagDict()), old_len) self.assertFalse("new3" in FLAGS.FlagDict()) self.assertFalse("new4" in FLAGS.FlagDict()) self.assertFalse("n4" in FLAGS.FlagDict()) # Make sure AppendFlagValues fails on duplicates gflags.DEFINE_boolean("dup4", 0, "runhelp d41") new_flags = gflags.FlagValues() gflags.DEFINE_boolean("dup4", 0, "runhelp d42", flag_values=new_flags) try: FLAGS.AppendFlagValues(new_flags) raise AssertionError("ignore_copy was not set but caused no exception") except gflags.DuplicateFlag: pass # Integer out of bounds try: argv = ('./program', '--repeat=-4') FLAGS(argv) raise AssertionError('integer bounds exception not raised:' + str(FLAGS.repeat)) except gflags.IllegalFlagValue: pass # Non-integer try: argv = ('./program', '--repeat=2.5') FLAGS(argv) raise AssertionError("malformed integer value exception not raised") except gflags.IllegalFlagValue: pass # Missing required arugment try: argv = ('./program', '--name') FLAGS(argv) raise AssertionError("Flag argument required exception not raised") except gflags.FlagsError: pass # Non-boolean arguments for boolean try: argv = ('./program', '--debug=goofup') FLAGS(argv) raise AssertionError("Illegal flag value exception not raised") except gflags.IllegalFlagValue: pass try: argv = ('./program', '--debug=42') FLAGS(argv) raise AssertionError("Illegal flag value exception not raised") except gflags.IllegalFlagValue: pass # Non-numeric argument for integer flag --repeat try: argv = ('./program', '--repeat', 'Bob', 'extra') FLAGS(argv) raise AssertionError("Illegal flag value exception not raised") except gflags.IllegalFlagValue: pass # Test ModuleHelp(). helpstr = FLAGS.ModuleHelp(module_baz) expected_help = "\n" + module_baz.__name__ + ":" + """ --[no]tmod_baz_x: Boolean flag. (default: 'true')""" self.assertMultiLineEqual(expected_help, helpstr) # Test MainModuleHelp(). This must be part of test_flags because # it dpeends on dup1/2/3/etc being introduced first. helpstr = FLAGS.MainModuleHelp() expected_help = "\n" + sys.argv[0] + ':' + """ --[no]debug: debughelp (default: 'false') -u,--[no]dup1: runhelp d12 (default: 'true') -u,--[no]dup2: runhelp d22 (default: 'true') -u,--[no]dup3: runhelp d32 (default: 'true') --[no]dup4: runhelp d41 (default: 'false') --kwery: <who|what|why|where|when>: ? --l: how long to be (default: '9223372032559808512') (an integer) --letters: a list of letters (default: 'a,b,c') (a comma separated list) -m,--m_str: string option that can occur multiple times; repeat this option to specify a list of values (default: "['def1', 'def2']") --name: namehelp (default: 'Bob') --[no]noexec: boolean flag with no as prefix (default: 'true') --numbers: a list of numbers (default: '1,2,3') (a comma separated list) --[no]q: quiet mode (default: 'true') --[no]quack: superstring of 'q' (default: 'false') -r,--repeat: how many times to repeat (0-5) (default: '4') (a non-negative integer) -s,--s_str: string option that can occur multiple times; repeat this option to specify a list of values (default: "['sing1']") --[no]test0: test boolean parsing --[no]test1: test boolean parsing --[no]testget1: test parsing with defaults --[no]testget2: test parsing with defaults --[no]testget3: test parsing with defaults --testget4: test parsing with defaults (an integer) --testlist: test lists parsing (default: '') (a comma separated list) --[no]testnone: test boolean parsing --testspacelist: tests space lists parsing (default: '') (a whitespace separated list) --x: how eXtreme to be (default: '3') (an integer) -z,--[no]zoom1: runhelp z1 (default: 'false')""" # Insert the --help flags in their proper place. help_help = """\ -?,--[no]help: show this help --[no]helpshort: show usage only for this module --[no]helpxml: like --help, but generates XML output """ expected_help = expected_help.replace(' --kwery', help_help + ' --kwery') self.assertMultiLineEqual(expected_help, helpstr) class MultiNumericalFlagsTest(googletest.TestCase): def testMultiNumericalFlags(self): """Test multi_int and multi_float flags.""" int_defaults = [77, 88,] gflags.DEFINE_multi_int('m_int', int_defaults, 'integer option that can occur multiple times', short_name='mi') self.assertListEqual(FLAGS.get('m_int', None), int_defaults) argv = ('./program', '--m_int=-99', '--mi=101') FLAGS(argv) self.assertListEqual(FLAGS.get('m_int', None), [-99, 101,]) float_defaults = [2.2, 3] gflags.DEFINE_multi_float('m_float', float_defaults, 'float option that can occur multiple times', short_name='mf') for (expected, actual) in zip(float_defaults, FLAGS.get('m_float', None)): self.assertAlmostEquals(expected, actual) argv = ('./program', '--m_float=-17', '--mf=2.78e9') FLAGS(argv) expected_floats = [-17.0, 2.78e9] for (expected, actual) in zip(expected_floats, FLAGS.get('m_float', None)): self.assertAlmostEquals(expected, actual) def testSingleValueDefault(self): """Test multi_int and multi_float flags with a single default value.""" int_default = 77 gflags.DEFINE_multi_int('m_int1', int_default, 'integer option that can occur multiple times') self.assertListEqual(FLAGS.get('m_int1', None), [int_default]) float_default = 2.2 gflags.DEFINE_multi_float('m_float1', float_default, 'float option that can occur multiple times') actual = FLAGS.get('m_float1', None) self.assertEquals(1, len(actual)) self.assertAlmostEquals(actual[0], float_default) def testBadMultiNumericalFlags(self): """Test multi_int and multi_float flags with non-parseable values.""" # Test non-parseable defaults. self.assertRaisesWithRegexpMatch( gflags.IllegalFlagValue, 'flag --m_int2=abc: invalid literal for int\(\) with base 10: \'abc\'', gflags.DEFINE_multi_int, 'm_int2', ['abc'], 'desc') self.assertRaisesWithRegexpMatch( gflags.IllegalFlagValue, 'flag --m_float2=abc: invalid literal for float\(\): abc', gflags.DEFINE_multi_float, 'm_float2', ['abc'], 'desc') # Test non-parseable command line values. gflags.DEFINE_multi_int('m_int2', '77', 'integer option that can occur multiple times') argv = ('./program', '--m_int2=def') self.assertRaisesWithRegexpMatch( gflags.IllegalFlagValue, 'flag --m_int2=def: invalid literal for int\(\) with base 10: \'def\'', FLAGS, argv) gflags.DEFINE_multi_float('m_float2', 2.2, 'float option that can occur multiple times') argv = ('./program', '--m_float2=def') self.assertRaisesWithRegexpMatch( gflags.IllegalFlagValue, 'flag --m_float2=def: invalid literal for float\(\): def', FLAGS, argv) class UnicodeFlagsTest(googletest.TestCase): """Testing proper unicode support for flags.""" def testUnicodeDefaultAndHelpstring(self): gflags.DEFINE_string("unicode_str", "\xC3\x80\xC3\xBD".decode("utf-8"), "help:\xC3\xAA".decode("utf-8")) argv = ("./program",) FLAGS(argv) # should not raise any exceptions argv = ("./program", "--unicode_str=foo") FLAGS(argv) # should not raise any exceptions def testUnicodeInList(self): gflags.DEFINE_list("unicode_list", ["abc", "\xC3\x80".decode("utf-8"), "\xC3\xBD".decode("utf-8")], "help:\xC3\xAB".decode("utf-8")) argv = ("./program",) FLAGS(argv) # should not raise any exceptions argv = ("./program", "--unicode_list=hello,there") FLAGS(argv) # should not raise any exceptions def testXMLOutput(self): gflags.DEFINE_string("unicode1", "\xC3\x80\xC3\xBD".decode("utf-8"), "help:\xC3\xAC".decode("utf-8")) gflags.DEFINE_list("unicode2", ["abc", "\xC3\x80".decode("utf-8"), "\xC3\xBD".decode("utf-8")], "help:\xC3\xAD".decode("utf-8")) gflags.DEFINE_list("non_unicode", ["abc", "def", "ghi"], "help:\xC3\xAD".decode("utf-8")) outfile = cStringIO.StringIO() FLAGS.WriteHelpInXMLFormat(outfile) actual_output = outfile.getvalue() # The xml output is large, so we just check parts of it. self.assertTrue("<name>unicode1</name>\n" " <meaning>help:&#236;</meaning>\n" " <default>&#192;&#253;</default>\n" " <current>&#192;&#253;</current>" in actual_output) self.assertTrue("<name>unicode2</name>\n" " <meaning>help:&#237;</meaning>\n" " <default>abc,&#192;,&#253;</default>\n" " <current>[\'abc\', u\'\\xc0\', u\'\\xfd\']</current>" in actual_output) self.assertTrue("<name>non_unicode</name>\n" " <meaning>help:&#237;</meaning>\n" " <default>abc,def,ghi</default>\n" " <current>[\'abc\', \'def\', \'ghi\']</current>" in actual_output) class LoadFromFlagFileTest(googletest.TestCase): """Testing loading flags from a file and parsing them.""" def setUp(self): self.flag_values = gflags.FlagValues() # make sure we are using the old, stupid way of parsing flags. self.flag_values.UseGnuGetOpt(False) gflags.DEFINE_string('UnitTestMessage1', 'Foo!', 'You Add Here.', flag_values=self.flag_values) gflags.DEFINE_string('UnitTestMessage2', 'Bar!', 'Hello, Sailor!', flag_values=self.flag_values) gflags.DEFINE_boolean('UnitTestBoolFlag', 0, 'Some Boolean thing', flag_values=self.flag_values) gflags.DEFINE_integer('UnitTestNumber', 12345, 'Some integer', lower_bound=0, flag_values=self.flag_values) gflags.DEFINE_list('UnitTestList', "1,2,3", 'Some list', flag_values=self.flag_values) self.files_to_delete = [] def tearDown(self): self._RemoveTestFiles() def _SetupTestFiles(self): """ Creates and sets up some dummy flagfile files with bogus flags""" # Figure out where to create temporary files tmp_path = '/tmp/flags_unittest' if os.path.exists(tmp_path): shutil.rmtree(tmp_path) os.makedirs(tmp_path) try: tmp_flag_file_1 = open(tmp_path + '/UnitTestFile1.tst', 'w') tmp_flag_file_2 = open(tmp_path + '/UnitTestFile2.tst', 'w') tmp_flag_file_3 = open(tmp_path + '/UnitTestFile3.tst', 'w') tmp_flag_file_4 = open(tmp_path + '/UnitTestFile4.tst', 'w') except IOError, e_msg: print e_msg print 'FAIL\n File Creation problem in Unit Test' sys.exit(1) # put some dummy flags in our test files tmp_flag_file_1.write('#A Fake Comment\n') tmp_flag_file_1.write('--UnitTestMessage1=tempFile1!\n') tmp_flag_file_1.write('\n') tmp_flag_file_1.write('--UnitTestNumber=54321\n') tmp_flag_file_1.write('--noUnitTestBoolFlag\n') file_list = [tmp_flag_file_1.name] # this one includes test file 1 tmp_flag_file_2.write('//A Different Fake Comment\n') tmp_flag_file_2.write('--flagfile=%s\n' % tmp_flag_file_1.name) tmp_flag_file_2.write('--UnitTestMessage2=setFromTempFile2\n') tmp_flag_file_2.write('\t\t\n') tmp_flag_file_2.write('--UnitTestNumber=6789a\n') file_list.append(tmp_flag_file_2.name) # this file points to itself tmp_flag_file_3.write('--flagfile=%s\n' % tmp_flag_file_3.name) tmp_flag_file_3.write('--UnitTestMessage1=setFromTempFile3\n') tmp_flag_file_3.write('#YAFC\n') tmp_flag_file_3.write('--UnitTestBoolFlag\n') file_list.append(tmp_flag_file_3.name) # this file is unreadable tmp_flag_file_4.write('--flagfile=%s\n' % tmp_flag_file_3.name) tmp_flag_file_4.write('--UnitTestMessage1=setFromTempFile3\n') tmp_flag_file_4.write('--UnitTestMessage1=setFromTempFile3\n') os.chmod(tmp_path + '/UnitTestFile4.tst', 0) file_list.append(tmp_flag_file_4.name) tmp_flag_file_1.close() tmp_flag_file_2.close() tmp_flag_file_3.close() tmp_flag_file_4.close() self.files_to_delete = file_list return file_list # these are just the file names # end SetupFiles def def _RemoveTestFiles(self): """Closes the files we just created. tempfile deletes them for us """ for file_name in self.files_to_delete: try: os.remove(file_name) except OSError, e_msg: print '%s\n, Problem deleting test file' % e_msg #end RemoveTestFiles def def _ReadFlagsFromFiles(self, argv, force_gnu): return argv[:1] + self.flag_values.ReadFlagsFromFiles(argv[1:], force_gnu=force_gnu) #### Flagfile Unit Tests #### def testMethod_flagfiles_1(self): """ Test trivial case with no flagfile based options. """ fake_cmd_line = 'fooScript --UnitTestBoolFlag' fake_argv = fake_cmd_line.split(' ') self.flag_values(fake_argv) self.assertEqual( self.flag_values.UnitTestBoolFlag, 1) self.assertEqual( fake_argv, self._ReadFlagsFromFiles(fake_argv, False)) # end testMethodOne def testMethod_flagfiles_2(self): """Tests parsing one file + arguments off simulated argv""" tmp_files = self._SetupTestFiles() # specify our temp file on the fake cmd line fake_cmd_line = 'fooScript --q --flagfile=%s' % tmp_files[0] fake_argv = fake_cmd_line.split(' ') # We should see the original cmd line with the file's contents spliced in. # Flags from the file will appear in the order order they are sepcified # in the file, in the same position as the flagfile argument. expected_results = ['fooScript', '--q', '--UnitTestMessage1=tempFile1!', '--UnitTestNumber=54321', '--noUnitTestBoolFlag'] test_results = self._ReadFlagsFromFiles(fake_argv, False) self.assertEqual(expected_results, test_results) # end testTwo def def testMethod_flagfiles_3(self): """Tests parsing nested files + arguments of simulated argv""" tmp_files = self._SetupTestFiles() # specify our temp file on the fake cmd line fake_cmd_line = ('fooScript --UnitTestNumber=77 --flagfile=%s' % tmp_files[1]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--UnitTestNumber=77', '--UnitTestMessage1=tempFile1!', '--UnitTestNumber=54321', '--noUnitTestBoolFlag', '--UnitTestMessage2=setFromTempFile2', '--UnitTestNumber=6789a'] test_results = self._ReadFlagsFromFiles(fake_argv, False) self.assertEqual(expected_results, test_results) # end testThree def def testMethod_flagfiles_4(self): """Tests parsing self-referential files + arguments of simulated argv. This test should print a warning to stderr of some sort. """ tmp_files = self._SetupTestFiles() # specify our temp file on the fake cmd line fake_cmd_line = ('fooScript --flagfile=%s --noUnitTestBoolFlag' % tmp_files[2]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--UnitTestMessage1=setFromTempFile3', '--UnitTestBoolFlag', '--noUnitTestBoolFlag' ] test_results = self._ReadFlagsFromFiles(fake_argv, False) self.assertEqual(expected_results, test_results) def testMethod_flagfiles_5(self): """Test that --flagfile parsing respects the '--' end-of-options marker.""" tmp_files = self._SetupTestFiles() # specify our temp file on the fake cmd line fake_cmd_line = 'fooScript --SomeFlag -- --flagfile=%s' % tmp_files[0] fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--SomeFlag', '--', '--flagfile=%s' % tmp_files[0]] test_results = self._ReadFlagsFromFiles(fake_argv, False) self.assertEqual(expected_results, test_results) def testMethod_flagfiles_6(self): """Test that --flagfile parsing stops at non-options (non-GNU behavior).""" tmp_files = self._SetupTestFiles() # specify our temp file on the fake cmd line fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s' % tmp_files[0]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--SomeFlag', 'some_arg', '--flagfile=%s' % tmp_files[0]] test_results = self._ReadFlagsFromFiles(fake_argv, False) self.assertEqual(expected_results, test_results) def testMethod_flagfiles_7(self): """Test that --flagfile parsing skips over a non-option (GNU behavior).""" self.flag_values.UseGnuGetOpt() tmp_files = self._SetupTestFiles() # specify our temp file on the fake cmd line fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s' % tmp_files[0]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--SomeFlag', 'some_arg', '--UnitTestMessage1=tempFile1!', '--UnitTestNumber=54321', '--noUnitTestBoolFlag'] test_results = self._ReadFlagsFromFiles(fake_argv, False) self.assertEqual(expected_results, test_results) def testMethod_flagfiles_8(self): """Test that --flagfile parsing respects force_gnu=True.""" tmp_files = self._SetupTestFiles() # specify our temp file on the fake cmd line fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s' % tmp_files[0]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--SomeFlag', 'some_arg', '--UnitTestMessage1=tempFile1!', '--UnitTestNumber=54321', '--noUnitTestBoolFlag'] test_results = self._ReadFlagsFromFiles(fake_argv, True) self.assertEqual(expected_results, test_results) def testMethod_flagfiles_NoPermissions(self): """Test that --flagfile raises except on file that is unreadable.""" tmp_files = self._SetupTestFiles() # specify our temp file on the fake cmd line fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s' % tmp_files[3]) fake_argv = fake_cmd_line.split(' ') self.assertRaises(gflags.CantOpenFlagFileError, self._ReadFlagsFromFiles, fake_argv, True) def testMethod_flagfiles_NotFound(self): """Test that --flagfile raises except on file that does not exist.""" tmp_files = self._SetupTestFiles() # specify our temp file on the fake cmd line fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%sNOTEXIST' % tmp_files[3]) fake_argv = fake_cmd_line.split(' ') self.assertRaises(gflags.CantOpenFlagFileError, self._ReadFlagsFromFiles, fake_argv, True) def test_flagfiles_user_path_expansion(self): """Test that user directory referenced paths (ie. ~/foo) are correctly expanded. This test depends on whatever account's running the unit test to have read/write access to their own home directory, otherwise it'll FAIL. """ fake_flagfile_item_style_1 = '--flagfile=~/foo.file' fake_flagfile_item_style_2 = '-flagfile=~/foo.file' expected_results = os.path.expanduser('~/foo.file') test_results = self.flag_values.ExtractFilename(fake_flagfile_item_style_1) self.assertEqual(expected_results, test_results) test_results = self.flag_values.ExtractFilename(fake_flagfile_item_style_2) self.assertEqual(expected_results, test_results) # end testFour def def test_no_touchy_non_flags(self): """ Test that the flags parser does not mutilate arguments which are not supposed to be flags """ fake_argv = ['fooScript', '--UnitTestBoolFlag', 'command', '--command_arg1', '--UnitTestBoom', '--UnitTestB'] argv = self.flag_values(fake_argv) self.assertEqual(argv, fake_argv[:1] + fake_argv[2:]) def test_parse_flags_after_args_if_using_gnu_getopt(self): """ Test that flags given after arguments are parsed if using gnu_getopt. """ self.flag_values.UseGnuGetOpt() fake_argv = ['fooScript', '--UnitTestBoolFlag', 'command', '--UnitTestB'] argv = self.flag_values(fake_argv) self.assertEqual(argv, ['fooScript', 'command']) def test_SetDefault(self): """ Test changing flag defaults. """ # Test that SetDefault changes both the default and the value, # and that the value is changed when one is given as an option. self.flag_values['UnitTestMessage1'].SetDefault('New value') self.assertEqual(self.flag_values.UnitTestMessage1, 'New value') self.assertEqual(self.flag_values['UnitTestMessage1'].default_as_str, "'New value'") self.flag_values([ 'dummyscript', '--UnitTestMessage1=Newer value' ]) self.assertEqual(self.flag_values.UnitTestMessage1, 'Newer value') # Test that setting the default to None works correctly. self.flag_values['UnitTestNumber'].SetDefault(None) self.assertEqual(self.flag_values.UnitTestNumber, None) self.assertEqual(self.flag_values['UnitTestNumber'].default_as_str, None) self.flag_values([ 'dummyscript', '--UnitTestNumber=56' ]) self.assertEqual(self.flag_values.UnitTestNumber, 56) # Test that setting the default to zero works correctly. self.flag_values['UnitTestNumber'].SetDefault(0) self.assertEqual(self.flag_values.UnitTestNumber, 0) self.assertEqual(self.flag_values['UnitTestNumber'].default_as_str, "'0'") self.flag_values([ 'dummyscript', '--UnitTestNumber=56' ]) self.assertEqual(self.flag_values.UnitTestNumber, 56) # Test that setting the default to "" works correctly. self.flag_values['UnitTestMessage1'].SetDefault("") self.assertEqual(self.flag_values.UnitTestMessage1, "") self.assertEqual(self.flag_values['UnitTestMessage1'].default_as_str, "''") self.flag_values([ 'dummyscript', '--UnitTestMessage1=fifty-six' ]) self.assertEqual(self.flag_values.UnitTestMessage1, "fifty-six") # Test that setting the default to false works correctly. self.flag_values['UnitTestBoolFlag'].SetDefault(False) self.assertEqual(self.flag_values.UnitTestBoolFlag, False) self.assertEqual(self.flag_values['UnitTestBoolFlag'].default_as_str, "'false'") self.flag_values([ 'dummyscript', '--UnitTestBoolFlag=true' ]) self.assertEqual(self.flag_values.UnitTestBoolFlag, True) # Test that setting a list default works correctly. self.flag_values['UnitTestList'].SetDefault('4,5,6') self.assertEqual(self.flag_values.UnitTestList, ['4', '5', '6']) self.assertEqual(self.flag_values['UnitTestList'].default_as_str, "'4,5,6'") self.flag_values([ 'dummyscript', '--UnitTestList=7,8,9' ]) self.assertEqual(self.flag_values.UnitTestList, ['7', '8', '9']) # Test that setting invalid defaults raises exceptions self.assertRaises(gflags.IllegalFlagValue, self.flag_values['UnitTestNumber'].SetDefault, 'oops') self.assertRaises(gflags.IllegalFlagValue, self.flag_values.SetDefault, 'UnitTestNumber', -1) class FlagsParsingTest(googletest.TestCase): """Testing different aspects of parsing: '-f' vs '--flag', etc.""" def setUp(self): self.flag_values = gflags.FlagValues() def testMethod_ShortestUniquePrefixes(self): """Test FlagValues.ShortestUniquePrefixes""" gflags.DEFINE_string('a', '', '', flag_values=self.flag_values) gflags.DEFINE_string('abc', '', '', flag_values=self.flag_values) gflags.DEFINE_string('common_a_string', '', '', flag_values=self.flag_values) gflags.DEFINE_boolean('common_b_boolean', 0, '', flag_values=self.flag_values) gflags.DEFINE_boolean('common_c_boolean', 0, '', flag_values=self.flag_values) gflags.DEFINE_boolean('common', 0, '', flag_values=self.flag_values) gflags.DEFINE_integer('commonly', 0, '', flag_values=self.flag_values) gflags.DEFINE_boolean('zz', 0, '', flag_values=self.flag_values) gflags.DEFINE_integer('nozz', 0, '', flag_values=self.flag_values) shorter_flags = self.flag_values.ShortestUniquePrefixes( self.flag_values.FlagDict()) expected_results = {'nocommon_b_boolean': 'nocommon_b', 'common_c_boolean': 'common_c', 'common_b_boolean': 'common_b', 'a': 'a', 'abc': 'ab', 'zz': 'z', 'nozz': 'nozz', 'common_a_string': 'common_a', 'commonly': 'commonl', 'nocommon_c_boolean': 'nocommon_c', 'nocommon': 'nocommon', 'common': 'common'} for name, shorter in expected_results.iteritems(): self.assertEquals(shorter_flags[name], shorter) self.flag_values.__delattr__('a') self.flag_values.__delattr__('abc') self.flag_values.__delattr__('common_a_string') self.flag_values.__delattr__('common_b_boolean') self.flag_values.__delattr__('common_c_boolean') self.flag_values.__delattr__('common') self.flag_values.__delattr__('commonly') self.flag_values.__delattr__('zz') self.flag_values.__delattr__('nozz') def test_twodasharg_first(self): gflags.DEFINE_string("twodash_name", "Bob", "namehelp", flag_values=self.flag_values) gflags.DEFINE_string("twodash_blame", "Rob", "blamehelp", flag_values=self.flag_values) argv = ('./program', '--', '--twodash_name=Harry') argv = self.flag_values(argv) self.assertEqual('Bob', self.flag_values.twodash_name) self.assertEqual(argv[1], '--twodash_name=Harry') def test_twodasharg_middle(self): gflags.DEFINE_string("twodash2_name", "Bob", "namehelp", flag_values=self.flag_values) gflags.DEFINE_string("twodash2_blame", "Rob", "blamehelp", flag_values=self.flag_values) argv = ('./program', '--twodash2_blame=Larry', '--', '--twodash2_name=Harry') argv = self.flag_values(argv) self.assertEqual('Bob', self.flag_values.twodash2_name) self.assertEqual('Larry', self.flag_values.twodash2_blame) self.assertEqual(argv[1], '--twodash2_name=Harry') def test_onedasharg_first(self): gflags.DEFINE_string("onedash_name", "Bob", "namehelp", flag_values=self.flag_values) gflags.DEFINE_string("onedash_blame", "Rob", "blamehelp", flag_values=self.flag_values) argv = ('./program', '-', '--onedash_name=Harry') argv = self.flag_values(argv) self.assertEqual(argv[1], '-') # TODO(csilvers): we should still parse --onedash_name=Harry as a # flag, but currently we don't (we stop flag processing as soon as # we see the first non-flag). # - This requires gnu_getopt from Python 2.3+ see FLAGS.UseGnuGetOpt() def test_unrecognized_flags(self): gflags.DEFINE_string("name", "Bob", "namehelp", flag_values=self.flag_values) # Unknown flag --nosuchflag try: argv = ('./program', '--nosuchflag', '--name=Bob', 'extra') self.flag_values(argv) raise AssertionError("Unknown flag exception not raised") except gflags.UnrecognizedFlag, e: assert e.flagname == 'nosuchflag' assert e.flagvalue == '--nosuchflag' # Unknown flag -w (short option) try: argv = ('./program', '-w', '--name=Bob', 'extra') self.flag_values(argv) raise AssertionError("Unknown flag exception not raised") except gflags.UnrecognizedFlag, e: assert e.flagname == 'w' assert e.flagvalue == '-w' # Unknown flag --nosuchflagwithparam=foo try: argv = ('./program', '--nosuchflagwithparam=foo', '--name=Bob', 'extra') self.flag_values(argv) raise AssertionError("Unknown flag exception not raised") except gflags.UnrecognizedFlag, e: assert e.flagname == 'nosuchflagwithparam' assert e.flagvalue == '--nosuchflagwithparam=foo' # Allow unknown flag --nosuchflag if specified with undefok argv = ('./program', '--nosuchflag', '--name=Bob', '--undefok=nosuchflag', 'extra') argv = self.flag_values(argv) assert len(argv) == 2, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" assert argv[1]=='extra', "extra argument not preserved" # Allow unknown flag --noboolflag if undefok=boolflag is specified argv = ('./program', '--noboolflag', '--name=Bob', '--undefok=boolflag', 'extra') argv = self.flag_values(argv) assert len(argv) == 2, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" assert argv[1]=='extra', "extra argument not preserved" # But not if the flagname is misspelled: try: argv = ('./program', '--nosuchflag', '--name=Bob', '--undefok=nosuchfla', 'extra') self.flag_values(argv) raise AssertionError("Unknown flag exception not raised") except gflags.UnrecognizedFlag, e: assert e.flagname == 'nosuchflag' try: argv = ('./program', '--nosuchflag', '--name=Bob', '--undefok=nosuchflagg', 'extra') self.flag_values(argv) raise AssertionError("Unknown flag exception not raised") except gflags.UnrecognizedFlag, e: assert e.flagname == 'nosuchflag' # Allow unknown short flag -w if specified with undefok argv = ('./program', '-w', '--name=Bob', '--undefok=w', 'extra') argv = self.flag_values(argv) assert len(argv) == 2, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" assert argv[1]=='extra', "extra argument not preserved" # Allow unknown flag --nosuchflagwithparam=foo if specified # with undefok argv = ('./program', '--nosuchflagwithparam=foo', '--name=Bob', '--undefok=nosuchflagwithparam', 'extra') argv = self.flag_values(argv) assert len(argv) == 2, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" assert argv[1]=='extra', "extra argument not preserved" # Even if undefok specifies multiple flags argv = ('./program', '--nosuchflag', '-w', '--nosuchflagwithparam=foo', '--name=Bob', '--undefok=nosuchflag,w,nosuchflagwithparam', 'extra') argv = self.flag_values(argv) assert len(argv) == 2, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" assert argv[1]=='extra', "extra argument not preserved" # However, not if undefok doesn't specify the flag try: argv = ('./program', '--nosuchflag', '--name=Bob', '--undefok=another_such', 'extra') self.flag_values(argv) raise AssertionError("Unknown flag exception not raised") except gflags.UnrecognizedFlag, e: assert e.flagname == 'nosuchflag' # Make sure --undefok doesn't mask other option errors. try: # Provide an option requiring a parameter but not giving it one. argv = ('./program', '--undefok=name', '--name') self.flag_values(argv) raise AssertionError("Missing option parameter exception not raised") except gflags.UnrecognizedFlag: raise AssertionError("Wrong kind of error exception raised") except gflags.FlagsError: pass # Test --undefok <list> argv = ('./program', '--nosuchflag', '-w', '--nosuchflagwithparam=foo', '--name=Bob', '--undefok', 'nosuchflag,w,nosuchflagwithparam', 'extra') argv = self.flag_values(argv) assert len(argv) == 2, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" assert argv[1]=='extra', "extra argument not preserved" class NonGlobalFlagsTest(googletest.TestCase): def test_nonglobal_flags(self): """Test use of non-global FlagValues""" nonglobal_flags = gflags.FlagValues() gflags.DEFINE_string("nonglobal_flag", "Bob", "flaghelp", nonglobal_flags) argv = ('./program', '--nonglobal_flag=Mary', 'extra') argv = nonglobal_flags(argv) assert len(argv) == 2, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" assert argv[1]=='extra', "extra argument not preserved" assert nonglobal_flags['nonglobal_flag'].value == 'Mary' def test_unrecognized_nonglobal_flags(self): """Test unrecognized non-global flags""" nonglobal_flags = gflags.FlagValues() argv = ('./program', '--nosuchflag') try: argv = nonglobal_flags(argv) raise AssertionError("Unknown flag exception not raised") except gflags.UnrecognizedFlag, e: assert e.flagname == 'nosuchflag' pass argv = ('./program', '--nosuchflag', '--undefok=nosuchflag') argv = nonglobal_flags(argv) assert len(argv) == 1, "wrong number of arguments pulled" assert argv[0]=='./program', "program name not preserved" def test_create_flag_errors(self): # Since the exception classes are exposed, nothing stops users # from creating their own instances. This test makes sure that # people modifying the flags module understand that the external # mechanisms for creating the exceptions should continue to work. e = gflags.FlagsError() e = gflags.FlagsError("message") e = gflags.DuplicateFlag() e = gflags.DuplicateFlag("message") e = gflags.IllegalFlagValue() e = gflags.IllegalFlagValue("message") e = gflags.UnrecognizedFlag() e = gflags.UnrecognizedFlag("message") def testFlagValuesDelAttr(self): """Checks that del self.flag_values.flag_id works.""" default_value = 'default value for testFlagValuesDelAttr' # 1. Declare and delete a flag with no short name. flag_values = gflags.FlagValues() gflags.DEFINE_string('delattr_foo', default_value, 'A simple flag.', flag_values=flag_values) self.assertEquals(flag_values.delattr_foo, default_value) flag_obj = flag_values['delattr_foo'] # We also check that _FlagIsRegistered works as expected :) self.assertTrue(flag_values._FlagIsRegistered(flag_obj)) del flag_values.delattr_foo self.assertFalse('delattr_foo' in flag_values.FlagDict()) self.assertFalse(flag_values._FlagIsRegistered(flag_obj)) # If the previous del FLAGS.delattr_foo did not work properly, the # next definition will trigger a redefinition error. gflags.DEFINE_integer('delattr_foo', 3, 'A simple flag.', flag_values=flag_values) del flag_values.delattr_foo self.assertFalse('delattr_foo' in flag_values.RegisteredFlags()) # 2. Declare and delete a flag with a short name. gflags.DEFINE_string('delattr_bar', default_value, 'flag with short name', short_name='x5', flag_values=flag_values) flag_obj = flag_values['delattr_bar'] self.assertTrue(flag_values._FlagIsRegistered(flag_obj)) del flag_values.x5 self.assertTrue(flag_values._FlagIsRegistered(flag_obj)) del flag_values.delattr_bar self.assertFalse(flag_values._FlagIsRegistered(flag_obj)) # 3. Just like 2, but del flag_values.name last gflags.DEFINE_string('delattr_bar', default_value, 'flag with short name', short_name='x5', flag_values=flag_values) flag_obj = flag_values['delattr_bar'] self.assertTrue(flag_values._FlagIsRegistered(flag_obj)) del flag_values.delattr_bar self.assertTrue(flag_values._FlagIsRegistered(flag_obj)) del flag_values.x5 self.assertFalse(flag_values._FlagIsRegistered(flag_obj)) self.assertFalse('delattr_bar' in flag_values.RegisteredFlags()) self.assertFalse('x5' in flag_values.RegisteredFlags()) class KeyFlagsTest(googletest.TestCase): def setUp(self): self.flag_values = gflags.FlagValues() def _GetNamesOfDefinedFlags(self, module, flag_values): """Returns the list of names of flags defined by a module. Auxiliary for the testKeyFlags* methods. Args: module: A module object or a string module name. flag_values: A FlagValues object. Returns: A list of strings. """ return [f.name for f in flag_values._GetFlagsDefinedByModule(module)] def _GetNamesOfKeyFlags(self, module, flag_values): """Returns the list of names of key flags for a module. Auxiliary for the testKeyFlags* methods. Args: module: A module object or a string module name. flag_values: A FlagValues object. Returns: A list of strings. """ return [f.name for f in flag_values._GetKeyFlagsForModule(module)] def _AssertListsHaveSameElements(self, list_1, list_2): # Checks that two lists have the same elements with the same # multiplicity, in possibly different order. list_1 = list(list_1) list_1.sort() list_2 = list(list_2) list_2.sort() self.assertListEqual(list_1, list_2) def testKeyFlags(self): # Before starting any testing, make sure no flags are already # defined for module_foo and module_bar. self.assertListEqual(self._GetNamesOfKeyFlags(module_foo, self.flag_values), []) self.assertListEqual(self._GetNamesOfKeyFlags(module_bar, self.flag_values), []) self.assertListEqual(self._GetNamesOfDefinedFlags(module_foo, self.flag_values), []) self.assertListEqual(self._GetNamesOfDefinedFlags(module_bar, self.flag_values), []) # Defines a few flags in module_foo and module_bar. module_foo.DefineFlags(flag_values=self.flag_values) try: # Part 1. Check that all flags defined by module_foo are key for # that module, and similarly for module_bar. for module in [module_foo, module_bar]: self._AssertListsHaveSameElements( self.flag_values._GetFlagsDefinedByModule(module), self.flag_values._GetKeyFlagsForModule(module)) # Also check that each module defined the expected flags. self._AssertListsHaveSameElements( self._GetNamesOfDefinedFlags(module, self.flag_values), module.NamesOfDefinedFlags()) # Part 2. Check that gflags.DECLARE_key_flag works fine. # Declare that some flags from module_bar are key for # module_foo. module_foo.DeclareKeyFlags(flag_values=self.flag_values) # Check that module_foo has the expected list of defined flags. self._AssertListsHaveSameElements( self._GetNamesOfDefinedFlags(module_foo, self.flag_values), module_foo.NamesOfDefinedFlags()) # Check that module_foo has the expected list of key flags. self._AssertListsHaveSameElements( self._GetNamesOfKeyFlags(module_foo, self.flag_values), module_foo.NamesOfDeclaredKeyFlags()) # Part 3. Check that gflags.ADOPT_module_key_flags works fine. # Trigger a call to gflags.ADOPT_module_key_flags(module_bar) # inside module_foo. This should declare a few more key # flags in module_foo. module_foo.DeclareExtraKeyFlags(flag_values=self.flag_values) # Check that module_foo has the expected list of key flags. self._AssertListsHaveSameElements( self._GetNamesOfKeyFlags(module_foo, self.flag_values), module_foo.NamesOfDeclaredKeyFlags() + module_foo.NamesOfDeclaredExtraKeyFlags()) finally: module_foo.RemoveFlags(flag_values=self.flag_values) def testKeyFlagsWithNonDefaultFlagValuesObject(self): # Check that key flags work even when we use a FlagValues object # that is not the default gflags.self.flag_values object. Otherwise, this # test is similar to testKeyFlags, but it uses only module_bar. # The other test module (module_foo) uses only the default values # for the flag_values keyword arguments. This way, testKeyFlags # and this method test both the default FlagValues, the explicitly # specified one, and a mixed usage of the two. # A brand-new FlagValues object, to use instead of gflags.self.flag_values. fv = gflags.FlagValues() # Before starting any testing, make sure no flags are already # defined for module_foo and module_bar. self.assertListEqual( self._GetNamesOfKeyFlags(module_bar, fv), []) self.assertListEqual( self._GetNamesOfDefinedFlags(module_bar, fv), []) module_bar.DefineFlags(flag_values=fv) # Check that all flags defined by module_bar are key for that # module, and that module_bar defined the expected flags. self._AssertListsHaveSameElements( fv._GetFlagsDefinedByModule(module_bar), fv._GetKeyFlagsForModule(module_bar)) self._AssertListsHaveSameElements( self._GetNamesOfDefinedFlags(module_bar, fv), module_bar.NamesOfDefinedFlags()) # Pick two flags from module_bar, declare them as key for the # current (i.e., main) module (via gflags.DECLARE_key_flag), and # check that we get the expected effect. The important thing is # that we always use flags_values=fv (instead of the default # self.flag_values). main_module = gflags._GetMainModule() names_of_flags_defined_by_bar = module_bar.NamesOfDefinedFlags() flag_name_0 = names_of_flags_defined_by_bar[0] flag_name_2 = names_of_flags_defined_by_bar[2] gflags.DECLARE_key_flag(flag_name_0, flag_values=fv) self._AssertListsHaveSameElements( self._GetNamesOfKeyFlags(main_module, fv), [flag_name_0]) gflags.DECLARE_key_flag(flag_name_2, flag_values=fv) self._AssertListsHaveSameElements( self._GetNamesOfKeyFlags(main_module, fv), [flag_name_0, flag_name_2]) # Try with a special (not user-defined) flag too: gflags.DECLARE_key_flag('undefok', flag_values=fv) self._AssertListsHaveSameElements( self._GetNamesOfKeyFlags(main_module, fv), [flag_name_0, flag_name_2, 'undefok']) gflags.ADOPT_module_key_flags(module_bar, fv) self._AssertListsHaveSameElements( self._GetNamesOfKeyFlags(main_module, fv), names_of_flags_defined_by_bar + ['undefok']) # Adopt key flags from the flags module itself. gflags.ADOPT_module_key_flags(gflags, flag_values=fv) self._AssertListsHaveSameElements( self._GetNamesOfKeyFlags(main_module, fv), names_of_flags_defined_by_bar + ['flagfile', 'undefok']) def testMainModuleHelpWithKeyFlags(self): # Similar to test_main_module_help, but this time we make sure to # declare some key flags. # Safety check that the main module does not declare any flags # at the beginning of this test. expected_help = '' self.assertMultiLineEqual(expected_help, self.flag_values.MainModuleHelp()) # Define one flag in this main module and some flags in modules # a and b. Also declare one flag from module a and one flag # from module b as key flags for the main module. gflags.DEFINE_integer('main_module_int_fg', 1, 'Integer flag in the main module.', flag_values=self.flag_values) try: main_module_int_fg_help = ( " --main_module_int_fg: Integer flag in the main module.\n" " (default: '1')\n" " (an integer)") expected_help += "\n%s:\n%s" % (sys.argv[0], main_module_int_fg_help) self.assertMultiLineEqual(expected_help, self.flag_values.MainModuleHelp()) # The following call should be a no-op: any flag declared by a # module is automatically key for that module. gflags.DECLARE_key_flag('main_module_int_fg', flag_values=self.flag_values) self.assertMultiLineEqual(expected_help, self.flag_values.MainModuleHelp()) # The definition of a few flags in an imported module should not # change the main module help. module_foo.DefineFlags(flag_values=self.flag_values) self.assertMultiLineEqual(expected_help, self.flag_values.MainModuleHelp()) gflags.DECLARE_key_flag('tmod_foo_bool', flag_values=self.flag_values) tmod_foo_bool_help = ( " --[no]tmod_foo_bool: Boolean flag from module foo.\n" " (default: 'true')") expected_help += "\n" + tmod_foo_bool_help self.assertMultiLineEqual(expected_help, self.flag_values.MainModuleHelp()) gflags.DECLARE_key_flag('tmod_bar_z', flag_values=self.flag_values) tmod_bar_z_help = ( " --[no]tmod_bar_z: Another boolean flag from module bar.\n" " (default: 'false')") # Unfortunately, there is some flag sorting inside # MainModuleHelp, so we can't keep incrementally extending # the expected_help string ... expected_help = ("\n%s:\n%s\n%s\n%s" % (sys.argv[0], main_module_int_fg_help, tmod_bar_z_help, tmod_foo_bool_help)) self.assertMultiLineEqual(self.flag_values.MainModuleHelp(), expected_help) finally: # At the end, delete all the flag information we created. self.flag_values.__delattr__('main_module_int_fg') module_foo.RemoveFlags(flag_values=self.flag_values) def test_ADOPT_module_key_flags(self): # Check that ADOPT_module_key_flags raises an exception when # called with a module name (as opposed to a module object). self.assertRaises(gflags.FlagsError, gflags.ADOPT_module_key_flags, 'pyglib.app') class GetCallingModuleTest(googletest.TestCase): """Test whether we correctly determine the module which defines the flag.""" def test_GetCallingModule(self): self.assertEqual(gflags._GetCallingModule(), sys.argv[0]) self.assertEqual( module_foo.GetModuleName(), 'flags_modules_for_testing.module_foo') self.assertEqual( module_bar.GetModuleName(), 'flags_modules_for_testing.module_bar') # We execute the following exec statements for their side-effect # (i.e., not raising an error). They emphasize the case that not # all code resides in one of the imported modules: Python is a # really dynamic language, where we can dynamically construct some # code and execute it. code = ("import gflags\n" "module_name = gflags._GetCallingModule()") exec(code) # Next two exec statements executes code with a global environment # that is different from the global environment of any imported # module. exec(code, {}) # vars(self) returns a dictionary corresponding to the symbol # table of the self object. dict(...) makes a distinct copy of # this dictionary, such that any new symbol definition by the # exec-ed code (e.g., import flags, module_name = ...) does not # affect the symbol table of self. exec(code, dict(vars(self))) # Next test is actually more involved: it checks not only that # _GetCallingModule does not crash inside exec code, it also checks # that it returns the expected value: the code executed via exec # code is treated as being executed by the current module. We # check it twice: first time by executing exec from the main # module, second time by executing it from module_bar. global_dict = {} exec(code, global_dict) self.assertEqual(global_dict['module_name'], sys.argv[0]) global_dict = {} module_bar.ExecuteCode(code, global_dict) self.assertEqual( global_dict['module_name'], 'flags_modules_for_testing.module_bar') def test_GetCallingModuleWithIteritemsError(self): # This test checks that _GetCallingModule is using # sys.modules.items(), instead of .iteritems(). orig_sys_modules = sys.modules # Mock sys.modules: simulates error produced by importing a module # in paralel with our iteration over sys.modules.iteritems(). class SysModulesMock(dict): def __init__(self, original_content): dict.__init__(self, original_content) def iteritems(self): # Any dictionary method is fine, but not .iteritems(). raise RuntimeError('dictionary changed size during iteration') sys.modules = SysModulesMock(orig_sys_modules) try: # _GetCallingModule should still work as expected: self.assertEqual(gflags._GetCallingModule(), sys.argv[0]) self.assertEqual( module_foo.GetModuleName(), 'flags_modules_for_testing.module_foo') finally: sys.modules = orig_sys_modules class FindModuleTest(googletest.TestCase): """Testing methods that find a module that defines a given flag.""" def testFindModuleDefiningFlag(self): self.assertEqual('default', FLAGS.FindModuleDefiningFlag( '__NON_EXISTENT_FLAG__', 'default')) self.assertEqual( module_baz.__name__, FLAGS.FindModuleDefiningFlag('tmod_baz_x')) def testFindModuleIdDefiningFlag(self): self.assertEqual('default', FLAGS.FindModuleIdDefiningFlag( '__NON_EXISTENT_FLAG__', 'default')) self.assertEqual( id(module_baz), FLAGS.FindModuleIdDefiningFlag('tmod_baz_x')) class FlagsErrorMessagesTest(googletest.TestCase): """Testing special cases for integer and float flags error messages.""" def setUp(self): # make sure we are using the old, stupid way of parsing flags. self.flag_values = gflags.FlagValues() self.flag_values.UseGnuGetOpt(False) def testIntegerErrorText(self): # Make sure we get proper error text gflags.DEFINE_integer('positive', 4, 'non-negative flag', lower_bound=1, flag_values=self.flag_values) gflags.DEFINE_integer('non_negative', 4, 'positive flag', lower_bound=0, flag_values=self.flag_values) gflags.DEFINE_integer('negative', -4, 'negative flag', upper_bound=-1, flag_values=self.flag_values) gflags.DEFINE_integer('non_positive', -4, 'non-positive flag', upper_bound=0, flag_values=self.flag_values) gflags.DEFINE_integer('greater', 19, 'greater-than flag', lower_bound=4, flag_values=self.flag_values) gflags.DEFINE_integer('smaller', -19, 'smaller-than flag', upper_bound=4, flag_values=self.flag_values) gflags.DEFINE_integer('usual', 4, 'usual flag', lower_bound=0, upper_bound=10000, flag_values=self.flag_values) gflags.DEFINE_integer('another_usual', 0, 'usual flag', lower_bound=-1, upper_bound=1, flag_values=self.flag_values) self._CheckErrorMessage('positive', -4, 'a positive integer') self._CheckErrorMessage('non_negative', -4, 'a non-negative integer') self._CheckErrorMessage('negative', 0, 'a negative integer') self._CheckErrorMessage('non_positive', 4, 'a non-positive integer') self._CheckErrorMessage('usual', -4, 'an integer in the range [0, 10000]') self._CheckErrorMessage('another_usual', 4, 'an integer in the range [-1, 1]') self._CheckErrorMessage('greater', -5, 'integer >= 4') self._CheckErrorMessage('smaller', 5, 'integer <= 4') def testFloatErrorText(self): gflags.DEFINE_float('positive', 4, 'non-negative flag', lower_bound=1, flag_values=self.flag_values) gflags.DEFINE_float('non_negative', 4, 'positive flag', lower_bound=0, flag_values=self.flag_values) gflags.DEFINE_float('negative', -4, 'negative flag', upper_bound=-1, flag_values=self.flag_values) gflags.DEFINE_float('non_positive', -4, 'non-positive flag', upper_bound=0, flag_values=self.flag_values) gflags.DEFINE_float('greater', 19, 'greater-than flag', lower_bound=4, flag_values=self.flag_values) gflags.DEFINE_float('smaller', -19, 'smaller-than flag', upper_bound=4, flag_values=self.flag_values) gflags.DEFINE_float('usual', 4, 'usual flag', lower_bound=0, upper_bound=10000, flag_values=self.flag_values) gflags.DEFINE_float('another_usual', 0, 'usual flag', lower_bound=-1, upper_bound=1, flag_values=self.flag_values) self._CheckErrorMessage('positive', 0.5, 'number >= 1') self._CheckErrorMessage('non_negative', -4.0, 'a non-negative number') self._CheckErrorMessage('negative', 0.5, 'number <= -1') self._CheckErrorMessage('non_positive', 4.0, 'a non-positive number') self._CheckErrorMessage('usual', -4.0, 'a number in the range [0, 10000]') self._CheckErrorMessage('another_usual', 4.0, 'a number in the range [-1, 1]') self._CheckErrorMessage('smaller', 5.0, 'number <= 4') def _CheckErrorMessage(self, flag_name, flag_value, expected_message_suffix): """Set a flag to a given value and make sure we get expected message.""" try: self.flag_values.__setattr__(flag_name, flag_value) raise AssertionError('Bounds exception not raised!') except gflags.IllegalFlagValue, e: expected = ('flag --%(name)s=%(value)s: %(value)s is not %(suffix)s' % {'name': flag_name, 'value': flag_value, 'suffix': expected_message_suffix}) self.assertEquals(str(e), expected) def main(): googletest.main() if __name__ == '__main__': main()
apache-2.0
jacobmetrick/Flexget
flexget/plugins/internal/urlrewriting.py
1
4917
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import logging from flexget import plugin from flexget.event import event log = logging.getLogger('urlrewriter') class UrlRewritingError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class PluginUrlRewriting(object): """ Provides URL rewriting framework """ def __init__(self): self.disabled_rewriters = [] def on_task_urlrewrite(self, task, config): log.debug('Checking %s entries' % len(task.accepted)) # try to urlrewrite all accepted for entry in task.accepted: try: self.url_rewrite(task, entry) except UrlRewritingError as e: log.warning(e.value) entry.fail() # API method def url_rewritable(self, task, entry): """Return True if entry is urlrewritable by registered rewriter.""" for urlrewriter in plugin.get_plugins(interface='urlrewriter'): if urlrewriter.name in self.disabled_rewriters: log.trace('Skipping rewriter %s since it\'s disabled' % urlrewriter.name) continue log.trace('checking urlrewriter %s' % urlrewriter.name) if urlrewriter.instance.url_rewritable(task, entry): return True return False # API method - why priority though? @plugin.priority(255) def url_rewrite(self, task, entry): """Rewrites given entry url. Raises UrlRewritingError if failed.""" tries = 0 while self.url_rewritable(task, entry) and entry.accepted: tries += 1 if tries > 20: raise UrlRewritingError('URL rewriting was left in infinite loop while rewriting url for %s, ' 'some rewriter is returning always True' % entry) for urlrewriter in plugin.get_plugins(interface='urlrewriter'): name = urlrewriter.name if name in self.disabled_rewriters: log.trace('Skipping rewriter %s since it\'s disabled' % name) continue try: if urlrewriter.instance.url_rewritable(task, entry): old_url = entry['url'] log.debug('Url rewriting %s' % entry['url']) urlrewriter.instance.url_rewrite(task, entry) if entry['url'] != old_url: if entry.get('urls') and old_url in entry.get('urls'): entry['urls'][entry['urls'].index(old_url)] = entry['url'] log.info('Entry \'%s\' URL rewritten to %s (with %s)' % ( entry['title'], entry['url'], name)) except UrlRewritingError as r: # increase failcount # count = self.shared_cache.storedefault(entry['url'], 1) # count += 1 raise UrlRewritingError('URL rewriting %s failed: %s' % (name, r.value)) except plugin.PluginError as e: raise UrlRewritingError('URL rewriting %s failed: %s' % (name, e.value)) except Exception as e: log.exception(e) raise UrlRewritingError('%s: Internal error with url %s' % (name, entry['url'])) class DisableUrlRewriter(object): """Disable certain urlrewriters.""" schema = {'type': 'array', 'items': {'type': 'string'}} def on_task_start(self, task, config): urlrewrite = plugin.get_plugin_by_name('urlrewriting')['instance'] for disable in config: try: plugin.get_plugin_by_name(disable) except plugin.DependencyError: log.critical('Unknown url-rewriter %s' % disable) continue log.debug('Disabling url rewriter %s' % disable) urlrewrite.disabled_rewriters.append(disable) def on_task_exit(self, task, config): urlrewrite = plugin.get_plugin_by_name('urlrewriting')['instance'] for disable in config: log.debug('Enabling url rewriter %s' % disable) try: urlrewrite.disabled_rewriters.remove(disable) except ValueError: log.debug('%s does not exists' % disable) on_task_abort = on_task_exit @event('plugin.register') def register_plugin(): plugin.register(PluginUrlRewriting, 'urlrewriting', builtin=True, api_ver=2) plugin.register(DisableUrlRewriter, 'disable_urlrewriters', api_ver=2) plugin.register_task_phase('urlrewrite', before='download')
mit
SuperTux/flexlay
text_editor/highlighters/highlighter.py
1
3157
# Flexlay - A Generic 2D Game Editor # Copyright (C) 2015 Karkus476 <karkus476@yahoo.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import json, re from PyQt4.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont from PyQt4.QtCore import Qt class SuperTuxHighlighter(QSyntaxHighlighter): @staticmethod def load_patterns(filename=None, root="supertux-level"): if not filename or filename[-5:] != ".json": filename = "highlighters/patterns.json" rules = [] patterns_file = open(filename, "r") pattern_list = json.loads(patterns_file.read())[root] for pattern_json in pattern_list: pattern = pattern_json["find"] colour = pattern_json["color"] id = pattern_json["id"] format = QTextCharFormat() if colour == "black": format.setForeground(Qt.black) elif colour == "blue": format.setForeground(Qt.blue) elif colour == "red": format.setForeground(Qt.red) elif colour == "green": format.setForeground(Qt.green) elif colour == "darkGreen": format.setForeground(Qt.darkGreen) elif colour == "darkBlue": format.setForeground(Qt.darkBlue) elif colour == "darkRed": format.setForeground(Qt.darkRed) elif colour == "magenta": format.setForeground(Qt.magenta) if pattern_json["bold"]: format.setFontWeight(QFont.Bold) if pattern_json["italic"]: format.setFontItalic(True) rule = HighlightingRule(pattern, format, id=id) rules.append(rule) print("Done:", len(rules)) return rules def __init__(self, text_edit): super().__init__(text_edit) self.highlighting_rules = [] def highlightBlock(self, text): for rule in self.highlighting_rules: search = re.search(rule.pattern, text) span = None if not search else search.span() while span: length = span[1] - span[0] self.setFormat(span[0], length, rule.format) search = re.search(rule.pattern, text[span[1]:]) span = None if not search else search.span() self.setCurrentBlockState(0) class HighlightingRule: def __init__(self, pattern, format, id="null"): self.pattern = pattern self.format = format self.id = id # EOF #
gpl-3.0
ndardenne/pymatgen
pymatgen/core/physical_constants.py
3
1935
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import unicode_literals import warnings import scipy.constants as constants """ This module defines useful physical constants and conversion factors. All units are in SI units except for conversion factors. .. attribute:: ELECTRON_CHARGE or e Charge of an electron in coulombs. .. attribute:: EPSILON_0 Permittivity of vacuum .. attribute:: BOLTZMANN_CONST or k_b Boltzmann's constant .. attribute:: R Gas constant in J K-1 mol-1 .. attribute:: F Faraday's constant in C / mol .. attribute:: ELECTRON_VOLT eV in Joules. .. attribute:: AVOGADROS_CONST or N_a Avogardo's constant """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2011, The Materials Project" __version__ = "1.0" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __status__ = "Production" __date__ = "Sep 23, 2011" warnings.warn("The pymatgen.core.physical_constants module is deprecated and " "will be removed in pymatgen 4.0. Pls use scipy.constants.", DeprecationWarning) # Constants. Note that some of these may replicate functionality in # scipy.constants. However, given the difficulty in installing scipy on many # systems, the replication of these constants minimizes scipy dependency. ELECTRON_CHARGE = constants.e ELECTRON_MASS = constants.m_e EPSILON_0 = constants.epsilon_0 BOLTZMANN_CONST = constants.k ELECTRON_VOLT = constants.e AVOGADROS_CONST = constants.N_A HARTREE_TO_ELECTRON_VOLT = 1/constants.physical_constants[ "electron volt-hartree relationship"][0] SPEED_OF_LIGHT = constants.c PLANCK_CONSTANT = constants.h # Some useful aliases N_a = AVOGADROS_CONST k_b = BOLTZMANN_CONST e = ELECTRON_CHARGE R = AVOGADROS_CONST * BOLTZMANN_CONST F = AVOGADROS_CONST * ELECTRON_CHARGE c = SPEED_OF_LIGHT h = PLANCK_CONSTANT
mit
broferek/ansible
test/units/modules/network/fortios/test_fortios_log_fortianalyzer_filter.py
21
9596
# Copyright 2019 Fortinet, Inc. # # 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 Ansible. If not, see <https://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest from mock import ANY from ansible.module_utils.network.fortios.fortios import FortiOSHandler try: from ansible.modules.network.fortios import fortios_log_fortianalyzer_filter except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_log_fortianalyzer_filter.Connection') return connection_class_mock fos_instance = FortiOSHandler(connection_mock) def test_log_fortianalyzer_filter_creation(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'log_fortianalyzer_filter': { 'anomaly': 'enable', 'dlp_archive': 'enable', 'dns': 'enable', 'filter': 'test_value_6', 'filter_type': 'include', 'forward_traffic': 'enable', 'gtp': 'enable', 'local_traffic': 'enable', 'multicast_traffic': 'enable', 'netscan_discovery': 'test_value_12,', 'netscan_vulnerability': 'test_value_13,', 'severity': 'emergency', 'sniffer_traffic': 'enable', 'ssh': 'enable', 'voip': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_log_fortianalyzer_filter.fortios_log_fortianalyzer(input_data, fos_instance) expected_data = { 'anomaly': 'enable', 'dlp-archive': 'enable', 'dns': 'enable', 'filter': 'test_value_6', 'filter-type': 'include', 'forward-traffic': 'enable', 'gtp': 'enable', 'local-traffic': 'enable', 'multicast-traffic': 'enable', 'netscan-discovery': 'test_value_12,', 'netscan-vulnerability': 'test_value_13,', 'severity': 'emergency', 'sniffer-traffic': 'enable', 'ssh': 'enable', 'voip': 'enable' } set_method_mock.assert_called_with('log.fortianalyzer', 'filter', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_log_fortianalyzer_filter_creation_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'log_fortianalyzer_filter': { 'anomaly': 'enable', 'dlp_archive': 'enable', 'dns': 'enable', 'filter': 'test_value_6', 'filter_type': 'include', 'forward_traffic': 'enable', 'gtp': 'enable', 'local_traffic': 'enable', 'multicast_traffic': 'enable', 'netscan_discovery': 'test_value_12,', 'netscan_vulnerability': 'test_value_13,', 'severity': 'emergency', 'sniffer_traffic': 'enable', 'ssh': 'enable', 'voip': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_log_fortianalyzer_filter.fortios_log_fortianalyzer(input_data, fos_instance) expected_data = { 'anomaly': 'enable', 'dlp-archive': 'enable', 'dns': 'enable', 'filter': 'test_value_6', 'filter-type': 'include', 'forward-traffic': 'enable', 'gtp': 'enable', 'local-traffic': 'enable', 'multicast-traffic': 'enable', 'netscan-discovery': 'test_value_12,', 'netscan-vulnerability': 'test_value_13,', 'severity': 'emergency', 'sniffer-traffic': 'enable', 'ssh': 'enable', 'voip': 'enable' } set_method_mock.assert_called_with('log.fortianalyzer', 'filter', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_log_fortianalyzer_filter_idempotent(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'log_fortianalyzer_filter': { 'anomaly': 'enable', 'dlp_archive': 'enable', 'dns': 'enable', 'filter': 'test_value_6', 'filter_type': 'include', 'forward_traffic': 'enable', 'gtp': 'enable', 'local_traffic': 'enable', 'multicast_traffic': 'enable', 'netscan_discovery': 'test_value_12,', 'netscan_vulnerability': 'test_value_13,', 'severity': 'emergency', 'sniffer_traffic': 'enable', 'ssh': 'enable', 'voip': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_log_fortianalyzer_filter.fortios_log_fortianalyzer(input_data, fos_instance) expected_data = { 'anomaly': 'enable', 'dlp-archive': 'enable', 'dns': 'enable', 'filter': 'test_value_6', 'filter-type': 'include', 'forward-traffic': 'enable', 'gtp': 'enable', 'local-traffic': 'enable', 'multicast-traffic': 'enable', 'netscan-discovery': 'test_value_12,', 'netscan-vulnerability': 'test_value_13,', 'severity': 'emergency', 'sniffer-traffic': 'enable', 'ssh': 'enable', 'voip': 'enable' } set_method_mock.assert_called_with('log.fortianalyzer', 'filter', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 404 def test_log_fortianalyzer_filter_filter_foreign_attributes(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'log_fortianalyzer_filter': { 'random_attribute_not_valid': 'tag', 'anomaly': 'enable', 'dlp_archive': 'enable', 'dns': 'enable', 'filter': 'test_value_6', 'filter_type': 'include', 'forward_traffic': 'enable', 'gtp': 'enable', 'local_traffic': 'enable', 'multicast_traffic': 'enable', 'netscan_discovery': 'test_value_12,', 'netscan_vulnerability': 'test_value_13,', 'severity': 'emergency', 'sniffer_traffic': 'enable', 'ssh': 'enable', 'voip': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_log_fortianalyzer_filter.fortios_log_fortianalyzer(input_data, fos_instance) expected_data = { 'anomaly': 'enable', 'dlp-archive': 'enable', 'dns': 'enable', 'filter': 'test_value_6', 'filter-type': 'include', 'forward-traffic': 'enable', 'gtp': 'enable', 'local-traffic': 'enable', 'multicast-traffic': 'enable', 'netscan-discovery': 'test_value_12,', 'netscan-vulnerability': 'test_value_13,', 'severity': 'emergency', 'sniffer-traffic': 'enable', 'ssh': 'enable', 'voip': 'enable' } set_method_mock.assert_called_with('log.fortianalyzer', 'filter', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200
gpl-3.0
amenonsen/ansible
lib/ansible/modules/network/fortios/fortios_system_replacemsg_image.py
1
9636
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_system_replacemsg_image short_description: Configure replacement message images in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS device by allowing the user to set and modify system feature and replacemsg_image category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 version_added: "2.9" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true state: description: - Indicates whether to create or remove the object. type: str choices: - present - absent system_replacemsg_image: description: - Configure replacement message images. default: null type: dict suboptions: image_base64: description: - Image data. type: str image_type: description: - Image type. type: str choices: - gif - jpg - tiff - png name: description: - Image name. required: true type: str ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Configure replacement message images. fortios_system_replacemsg_image: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" state: "present" system_replacemsg_image: image_base64: "<your_own_value>" image_type: "gif" name: "default_name_5" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_system_replacemsg_image_data(json): option_list = ['image_base64', 'image_type', 'name'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def system_replacemsg_image(data, fos): vdom = data['vdom'] state = data['state'] system_replacemsg_image_data = data['system_replacemsg_image'] filtered_data = underscore_to_hyphen(filter_system_replacemsg_image_data(system_replacemsg_image_data)) if state == "present": return fos.set('system', 'replacemsg-image', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('system', 'replacemsg-image', mkey=filtered_data['name'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_system(data, fos): if data['system_replacemsg_image']: resp = system_replacemsg_image(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "system_replacemsg_image": { "required": False, "type": "dict", "default": None, "options": { "image_base64": {"required": False, "type": "str"}, "image_type": {"required": False, "type": "str", "choices": ["gif", "jpg", "tiff", "png"]}, "name": {"required": True, "type": "str"} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_system(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_system(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
gpl-3.0
matrix-org/synapse
synapse/config/server.py
1
56774
# Copyright 2014-2016 OpenMarket Ltd # Copyright 2017-2018 New Vector Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. # # 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 itertools import logging import os.path import re from textwrap import indent from typing import Any, Dict, Iterable, List, Optional, Set, Tuple import attr import yaml from netaddr import AddrFormatError, IPNetwork, IPSet from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.util.module_loader import load_module from synapse.util.stringutils import parse_and_validate_server_name from ._base import Config, ConfigError logger = logging.Logger(__name__) # by default, we attempt to listen on both '::' *and* '0.0.0.0' because some OSes # (Windows, macOS, other BSD/Linux where net.ipv6.bindv6only is set) will only listen # on IPv6 when '::' is set. # # We later check for errors when binding to 0.0.0.0 and ignore them if :: is also in # in the list. DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"] def _6to4(network: IPNetwork) -> IPNetwork: """Convert an IPv4 network into a 6to4 IPv6 network per RFC 3056.""" # 6to4 networks consist of: # * 2002 as the first 16 bits # * The first IPv4 address in the network hex-encoded as the next 32 bits # * The new prefix length needs to include the bits from the 2002 prefix. hex_network = hex(network.first)[2:] hex_network = ("0" * (8 - len(hex_network))) + hex_network return IPNetwork( "2002:%s:%s::/%d" % ( hex_network[:4], hex_network[4:], 16 + network.prefixlen, ) ) def generate_ip_set( ip_addresses: Optional[Iterable[str]], extra_addresses: Optional[Iterable[str]] = None, config_path: Optional[Iterable[str]] = None, ) -> IPSet: """ Generate an IPSet from a list of IP addresses or CIDRs. Additionally, for each IPv4 network in the list of IP addresses, also includes the corresponding IPv6 networks. This includes: * IPv4-Compatible IPv6 Address (see RFC 4291, section 2.5.5.1) * IPv4-Mapped IPv6 Address (see RFC 4291, section 2.5.5.2) * 6to4 Address (see RFC 3056, section 2) Args: ip_addresses: An iterable of IP addresses or CIDRs. extra_addresses: An iterable of IP addresses or CIDRs. config_path: The path in the configuration for error messages. Returns: A new IP set. """ result = IPSet() for ip in itertools.chain(ip_addresses or (), extra_addresses or ()): try: network = IPNetwork(ip) except AddrFormatError as e: raise ConfigError( "Invalid IP range provided: %s." % (ip,), config_path ) from e result.add(network) # It is possible that these already exist in the set, but that's OK. if ":" not in str(network): result.add(IPNetwork(network).ipv6(ipv4_compatible=True)) result.add(IPNetwork(network).ipv6(ipv4_compatible=False)) result.add(_6to4(network)) return result # IP ranges that are considered private / unroutable / don't make sense. DEFAULT_IP_RANGE_BLACKLIST = [ # Localhost "127.0.0.0/8", # Private networks. "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", # Carrier grade NAT. "100.64.0.0/10", # Address registry. "192.0.0.0/24", # Link-local networks. "169.254.0.0/16", # Formerly used for 6to4 relay. "192.88.99.0/24", # Testing networks. "198.18.0.0/15", "192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", # Multicast. "224.0.0.0/4", # Localhost "::1/128", # Link-local addresses. "fe80::/10", # Unique local addresses. "fc00::/7", # Testing networks. "2001:db8::/32", # Multicast. "ff00::/8", # Site-local addresses "fec0::/10", ] DEFAULT_ROOM_VERSION = "6" ROOM_COMPLEXITY_TOO_GREAT = ( "Your homeserver is unable to join rooms this large or complex. " "Please speak to your server administrator, or upgrade your instance " "to join this room." ) METRICS_PORT_WARNING = """\ The metrics_port configuration option is deprecated in Synapse 0.31 in favour of a listener. Please see https://github.com/matrix-org/synapse/blob/master/docs/metrics-howto.md on how to configure the new listener. --------------------------------------------------------------------------------""" KNOWN_LISTENER_TYPES = { "http", "metrics", "manhole", "replication", } KNOWN_RESOURCES = { "client", "consent", "federation", "keys", "media", "metrics", "openid", "replication", "static", "webclient", } @attr.s(frozen=True) class HttpResourceConfig: names = attr.ib( type=List[str], factory=list, validator=attr.validators.deep_iterable(attr.validators.in_(KNOWN_RESOURCES)), # type: ignore ) compress = attr.ib( type=bool, default=False, validator=attr.validators.optional(attr.validators.instance_of(bool)), # type: ignore[arg-type] ) @attr.s(frozen=True) class HttpListenerConfig: """Object describing the http-specific parts of the config of a listener""" x_forwarded = attr.ib(type=bool, default=False) resources = attr.ib(type=List[HttpResourceConfig], factory=list) additional_resources = attr.ib(type=Dict[str, dict], factory=dict) tag = attr.ib(type=str, default=None) @attr.s(frozen=True) class ListenerConfig: """Object describing the configuration of a single listener.""" port = attr.ib(type=int, validator=attr.validators.instance_of(int)) bind_addresses = attr.ib(type=List[str]) type = attr.ib(type=str, validator=attr.validators.in_(KNOWN_LISTENER_TYPES)) tls = attr.ib(type=bool, default=False) # http_options is only populated if type=http http_options = attr.ib(type=Optional[HttpListenerConfig], default=None) class ServerConfig(Config): section = "server" def read_config(self, config, **kwargs): self.server_name = config["server_name"] self.server_context = config.get("server_context", None) try: parse_and_validate_server_name(self.server_name) except ValueError as e: raise ConfigError(str(e)) self.pid_file = self.abspath(config.get("pid_file")) self.web_client_location = config.get("web_client_location", None) self.soft_file_limit = config.get("soft_file_limit", 0) self.daemonize = config.get("daemonize") self.print_pidfile = config.get("print_pidfile") self.user_agent_suffix = config.get("user_agent_suffix") self.use_frozen_dicts = config.get("use_frozen_dicts", False) self.public_baseurl = config.get("public_baseurl") if self.public_baseurl is not None: if self.public_baseurl[-1] != "/": self.public_baseurl += "/" # Whether to enable user presence. presence_config = config.get("presence") or {} self.use_presence = presence_config.get("enabled") if self.use_presence is None: self.use_presence = config.get("use_presence", True) # Custom presence router module self.presence_router_module_class = None self.presence_router_config = None presence_router_config = presence_config.get("presence_router") if presence_router_config: ( self.presence_router_module_class, self.presence_router_config, ) = load_module(presence_router_config, ("presence", "presence_router")) # Whether to update the user directory or not. This should be set to # false only if we are updating the user directory in a worker self.update_user_directory = config.get("update_user_directory", True) # whether to enable the media repository endpoints. This should be set # to false if the media repository is running as a separate endpoint; # doing so ensures that we will not run cache cleanup jobs on the # master, potentially causing inconsistency. self.enable_media_repo = config.get("enable_media_repo", True) # Whether to require authentication to retrieve profile data (avatars, # display names) of other users through the client API. self.require_auth_for_profile_requests = config.get( "require_auth_for_profile_requests", False ) # Whether to require sharing a room with a user to retrieve their # profile data self.limit_profile_requests_to_users_who_share_rooms = config.get( "limit_profile_requests_to_users_who_share_rooms", False, ) # Whether to retrieve and display profile data for a user when they # are invited to a room self.include_profile_data_on_invite = config.get( "include_profile_data_on_invite", True ) if "restrict_public_rooms_to_local_users" in config and ( "allow_public_rooms_without_auth" in config or "allow_public_rooms_over_federation" in config ): raise ConfigError( "Can't use 'restrict_public_rooms_to_local_users' if" " 'allow_public_rooms_without_auth' and/or" " 'allow_public_rooms_over_federation' is set." ) # Check if the legacy "restrict_public_rooms_to_local_users" flag is set. This # flag is now obsolete but we need to check it for backward-compatibility. if config.get("restrict_public_rooms_to_local_users", False): self.allow_public_rooms_without_auth = False self.allow_public_rooms_over_federation = False else: # If set to 'true', removes the need for authentication to access the server's # public rooms directory through the client API, meaning that anyone can # query the room directory. Defaults to 'false'. self.allow_public_rooms_without_auth = config.get( "allow_public_rooms_without_auth", False ) # If set to 'true', allows any other homeserver to fetch the server's public # rooms directory via federation. Defaults to 'false'. self.allow_public_rooms_over_federation = config.get( "allow_public_rooms_over_federation", False ) default_room_version = config.get("default_room_version", DEFAULT_ROOM_VERSION) # Ensure room version is a str default_room_version = str(default_room_version) if default_room_version not in KNOWN_ROOM_VERSIONS: raise ConfigError( "Unknown default_room_version: %s, known room versions: %s" % (default_room_version, list(KNOWN_ROOM_VERSIONS.keys())) ) # Get the actual room version object rather than just the identifier self.default_room_version = KNOWN_ROOM_VERSIONS[default_room_version] # whether to enable search. If disabled, new entries will not be inserted # into the search tables and they will not be indexed. Users will receive # errors when attempting to search for messages. self.enable_search = config.get("enable_search", True) self.filter_timeline_limit = config.get("filter_timeline_limit", 100) # Whether we should block invites sent to users on this server # (other than those sent by local server admins) self.block_non_admin_invites = config.get("block_non_admin_invites", False) # Whether to enable experimental MSC1849 (aka relations) support self.experimental_msc1849_support_enabled = config.get( "experimental_msc1849_support_enabled", True ) # Options to control access by tracking MAU self.limit_usage_by_mau = config.get("limit_usage_by_mau", False) self.max_mau_value = 0 if self.limit_usage_by_mau: self.max_mau_value = config.get("max_mau_value", 0) self.mau_stats_only = config.get("mau_stats_only", False) self.mau_limits_reserved_threepids = config.get( "mau_limit_reserved_threepids", [] ) self.mau_trial_days = config.get("mau_trial_days", 0) self.mau_limit_alerting = config.get("mau_limit_alerting", True) # How long to keep redacted events in the database in unredacted form # before redacting them. redaction_retention_period = config.get("redaction_retention_period", "7d") if redaction_retention_period is not None: self.redaction_retention_period = self.parse_duration( redaction_retention_period ) else: self.redaction_retention_period = None # How long to keep entries in the `users_ips` table. user_ips_max_age = config.get("user_ips_max_age", "28d") if user_ips_max_age is not None: self.user_ips_max_age = self.parse_duration(user_ips_max_age) else: self.user_ips_max_age = None # Options to disable HS self.hs_disabled = config.get("hs_disabled", False) self.hs_disabled_message = config.get("hs_disabled_message", "") # Admin uri to direct users at should their instance become blocked # due to resource constraints self.admin_contact = config.get("admin_contact", None) ip_range_blacklist = config.get( "ip_range_blacklist", DEFAULT_IP_RANGE_BLACKLIST ) # Attempt to create an IPSet from the given ranges # Always blacklist 0.0.0.0, :: self.ip_range_blacklist = generate_ip_set( ip_range_blacklist, ["0.0.0.0", "::"], config_path=("ip_range_blacklist",) ) self.ip_range_whitelist = generate_ip_set( config.get("ip_range_whitelist", ()), config_path=("ip_range_whitelist",) ) # The federation_ip_range_blacklist is used for backwards-compatibility # and only applies to federation and identity servers. if "federation_ip_range_blacklist" in config: # Always blacklist 0.0.0.0, :: self.federation_ip_range_blacklist = generate_ip_set( config["federation_ip_range_blacklist"], ["0.0.0.0", "::"], config_path=("federation_ip_range_blacklist",), ) # 'federation_ip_range_whitelist' was never a supported configuration option. self.federation_ip_range_whitelist = None else: # No backwards-compatiblity requrired, as federation_ip_range_blacklist # is not given. Default to ip_range_blacklist and ip_range_whitelist. self.federation_ip_range_blacklist = self.ip_range_blacklist self.federation_ip_range_whitelist = self.ip_range_whitelist # (undocumented) option for torturing the worker-mode replication a bit, # for testing. The value defines the number of milliseconds to pause before # sending out any replication updates. self.replication_torture_level = config.get("replication_torture_level") # Whether to require a user to be in the room to add an alias to it. # Defaults to True. self.require_membership_for_aliases = config.get( "require_membership_for_aliases", True ) # Whether to allow per-room membership profiles through the send of membership # events with profile information that differ from the target's global profile. self.allow_per_room_profiles = config.get("allow_per_room_profiles", True) retention_config = config.get("retention") if retention_config is None: retention_config = {} self.retention_enabled = retention_config.get("enabled", False) retention_default_policy = retention_config.get("default_policy") if retention_default_policy is not None: self.retention_default_min_lifetime = retention_default_policy.get( "min_lifetime" ) if self.retention_default_min_lifetime is not None: self.retention_default_min_lifetime = self.parse_duration( self.retention_default_min_lifetime ) self.retention_default_max_lifetime = retention_default_policy.get( "max_lifetime" ) if self.retention_default_max_lifetime is not None: self.retention_default_max_lifetime = self.parse_duration( self.retention_default_max_lifetime ) if ( self.retention_default_min_lifetime is not None and self.retention_default_max_lifetime is not None and ( self.retention_default_min_lifetime > self.retention_default_max_lifetime ) ): raise ConfigError( "The default retention policy's 'min_lifetime' can not be greater" " than its 'max_lifetime'" ) else: self.retention_default_min_lifetime = None self.retention_default_max_lifetime = None if self.retention_enabled: logger.info( "Message retention policies support enabled with the following default" " policy: min_lifetime = %s ; max_lifetime = %s", self.retention_default_min_lifetime, self.retention_default_max_lifetime, ) self.retention_allowed_lifetime_min = retention_config.get( "allowed_lifetime_min" ) if self.retention_allowed_lifetime_min is not None: self.retention_allowed_lifetime_min = self.parse_duration( self.retention_allowed_lifetime_min ) self.retention_allowed_lifetime_max = retention_config.get( "allowed_lifetime_max" ) if self.retention_allowed_lifetime_max is not None: self.retention_allowed_lifetime_max = self.parse_duration( self.retention_allowed_lifetime_max ) if ( self.retention_allowed_lifetime_min is not None and self.retention_allowed_lifetime_max is not None and self.retention_allowed_lifetime_min > self.retention_allowed_lifetime_max ): raise ConfigError( "Invalid retention policy limits: 'allowed_lifetime_min' can not be" " greater than 'allowed_lifetime_max'" ) self.retention_purge_jobs = [] # type: List[Dict[str, Optional[int]]] for purge_job_config in retention_config.get("purge_jobs", []): interval_config = purge_job_config.get("interval") if interval_config is None: raise ConfigError( "A retention policy's purge jobs configuration must have the" " 'interval' key set." ) interval = self.parse_duration(interval_config) shortest_max_lifetime = purge_job_config.get("shortest_max_lifetime") if shortest_max_lifetime is not None: shortest_max_lifetime = self.parse_duration(shortest_max_lifetime) longest_max_lifetime = purge_job_config.get("longest_max_lifetime") if longest_max_lifetime is not None: longest_max_lifetime = self.parse_duration(longest_max_lifetime) if ( shortest_max_lifetime is not None and longest_max_lifetime is not None and shortest_max_lifetime > longest_max_lifetime ): raise ConfigError( "A retention policy's purge jobs configuration's" " 'shortest_max_lifetime' value can not be greater than its" " 'longest_max_lifetime' value." ) self.retention_purge_jobs.append( { "interval": interval, "shortest_max_lifetime": shortest_max_lifetime, "longest_max_lifetime": longest_max_lifetime, } ) if not self.retention_purge_jobs: self.retention_purge_jobs = [ { "interval": self.parse_duration("1d"), "shortest_max_lifetime": None, "longest_max_lifetime": None, } ] self.listeners = [parse_listener_def(x) for x in config.get("listeners", [])] # no_tls is not really supported any more, but let's grandfather it in # here. if config.get("no_tls", False): l2 = [] for listener in self.listeners: if listener.tls: logger.info( "Ignoring TLS-enabled listener on port %i due to no_tls", listener.port, ) else: l2.append(listener) self.listeners = l2 if not self.web_client_location: _warn_if_webclient_configured(self.listeners) self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None)) self.gc_seconds = self.read_gc_intervals(config.get("gc_min_interval", None)) @attr.s class LimitRemoteRoomsConfig: enabled = attr.ib( validator=attr.validators.instance_of(bool), default=False ) complexity = attr.ib( validator=attr.validators.instance_of( (float, int) # type: ignore[arg-type] # noqa ), default=1.0, ) complexity_error = attr.ib( validator=attr.validators.instance_of(str), default=ROOM_COMPLEXITY_TOO_GREAT, ) admins_can_join = attr.ib( validator=attr.validators.instance_of(bool), default=False ) self.limit_remote_rooms = LimitRemoteRoomsConfig( **(config.get("limit_remote_rooms") or {}) ) bind_port = config.get("bind_port") if bind_port: if config.get("no_tls", False): raise ConfigError("no_tls is incompatible with bind_port") self.listeners = [] bind_host = config.get("bind_host", "") gzip_responses = config.get("gzip_responses", True) http_options = HttpListenerConfig( resources=[ HttpResourceConfig(names=["client"], compress=gzip_responses), HttpResourceConfig(names=["federation"]), ], ) self.listeners.append( ListenerConfig( port=bind_port, bind_addresses=[bind_host], tls=True, type="http", http_options=http_options, ) ) unsecure_port = config.get("unsecure_port", bind_port - 400) if unsecure_port: self.listeners.append( ListenerConfig( port=unsecure_port, bind_addresses=[bind_host], tls=False, type="http", http_options=http_options, ) ) manhole = config.get("manhole") if manhole: self.listeners.append( ListenerConfig( port=manhole, bind_addresses=["127.0.0.1"], type="manhole", ) ) metrics_port = config.get("metrics_port") if metrics_port: logger.warning(METRICS_PORT_WARNING) self.listeners.append( ListenerConfig( port=metrics_port, bind_addresses=[config.get("metrics_bind_host", "127.0.0.1")], type="http", http_options=HttpListenerConfig( resources=[HttpResourceConfig(names=["metrics"])] ), ) ) self.cleanup_extremities_with_dummy_events = config.get( "cleanup_extremities_with_dummy_events", True ) # The number of forward extremities in a room needed to send a dummy event. self.dummy_events_threshold = config.get("dummy_events_threshold", 10) self.enable_ephemeral_messages = config.get("enable_ephemeral_messages", False) # Inhibits the /requestToken endpoints from returning an error that might leak # information about whether an e-mail address is in use or not on this # homeserver, and instead return a 200 with a fake sid if this kind of error is # met, without sending anything. # This is a compromise between sending an email, which could be a spam vector, # and letting the client know which email address is bound to an account and # which one isn't. self.request_token_inhibit_3pid_errors = config.get( "request_token_inhibit_3pid_errors", False, ) # List of users trialing the new experimental default push rules. This setting is # not included in the sample configuration file on purpose as it's a temporary # hack, so that some users can trial the new defaults without impacting every # user on the homeserver. users_new_default_push_rules = ( config.get("users_new_default_push_rules") or [] ) # type: list if not isinstance(users_new_default_push_rules, list): raise ConfigError("'users_new_default_push_rules' must be a list") # Turn the list into a set to improve lookup speed. self.users_new_default_push_rules = set( users_new_default_push_rules ) # type: set # Whitelist of domain names that given next_link parameters must have next_link_domain_whitelist = config.get( "next_link_domain_whitelist" ) # type: Optional[List[str]] self.next_link_domain_whitelist = None # type: Optional[Set[str]] if next_link_domain_whitelist is not None: if not isinstance(next_link_domain_whitelist, list): raise ConfigError("'next_link_domain_whitelist' must be a list") # Turn the list into a set to improve lookup speed. self.next_link_domain_whitelist = set(next_link_domain_whitelist) def has_tls_listener(self) -> bool: return any(listener.tls for listener in self.listeners) def generate_config_section( self, server_name, data_dir_path, open_private_ports, listeners, **kwargs ): ip_range_blacklist = "\n".join( " # - '%s'" % ip for ip in DEFAULT_IP_RANGE_BLACKLIST ) _, bind_port = parse_and_validate_server_name(server_name) if bind_port is not None: unsecure_port = bind_port - 400 else: bind_port = 8448 unsecure_port = 8008 pid_file = os.path.join(data_dir_path, "homeserver.pid") # Bring DEFAULT_ROOM_VERSION into the local-scope for use in the # default config string default_room_version = DEFAULT_ROOM_VERSION secure_listeners = [] unsecure_listeners = [] private_addresses = ["::1", "127.0.0.1"] if listeners: for listener in listeners: if listener["tls"]: secure_listeners.append(listener) else: # If we don't want open ports we need to bind the listeners # to some address other than 0.0.0.0. Here we chose to use # localhost. # If the addresses are already bound we won't overwrite them # however. if not open_private_ports: listener.setdefault("bind_addresses", private_addresses) unsecure_listeners.append(listener) secure_http_bindings = indent( yaml.dump(secure_listeners), " " * 10 ).lstrip() unsecure_http_bindings = indent( yaml.dump(unsecure_listeners), " " * 10 ).lstrip() if not unsecure_listeners: unsecure_http_bindings = ( """- port: %(unsecure_port)s tls: false type: http x_forwarded: true""" % locals() ) if not open_private_ports: unsecure_http_bindings += ( "\n bind_addresses: ['::1', '127.0.0.1']" ) unsecure_http_bindings += """ resources: - names: [client, federation] compress: false""" if listeners: # comment out this block unsecure_http_bindings = "#" + re.sub( "\n {10}", lambda match: match.group(0) + "#", unsecure_http_bindings, ) if not secure_listeners: secure_http_bindings = ( """#- port: %(bind_port)s # type: http # tls: true # resources: # - names: [client, federation]""" % locals() ) return ( """\ ## Server ## # The public-facing domain of the server # # The server_name name will appear at the end of usernames and room addresses # created on this server. For example if the server_name was example.com, # usernames on this server would be in the format @user:example.com # # In most cases you should avoid using a matrix specific subdomain such as # matrix.example.com or synapse.example.com as the server_name for the same # reasons you wouldn't use user@email.example.com as your email address. # See https://github.com/matrix-org/synapse/blob/master/docs/delegate.md # for information on how to host Synapse on a subdomain while preserving # a clean server_name. # # The server_name cannot be changed later so it is important to # configure this correctly before you start Synapse. It should be all # lowercase and may contain an explicit port. # Examples: matrix.org, localhost:8080 # server_name: "%(server_name)s" # When running as a daemon, the file to store the pid in # pid_file: %(pid_file)s # The absolute URL to the web client which /_matrix/client will redirect # to if 'webclient' is configured under the 'listeners' configuration. # # This option can be also set to the filesystem path to the web client # which will be served at /_matrix/client/ if 'webclient' is configured # under the 'listeners' configuration, however this is a security risk: # https://github.com/matrix-org/synapse#security-note # #web_client_location: https://riot.example.com/ # The public-facing base URL that clients use to access this Homeserver (not # including _matrix/...). This is the same URL a user might enter into the # 'Custom Homeserver URL' field on their client. If you use Synapse with a # reverse proxy, this should be the URL to reach Synapse via the proxy. # Otherwise, it should be the URL to reach Synapse's client HTTP listener (see # 'listeners' below). # #public_baseurl: https://example.com/ # Set the soft limit on the number of file descriptors synapse can use # Zero is used to indicate synapse should set the soft limit to the # hard limit. # #soft_file_limit: 0 # Presence tracking allows users to see the state (e.g online/offline) # of other local and remote users. # presence: # Uncomment to disable presence tracking on this homeserver. This option # replaces the previous top-level 'use_presence' option. # #enabled: false # Presence routers are third-party modules that can specify additional logic # to where presence updates from users are routed. # presence_router: # The custom module's class. Uncomment to use a custom presence router module. # #module: "my_custom_router.PresenceRouter" # Configuration options of the custom module. Refer to your module's # documentation for available options. # #config: # example_option: 'something' # Whether to require authentication to retrieve profile data (avatars, # display names) of other users through the client API. Defaults to # 'false'. Note that profile data is also available via the federation # API, unless allow_profile_lookup_over_federation is set to false. # #require_auth_for_profile_requests: true # Uncomment to require a user to share a room with another user in order # to retrieve their profile information. Only checked on Client-Server # requests. Profile requests from other servers should be checked by the # requesting server. Defaults to 'false'. # #limit_profile_requests_to_users_who_share_rooms: true # Uncomment to prevent a user's profile data from being retrieved and # displayed in a room until they have joined it. By default, a user's # profile data is included in an invite event, regardless of the values # of the above two settings, and whether or not the users share a server. # Defaults to 'true'. # #include_profile_data_on_invite: false # If set to 'true', removes the need for authentication to access the server's # public rooms directory through the client API, meaning that anyone can # query the room directory. Defaults to 'false'. # #allow_public_rooms_without_auth: true # If set to 'true', allows any other homeserver to fetch the server's public # rooms directory via federation. Defaults to 'false'. # #allow_public_rooms_over_federation: true # The default room version for newly created rooms. # # Known room versions are listed here: # https://matrix.org/docs/spec/#complete-list-of-room-versions # # For example, for room version 1, default_room_version should be set # to "1". # #default_room_version: "%(default_room_version)s" # The GC threshold parameters to pass to `gc.set_threshold`, if defined # #gc_thresholds: [700, 10, 10] # The minimum time in seconds between each GC for a generation, regardless of # the GC thresholds. This ensures that we don't do GC too frequently. # # A value of `[1s, 10s, 30s]` indicates that a second must pass between consecutive # generation 0 GCs, etc. # # Defaults to `[1s, 10s, 30s]`. # #gc_min_interval: [0.5s, 30s, 1m] # Set the limit on the returned events in the timeline in the get # and sync operations. The default value is 100. -1 means no upper limit. # # Uncomment the following to increase the limit to 5000. # #filter_timeline_limit: 5000 # Whether room invites to users on this server should be blocked # (except those sent by local server admins). The default is False. # #block_non_admin_invites: true # Room searching # # If disabled, new messages will not be indexed for searching and users # will receive errors when searching for messages. Defaults to enabled. # #enable_search: false # Prevent outgoing requests from being sent to the following blacklisted IP address # CIDR ranges. If this option is not specified then it defaults to private IP # address ranges (see the example below). # # The blacklist applies to the outbound requests for federation, identity servers, # push servers, and for checking key validity for third-party invite events. # # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly # listed here, since they correspond to unroutable addresses.) # # This option replaces federation_ip_range_blacklist in Synapse v1.25.0. # #ip_range_blacklist: %(ip_range_blacklist)s # List of IP address CIDR ranges that should be allowed for federation, # identity servers, push servers, and for checking key validity for # third-party invite events. This is useful for specifying exceptions to # wide-ranging blacklisted target IP ranges - e.g. for communication with # a push server only visible in your network. # # This whitelist overrides ip_range_blacklist and defaults to an empty # list. # #ip_range_whitelist: # - '192.168.1.1' # List of ports that Synapse should listen on, their purpose and their # configuration. # # Options for each listener include: # # port: the TCP port to bind to # # bind_addresses: a list of local addresses to listen on. The default is # 'all local interfaces'. # # type: the type of listener. Normally 'http', but other valid options are: # 'manhole' (see docs/manhole.md), # 'metrics' (see docs/metrics-howto.md), # 'replication' (see docs/workers.md). # # tls: set to true to enable TLS for this listener. Will use the TLS # key/cert specified in tls_private_key_path / tls_certificate_path. # # x_forwarded: Only valid for an 'http' listener. Set to true to use the # X-Forwarded-For header as the client IP. Useful when Synapse is # behind a reverse-proxy. # # resources: Only valid for an 'http' listener. A list of resources to host # on this port. Options for each resource are: # # names: a list of names of HTTP resources. See below for a list of # valid resource names. # # compress: set to true to enable HTTP compression for this resource. # # additional_resources: Only valid for an 'http' listener. A map of # additional endpoints which should be loaded via dynamic modules. # # Valid resource names are: # # client: the client-server API (/_matrix/client), and the synapse admin # API (/_synapse/admin). Also implies 'media' and 'static'. # # consent: user consent forms (/_matrix/consent). See # docs/consent_tracking.md. # # federation: the server-server API (/_matrix/federation). Also implies # 'media', 'keys', 'openid' # # keys: the key discovery API (/_matrix/keys). # # media: the media API (/_matrix/media). # # metrics: the metrics interface. See docs/metrics-howto.md. # # openid: OpenID authentication. # # replication: the HTTP replication API (/_synapse/replication). See # docs/workers.md. # # static: static resources under synapse/static (/_matrix/static). (Mostly # useful for 'fallback authentication'.) # # webclient: A web client. Requires web_client_location to be set. # listeners: # TLS-enabled listener: for when matrix traffic is sent directly to synapse. # # Disabled by default. To enable it, uncomment the following. (Note that you # will also need to give Synapse a TLS key and certificate: see the TLS section # below.) # %(secure_http_bindings)s # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy # that unwraps TLS. # # If you plan to use a reverse proxy, please see # https://github.com/matrix-org/synapse/blob/master/docs/reverse_proxy.md. # %(unsecure_http_bindings)s # example additional_resources: # #additional_resources: # "/_matrix/my/custom/endpoint": # module: my_module.CustomRequestHandler # config: {} # Turn on the twisted ssh manhole service on localhost on the given # port. # #- port: 9000 # bind_addresses: ['::1', '127.0.0.1'] # type: manhole # Forward extremities can build up in a room due to networking delays between # homeservers. Once this happens in a large room, calculation of the state of # that room can become quite expensive. To mitigate this, once the number of # forward extremities reaches a given threshold, Synapse will send an # org.matrix.dummy_event event, which will reduce the forward extremities # in the room. # # This setting defines the threshold (i.e. number of forward extremities in the # room) at which dummy events are sent. The default value is 10. # #dummy_events_threshold: 5 ## Homeserver blocking ## # How to reach the server admin, used in ResourceLimitError # #admin_contact: 'mailto:admin@server.com' # Global blocking # #hs_disabled: false #hs_disabled_message: 'Human readable reason for why the HS is blocked' # Monthly Active User Blocking # # Used in cases where the admin or server owner wants to limit to the # number of monthly active users. # # 'limit_usage_by_mau' disables/enables monthly active user blocking. When # enabled and a limit is reached the server returns a 'ResourceLimitError' # with error type Codes.RESOURCE_LIMIT_EXCEEDED # # 'max_mau_value' is the hard limit of monthly active users above which # the server will start blocking user actions. # # 'mau_trial_days' is a means to add a grace period for active users. It # means that users must be active for this number of days before they # can be considered active and guards against the case where lots of users # sign up in a short space of time never to return after their initial # session. # # 'mau_limit_alerting' is a means of limiting client side alerting # should the mau limit be reached. This is useful for small instances # where the admin has 5 mau seats (say) for 5 specific people and no # interest increasing the mau limit further. Defaults to True, which # means that alerting is enabled # #limit_usage_by_mau: false #max_mau_value: 50 #mau_trial_days: 2 #mau_limit_alerting: false # If enabled, the metrics for the number of monthly active users will # be populated, however no one will be limited. If limit_usage_by_mau # is true, this is implied to be true. # #mau_stats_only: false # Sometimes the server admin will want to ensure certain accounts are # never blocked by mau checking. These accounts are specified here. # #mau_limit_reserved_threepids: # - medium: 'email' # address: 'reserved_user@example.com' # Used by phonehome stats to group together related servers. #server_context: context # Resource-constrained homeserver settings # # When this is enabled, the room "complexity" will be checked before a user # joins a new remote room. If it is above the complexity limit, the server will # disallow joining, or will instantly leave. # # Room complexity is an arbitrary measure based on factors such as the number of # users in the room. # limit_remote_rooms: # Uncomment to enable room complexity checking. # #enabled: true # the limit above which rooms cannot be joined. The default is 1.0. # #complexity: 0.5 # override the error which is returned when the room is too complex. # #complexity_error: "This room is too complex." # allow server admins to join complex rooms. Default is false. # #admins_can_join: true # Whether to require a user to be in the room to add an alias to it. # Defaults to 'true'. # #require_membership_for_aliases: false # Whether to allow per-room membership profiles through the send of membership # events with profile information that differ from the target's global profile. # Defaults to 'true'. # #allow_per_room_profiles: false # How long to keep redacted events in unredacted form in the database. After # this period redacted events get replaced with their redacted form in the DB. # # Defaults to `7d`. Set to `null` to disable. # #redaction_retention_period: 28d # How long to track users' last seen time and IPs in the database. # # Defaults to `28d`. Set to `null` to disable clearing out of old rows. # #user_ips_max_age: 14d # Message retention policy at the server level. # # Room admins and mods can define a retention period for their rooms using the # 'm.room.retention' state event, and server admins can cap this period by setting # the 'allowed_lifetime_min' and 'allowed_lifetime_max' config options. # # If this feature is enabled, Synapse will regularly look for and purge events # which are older than the room's maximum retention period. Synapse will also # filter events received over federation so that events that should have been # purged are ignored and not stored again. # retention: # The message retention policies feature is disabled by default. Uncomment the # following line to enable it. # #enabled: true # Default retention policy. If set, Synapse will apply it to rooms that lack the # 'm.room.retention' state event. Currently, the value of 'min_lifetime' doesn't # matter much because Synapse doesn't take it into account yet. # #default_policy: # min_lifetime: 1d # max_lifetime: 1y # Retention policy limits. If set, and the state of a room contains a # 'm.room.retention' event in its state which contains a 'min_lifetime' or a # 'max_lifetime' that's out of these bounds, Synapse will cap the room's policy # to these limits when running purge jobs. # #allowed_lifetime_min: 1d #allowed_lifetime_max: 1y # Server admins can define the settings of the background jobs purging the # events which lifetime has expired under the 'purge_jobs' section. # # If no configuration is provided, a single job will be set up to delete expired # events in every room daily. # # Each job's configuration defines which range of message lifetimes the job # takes care of. For example, if 'shortest_max_lifetime' is '2d' and # 'longest_max_lifetime' is '3d', the job will handle purging expired events in # rooms whose state defines a 'max_lifetime' that's both higher than 2 days, and # lower than or equal to 3 days. Both the minimum and the maximum value of a # range are optional, e.g. a job with no 'shortest_max_lifetime' and a # 'longest_max_lifetime' of '3d' will handle every room with a retention policy # which 'max_lifetime' is lower than or equal to three days. # # The rationale for this per-job configuration is that some rooms might have a # retention policy with a low 'max_lifetime', where history needs to be purged # of outdated messages on a more frequent basis than for the rest of the rooms # (e.g. every 12h), but not want that purge to be performed by a job that's # iterating over every room it knows, which could be heavy on the server. # # If any purge job is configured, it is strongly recommended to have at least # a single job with neither 'shortest_max_lifetime' nor 'longest_max_lifetime' # set, or one job without 'shortest_max_lifetime' and one job without # 'longest_max_lifetime' set. Otherwise some rooms might be ignored, even if # 'allowed_lifetime_min' and 'allowed_lifetime_max' are set, because capping a # room's policy to these values is done after the policies are retrieved from # Synapse's database (which is done using the range specified in a purge job's # configuration). # #purge_jobs: # - longest_max_lifetime: 3d # interval: 12h # - shortest_max_lifetime: 3d # interval: 1d # Inhibits the /requestToken endpoints from returning an error that might leak # information about whether an e-mail address is in use or not on this # homeserver. # Note that for some endpoints the error situation is the e-mail already being # used, and for others the error is entering the e-mail being unused. # If this option is enabled, instead of returning an error, these endpoints will # act as if no error happened and return a fake session ID ('sid') to clients. # #request_token_inhibit_3pid_errors: true # A list of domains that the domain portion of 'next_link' parameters # must match. # # This parameter is optionally provided by clients while requesting # validation of an email or phone number, and maps to a link that # users will be automatically redirected to after validation # succeeds. Clients can make use this parameter to aid the validation # process. # # The whitelist is applied whether the homeserver or an # identity server is handling validation. # # The default value is no whitelist functionality; all domains are # allowed. Setting this value to an empty list will instead disallow # all domains. # #next_link_domain_whitelist: ["matrix.org"] """ % locals() ) def read_arguments(self, args): if args.manhole is not None: self.manhole = args.manhole if args.daemonize is not None: self.daemonize = args.daemonize if args.print_pidfile is not None: self.print_pidfile = args.print_pidfile @staticmethod def add_arguments(parser): server_group = parser.add_argument_group("server") server_group.add_argument( "-D", "--daemonize", action="store_true", default=None, help="Daemonize the homeserver", ) server_group.add_argument( "--print-pidfile", action="store_true", default=None, help="Print the path to the pidfile just before daemonizing", ) server_group.add_argument( "--manhole", metavar="PORT", dest="manhole", type=int, help="Turn on the twisted telnet manhole service on the given port.", ) def read_gc_intervals(self, durations) -> Optional[Tuple[float, float, float]]: """Reads the three durations for the GC min interval option, returning seconds.""" if durations is None: return None try: if len(durations) != 3: raise ValueError() return ( self.parse_duration(durations[0]) / 1000, self.parse_duration(durations[1]) / 1000, self.parse_duration(durations[2]) / 1000, ) except Exception: raise ConfigError( "Value of `gc_min_interval` must be a list of three durations if set" ) def is_threepid_reserved(reserved_threepids, threepid): """Check the threepid against the reserved threepid config Args: reserved_threepids([dict]) - list of reserved threepids threepid(dict) - The threepid to test for Returns: boolean Is the threepid undertest reserved_user """ for tp in reserved_threepids: if threepid["medium"] == tp["medium"] and threepid["address"] == tp["address"]: return True return False def read_gc_thresholds(thresholds): """Reads the three integer thresholds for garbage collection. Ensures that the thresholds are integers if thresholds are supplied. """ if thresholds is None: return None try: assert len(thresholds) == 3 return (int(thresholds[0]), int(thresholds[1]), int(thresholds[2])) except Exception: raise ConfigError( "Value of `gc_threshold` must be a list of three integers if set" ) def parse_listener_def(listener: Any) -> ListenerConfig: """parse a listener config from the config file""" listener_type = listener["type"] port = listener.get("port") if not isinstance(port, int): raise ConfigError("Listener configuration is lacking a valid 'port' option") tls = listener.get("tls", False) bind_addresses = listener.get("bind_addresses", []) bind_address = listener.get("bind_address") # if bind_address was specified, add it to the list of addresses if bind_address: bind_addresses.append(bind_address) # if we still have an empty list of addresses, use the default list if not bind_addresses: if listener_type == "metrics": # the metrics listener doesn't support IPv6 bind_addresses.append("0.0.0.0") else: bind_addresses.extend(DEFAULT_BIND_ADDRESSES) http_config = None if listener_type == "http": http_config = HttpListenerConfig( x_forwarded=listener.get("x_forwarded", False), resources=[ HttpResourceConfig(**res) for res in listener.get("resources", []) ], additional_resources=listener.get("additional_resources", {}), tag=listener.get("tag"), ) return ListenerConfig(port, bind_addresses, listener_type, tls, http_config) NO_MORE_WEB_CLIENT_WARNING = """ Synapse no longer includes a web client. To enable a web client, configure web_client_location. To remove this warning, remove 'webclient' from the 'listeners' configuration. """ def _warn_if_webclient_configured(listeners: Iterable[ListenerConfig]) -> None: for listener in listeners: if not listener.http_options: continue for res in listener.http_options.resources: for name in res.names: if name == "webclient": logger.warning(NO_MORE_WEB_CLIENT_WARNING) return
apache-2.0
openstack/nova-solver-scheduler
nova_solverscheduler/tests/scheduler/solvers/test_solvers.py
1
3383
# Copyright (c) 2014 Cisco Systems, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from nova import test from nova_solverscheduler.scheduler import solvers from nova_solverscheduler.scheduler.solvers import constraints from nova_solverscheduler.scheduler.solvers import costs from nova_solverscheduler import solver_scheduler_exception as exception class FakeCost1(costs.BaseCost): def get_components(self, variables, hosts, filter_properties): pass class FakeCost2(costs.BaseCost): def get_components(self, variables, hosts, filter_properties): pass class FakeConstraint1(constraints.BaseConstraint): def get_components(self, variables, hosts, filter_properties): pass class FakeConstraint2(constraints.BaseConstraint): def get_components(self, variables, hosts, filter_properties): pass class TestBaseHostSolver(test.NoDBTestCase): """Test case for scheduler base solver.""" def setUp(self): super(TestBaseHostSolver, self).setUp() self.solver = solvers.BaseHostSolver() @mock.patch.object(costs.CostHandler, 'get_all_classes') def test_get_cost_classes_normal(self, getcls): self.flags(scheduler_solver_costs=['FakeCost1'], group='solver_scheduler') getcls.return_value = [FakeCost1, FakeCost2] cost_classes = self.solver._get_cost_classes() self.assertIn(FakeCost1, cost_classes) self.assertNotIn(FakeCost2, cost_classes) @mock.patch.object(costs.CostHandler, 'get_all_classes') def test_get_cost_classes_not_found(self, getcls): self.flags(scheduler_solver_costs=['FakeUnknownCost'], group='solver_scheduler') getcls.return_value = [FakeCost1, FakeCost2] self.assertRaises(exception.SchedulerSolverCostNotFound, self.solver._get_cost_classes) @mock.patch.object(constraints.ConstraintHandler, 'get_all_classes') def test_get_constraint_classes_normal(self, getcls): self.flags(scheduler_solver_constraints=['FakeConstraint1'], group='solver_scheduler') getcls.return_value = [FakeConstraint1, FakeConstraint2] constraint_classes = self.solver._get_constraint_classes() self.assertIn(FakeConstraint1, constraint_classes) self.assertNotIn(FakeConstraint2, constraint_classes) @mock.patch.object(constraints.ConstraintHandler, 'get_all_classes') def test_get_constraint_classes_not_found(self, getcls): self.flags(scheduler_solver_constraints=['FakeUnknownConstraint'], group='solver_scheduler') getcls.return_value = [FakeConstraint1, FakeConstraint2] self.assertRaises(exception.SchedulerSolverConstraintNotFound, self.solver._get_constraint_classes)
apache-2.0
buuck/root
interpreter/llvm/src/tools/clang/tools/scan-build-py/tests/functional/cases/test_exec_anatomy.py
52
1595
# -*- coding: utf-8 -*- # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. import libear import unittest import os.path import subprocess import json def run(source_dir, target_dir): def execute(cmd): return subprocess.check_call(cmd, cwd=target_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) execute(['cmake', source_dir]) execute(['make']) result_file = os.path.join(target_dir, 'result.json') expected_file = os.path.join(target_dir, 'expected.json') execute(['intercept-build', '--cdb', result_file, './exec', expected_file]) return (expected_file, result_file) class ExecAnatomyTest(unittest.TestCase): def assertEqualJson(self, expected, result): def read_json(filename): with open(filename) as handler: return json.load(handler) lhs = read_json(expected) rhs = read_json(result) for item in lhs: self.assertTrue(rhs.count(item)) for item in rhs: self.assertTrue(lhs.count(item)) def test_all_exec_calls(self): this_dir, _ = os.path.split(__file__) source_dir = os.path.normpath(os.path.join(this_dir, '..', 'exec')) with libear.TemporaryDirectory() as tmp_dir: expected, result = run(source_dir, tmp_dir) self.assertEqualJson(expected, result)
lgpl-2.1
dennybaa/st2
st2common/tests/unit/test_queue_consumer.py
4
2026
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import mock from kombu import Connection, Exchange, Queue from st2common.transport import consumers from st2common.transport import utils as transport_utils from st2tests.base import DbTestCase from tests.unit.base import FakeModelDB FAKE_XCHG = Exchange('st2.tests', type='topic') FAKE_WORK_Q = Queue('st2.tests.unit', FAKE_XCHG) class FakeMessageHandler(consumers.MessageHandler): message_type = FakeModelDB def process(self, payload): pass def get_handler(): with Connection(transport_utils.get_messaging_urls()) as conn: return FakeMessageHandler(conn, [FAKE_WORK_Q]) class QueueConsumerTest(DbTestCase): @mock.patch.object(FakeMessageHandler, 'process', mock.MagicMock()) def test_process_message(self): payload = FakeModelDB() handler = get_handler() handler._queue_consumer._process_message(payload) FakeMessageHandler.process.assert_called_once_with(payload) @mock.patch.object(FakeMessageHandler, 'process', mock.MagicMock()) def test_process_message_wrong_payload_type(self): payload = 100 handler = get_handler() handler._queue_consumer._process_message(payload) self.assertFalse(FakeMessageHandler.process.called)
apache-2.0
czchen/cppman
cppman/formatter/cppreference.py
1
11978
# -*- coding: utf-8 -*- # # formatter.py - format html from cplusplus.com to groff syntax # # Copyright (C) 2010 - 2015 Wei-Ning Huang (AZ) <aitjcize@gmail.com> # All Rights reserved. # # This file is part of cppman. # # 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. # import datetime import re import string import urllib.request from functools import partial from cppman.util import html2man, fixupHTML from cppman.formatter.tableparser import parse_table def member_table_def(g): tbl = parse_table('<table>%s</table>' % str(g.group(3))) # Escape column with '.' as prefix tbl = re.compile(r'T{\n(\..*?)\nT}', re.S).sub(r'T{\n\E \1\nT}', tbl) return '\n.IP "%s"\n%s\n%s\n' % (g.group(1), g.group(2), tbl) def member_type_function(g): head = re.sub(r'<.*?>', '', g.group(1)).strip() tail = '' cppvertag = re.search('^(.*)(\[(?:(?:since|until) )?C\+\+\d+\])$', head) if cppvertag: head = cppvertag.group(1).strip() tail = ' ' + cppvertag.group(2) if ',' in head: head = ', '.join([x.strip() + '(3)' for x in head.split(',')]) else: head = head.strip() + '(3)' return '\n.IP "%s"\n%s\n' % (head + tail, g.group(2)) NAV_BAR_END = '<div class="t-navbar-sep">.?</div></div>' # Format replacement RE list # The '.SE' pseudo macro is described in the function: html2groff rps = [ # Workaround: remove <p> in t-dcl (r'<tr class="t-dcl">(.*?)</tr>', lambda g: re.sub('<p/?>', '', g.group(1)), re.S), # Header, Name (r'<h1.*?>(.*?)</h1>', r'\n.TH "{{name}}" 3 "%s" "cppreference.com" "C++ Programmer\'s Manual"\n' r'\n.SH "NAME"\n{{name}} {{shortdesc}}\n.SE\n' % datetime.date.today(), re.S), # Defined in header (r'<div class="t-navbar"[^>]*>.*?' + NAV_BAR_END + r'.*?' r'Defined in header <code>(.*?)</code>(.*?)<tr class="t-dcl-sep">', r'\n.SH "SYNOPSIS"\n#include \1\n.sp\n' r'.nf\n\2\n.fi\n.SE\n' r'\n.SH "DESCRIPTION"\n', re.S), (r'<div class="t-navbar"[^>]*>.*?' + NAV_BAR_END + r'(.*?)<tr class="t-dcl-sep">', r'\n.SH "SYNOPSIS"\n.nf\n\1\n.fi\n.SE\n' r'\n.SH "DESCRIPTION"\n', re.S), # <unordered_map> (r'<div class="t-navbar"[^>]*>.*?' + NAV_BAR_END + r'(.*?)<table class="t-dsc-begin">', r'\n.SH "DESCRIPTION"\n\1\n', re.S), # access specifiers (r'<div class="t-navbar"[^>]*>.*?' + NAV_BAR_END + r'(.*?)<h3', r'\n.SH "DESCRIPTION"\n\1\n<h3', re.S), (r'<td>\s*\([0-9]+\)\s*</td>', r'', 0), # Section headers (r'<div class="t-inherited">.*?<h2>.*?Inherited from\s*(.*?)\s*</h2>', r'\n.SE\n.IEND\n.IBEGIN \1\n', re.S), # Remove tags (r'<span class="edit.*?">.*?</span> ?', r'', re.S), (r'&#91;edit&#93;', r'', re.S), (r'\[edit\]', r'', re.S), (r'<div id="siteSub">.*?</div>', r'', 0), (r'<div id="contentSub">.*?</div>', r'', 0), (r'<table class="toc" id="toc"[^>]*>.*?</table>', r'', re.S), (r'<h2[^>]*>.*?</h2>', r'', re.S), (r'<div class="coliru-btn coliru-btn-run-init">.*?</div>', r'', re.S), (r'<tr class="t-dsc-hitem">.*?</tr>', r'', re.S), # C++11/14 (r'\(((?:since|until) C\+\+\d+)\)', r' [\1]', re.S), (r'\((C\+\+\d+)\)', r' [\1]', re.S), # Subsections (r'<h5[^>]*>\s*(.*)</h5>', r'\n.SS "\1"\n', 0), # Group t-lines (r'<span></span>', r'', re.S), (r'<span class="t-lines">(?:<span>.+?</span>)+</span>', lambda x: re.sub('\s*</span><span>\s*', r', ', x.group(0)), re.S), # Member type & function second col is group see basic_fstream for example (r'<tr class="t-dsc">\s*?<td>((?:(?!</td>).)*?)</td>\s*?' r'<td>((?:(?!</td>).)*?)<table[^>]*>((?:(?!</table>).)*?)</table>' r'(?:(?!</td>).)*?</td>\s*?</tr>', member_table_def, re.S), # Section headers (r'.*<h3>(.+?)</h3>', r'\n.SE\n.SH "\1"\n', 0), # Member type & function (r'<tr class="t-dsc">\n?<td>\s*(.*?)\n?</td>.*?<td>\s*(.*?)</td>.*?</tr>', member_type_function, re.S), # Parameters (r'<tr class="t-par">.*?<td>\s*(.*?)\n?</td>.*?<td>.*?</td>.*?' r'<td>\s*(.*?)</td>.*?</tr>', r'\n.IP "\1"\n\2\n', re.S), # 'ul' tag (r'<ul>', r'\n.RS 2\n', 0), (r'</ul>', r'\n.RE\n.sp\n', 0), # 'li' tag (r'<li>\s*(.+?)</li>', r'\n.IP \[bu] 3\n\1\n', re.S), # 'pre' tag (r'<pre[^>]*>(.+?)</pre\s*>', r'\n.in +2n\n.nf\n\1\n.fi\n.in\n', re.S), # Footer (r'<div class="printfooter">', r'\n.SE\n.IEND\n.SH "REFERENCE"\n' r'cppreference.com, 2015 - All rights reserved.', re.S), # C++ version tag (r'<div title="(C\+\+..)"[^>]*>', r'.sp\n\1\n', 0), # Output (r'<p>Output:\n?</p>', r'\n.sp\nOutput:\n', re.S), # Paragraph (r'<p>(.*?)</p>', r'\n\1\n.sp\n', re.S), (r'<div class="t-li1">(.*?)</div>', r'\n\1\n.sp\n', re.S), (r'<div class="t-li2">(.*?)</div>', r'\n.RS\n\1\n.RE\n.sp\n', re.S), # 'br' tag (r'<br/>', r'\n.br\n', 0), (r'\n.br\n.br\n', r'\n.sp\n', 0), # 'dd' 'dt' tag (r'<dt>(.+?)</dt>\s*<dd>(.+?)</dd>', r'\n.IP "\1"\n\2\n', re.S), # Bold (r'<strong>(.+?)</strong>', r'\n.B \1\n', 0), # Any other tags (r'<script[^>]*>[^<]*</script>', r'', 0), (r'<.*?>', r'', re.S), # Escape (r'^#', r'\#', 0), (r'&#160;', ' ', 0), (r'&#(\d+);', lambda g: chr(int(g.group(1))), 0), # Misc (r'&lt;', r'<', 0), (r'&gt;', r'>', 0), (r'&quot;', r'"', 0), (r'&amp;', r'&', 0), (r'&nbsp;', r' ', 0), (r'\\([^\^nE])', r'\\\\\1', 0), (r'>/">', r'', 0), (r'/">', r'', 0), # Remove empty sections (r'\n.SH (.+?)\n+.SE', r'', 0), # Remove empty lines (r'\n\s*\n+', r'\n', 0), (r'\n\n+', r'\n', 0), # Preserve \n" in EXAMPLE (r'\\n', r'\en', 0), # Remove leading whitespace (r'^\s+', r'', re.S), # Trailing white-spaces (r'\s+\n', r'\n', re.S), # Remove extra whitespace and newline in .SH/SS/IP section (r'.(SH|SS|IP) "\s*(.*?)\s*\n?"', r'.\1 "\2"', 0), # Remove extra whitespace before .IP bullet (r'(.IP \\\\\[bu\] 3)\n\s*(.*?)\n', r'\1\n\2\n', 0), # Remove extra '\n' before C++ version Tag (don't do it in table) (r'(?<!T{)\n\s*(\[(:?since|until) C\+\+\d+\])', r' \1', re.S) ] def html2groff(data, name): """Convert HTML text from cppreference.com to Groff-formated text.""" # Remove header and footer try: data = data[data.index('<div id="cpp-content-base">'):] data = data[:data.index('<div class="printfooter">') + 25] except ValueError: pass # Remove non-printable characters data = ''.join([x for x in data if x in string.printable]) for table in re.findall( r'<table class="(?:wikitable|dsctable)"[^>]*>.*?</table>', data, re.S): tbl = parse_table(table) # Escape column with '.' as prefix tbl = re.compile(r'T{\n(\..*?)\nT}', re.S).sub(r'T{\n\E \1\nT}', tbl) data = data.replace(table, tbl) # Pre replace all for rp in rps: data = re.compile(rp[0], rp[2]).sub(rp[1], data) # Remove non-printable characters data = ''.join([x for x in data if x in string.printable]) # Upper case all section headers for st in re.findall(r'.SH .*\n', data): data = data.replace(st, st.upper()) # Add tags to member/inherited member functions # e.g. insert -> vector::insert # # .SE is a pseudo macro I created which means 'SECTION END' # The reason I use it is because I need a marker to know where section # ends. # re.findall find patterns which does not overlap, which means if I do # this: secs = re.findall(r'\n\.SH "(.+?)"(.+?)\.SH', data, re.S) # re.findall will skip the later .SH tag and thus skip the later section. # To fix this, '.SE' is used to mark the end of the section so the next # '.SH' can be find by re.findall try: idx = data.index('.IEND') except ValueError: idx = None def add_header_multi(prefix, g): if ',' in g.group(1): res = ', '.join(['%s::%s' % (prefix, x.strip()) for x in g.group(1).split(',')]) else: res = '%s::%s' % (prefix, g.group(1)) return '\n.IP "%s"' % res if idx: class_name = name if class_name.startswith('std::'): normalized_class_name = class_name[len('std::'):] else: normalized_class_name = class_name class_member_content = data[:idx] secs = re.findall(r'\.SH "(.+?)"(.+?)\.SE', class_member_content, re.S) for sec, content in secs: # Member functions if ('MEMBER' in sec and 'NON-MEMBER' not in sec and 'INHERITED' not in sec and sec != 'MEMBER TYPES'): content2 = re.sub(r'\n\.IP "([^:]+?)"', partial(add_header_multi, class_name), content) # Replace (constructor) (destructor) content2 = re.sub(r'\(constructor\)', r'%s' % normalized_class_name, content2) content2 = re.sub(r'\(destructor\)', r'~%s' % normalized_class_name, content2) data = data.replace(content, content2) blocks = re.findall(r'\.IBEGIN\s*(.+?)\s*\n(.+?)\.IEND', data, re.S) for inherited_class, content in blocks: content2 = re.sub(r'\.SH "(.+?)"', r'\n.SH "\1 INHERITED FROM %s"' % inherited_class.upper(), content) data = data.replace(content, content2) secs = re.findall(r'\.SH "(.+?)"(.+?)\.SE', content, re.S) for sec, content in secs: # Inherited member functions if 'MEMBER' in sec and \ sec != 'MEMBER TYPES': content2 = re.sub(r'\n\.IP "(.+)"', partial(add_header_multi, inherited_class), content) data = data.replace(content, content2) # Remove unneeded pseudo macro data = re.sub('(?:\n.SE|.IBEGIN.*?\n|\n.IEND)', '', data) # Replace all macros desc_re = re.search(r'.SH "DESCRIPTION"\n.*?([^\n\s].*?)\n', data) shortdesc = '' # not empty description if desc_re and not desc_re.group(1).startswith('.SH'): shortdesc = '- ' + desc_re.group(1) def dereference(g): d = dict(name=name, shortdesc=shortdesc) if g.group(1) in d: return d[g.group(1)] data = re.sub('{{(.*?)}}', dereference, data) return data def func_test(): """Test if there is major format changes in cplusplus.com""" ifs = urllib.request.urlopen('http://en.cppreference.com/w/cpp/container/vector') result = html2groff(fixupHTML(ifs.read()), 'std::vector') assert '.SH "NAME"' in result assert '.SH "SYNOPSIS"' in result assert '.SH "DESCRIPTION"' in result def test(): """Simple Text""" ifs = urllib.request.urlopen('http://en.cppreference.com/w/cpp/container/vector') print(html2groff(fixupHTML(ifs.read()), 'std::vector'), end=' ') #with open('test.html') as ifs: # data = fixupHTML(ifs.read()) # print html2groff(data, 'std::vector'), if __name__ == '__main__': test()
gpl-3.0
shuangsong/pattern
test/test_de.py
21
10848
# -*- coding: utf-8 -*- import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) import unittest import subprocess from pattern import de try: PATH = os.path.dirname(os.path.realpath(__file__)) except: PATH = "" #--------------------------------------------------------------------------------------------------- class TestInflection(unittest.TestCase): def setUp(self): pass def test_gender(self): # Assert der Hund => MASCULINE # Assert die Studentin => FEMININE # Assert das Auto => NEUTRAL self.assertEqual(de.gender("Hund"), de.MASCULINE) self.assertEqual(de.gender("Studentin"), de.FEMININE) self.assertEqual(de.gender("Auto"), de.NEUTRAL) def test_pluralize(self): # Assert the accuracy of the pluralization algorithm. from pattern.db import Datasheet i, n = 0, 0 for tag, sg, pl in Datasheet.load(os.path.join(PATH, "corpora", "wordforms-de-celex.csv")): if tag == "n": if de.pluralize(sg) == pl: i +=1 n += 1 self.assertTrue(float(i) / n > 0.69) print("pattern.de.pluralize()") def test_singularize(self): # Assert the accuracy of the singularization algorithm. from pattern.db import Datasheet i, n = 0, 0 for tag, sg, pl in Datasheet.load(os.path.join(PATH, "corpora", "wordforms-de-celex.csv")): if tag == "n": if de.singularize(pl) == sg: i +=1 n += 1 self.assertTrue(float(i) / n > 0.82) print("pattern.de.singularize()") def test_attributive(self): # Assert "groß" => "großer" (masculine, nominative), and others. for lemma, inflected, gender, role, article in ( (u"groß", u"großer", de.MALE, de.SUBJECT, None), (u"groß", u"großen", de.MALE, de.OBJECT, None), (u"groß", u"großem", de.MALE, de.INDIRECT, None), (u"groß", u"großen", de.MALE, de.PROPERTY, None), (u"groß", u"große", de.FEMALE, de.SUBJECT, None), (u"groß", u"große", de.FEMALE, de.OBJECT, None), (u"groß", u"großer", de.FEMALE, de.INDIRECT, None), (u"groß", u"großes", de.NEUTRAL, de.SUBJECT, None), (u"groß", u"großes", de.NEUTRAL, de.OBJECT, None), (u"groß", u"großen", de.MALE, de.PROPERTY, "mein"), (u"groß", u"großen", de.FEMALE, de.PROPERTY, "jeder"), (u"groß", u"großen", de.FEMALE, de.PROPERTY, "mein"), (u"groß", u"großen", de.PLURAL, de.INDIRECT, "jede"), (u"groß", u"großen", de.PLURAL, de.PROPERTY, "jeder")): v = de.attributive(lemma, gender, role, article) self.assertEqual(v, inflected) print("pattern.de.attributive()") def test_predicative(self): # Assert the accuracy of the predicative algorithm ("großer" => "groß"). from pattern.db import Datasheet i, n = 0, 0 for tag, pred, attr in Datasheet.load(os.path.join(PATH, "corpora", "wordforms-de-celex.csv")): if tag == "a": if de.predicative(attr) == pred: i +=1 n += 1 self.assertTrue(float(i) / n > 0.98) print("pattern.de.predicative()") def test_find_lemma(self): # Assert the accuracy of the verb lemmatization algorithm. # Note: the accuracy is higher (88%) when measured on CELEX word forms # (presumably because de.inflect.verbs has high percentage irregular verbs). i, n = 0, 0 for v1, v2 in de.inflect.verbs.inflections.items(): if de.inflect.verbs.find_lemma(v1) == v2: i += 1 n += 1 self.assertTrue(float(i) / n > 0.86) print("pattern.de.inflect.verbs.find_lemma()") def test_find_lexeme(self): # Assert the accuracy of the verb conjugation algorithm. i, n = 0, 0 for v, lexeme1 in de.inflect.verbs.infinitives.items(): lexeme2 = de.inflect.verbs.find_lexeme(v) for j in range(len(lexeme2)): if lexeme1[j] == "": continue if lexeme1[j] == lexeme2[j]: i += 1 n += 1 self.assertTrue(float(i) / n > 0.86) print("pattern.de.inflect.verbs.find_lexeme()") def test_conjugate(self): # Assert different tenses with different conjugations. for (v1, v2, tense) in ( ("sein", "sein", de.INFINITIVE), ("sein", "bin", (de.PRESENT, 1, de.SINGULAR)), ("sein", "bist", (de.PRESENT, 2, de.SINGULAR)), ("sein", "ist", (de.PRESENT, 3, de.SINGULAR)), ("sein", "sind", (de.PRESENT, 1, de.PLURAL)), ("sein", "seid", (de.PRESENT, 2, de.PLURAL)), ("sein", "sind", (de.PRESENT, 3, de.PLURAL)), ("sein", "seiend", (de.PRESENT + de.PARTICIPLE)), ("sein", "war", (de.PAST, 1, de.SINGULAR)), ("sein", "warst", (de.PAST, 2, de.SINGULAR)), ("sein", "war", (de.PAST, 3, de.SINGULAR)), ("sein", "waren", (de.PAST, 1, de.PLURAL)), ("sein", "wart", (de.PAST, 2, de.PLURAL)), ("sein", "waren", (de.PAST, 3, de.PLURAL)), ("sein", "gewesen", (de.PAST + de.PARTICIPLE)), ("sein", "sei", (de.PRESENT, 2, de.SINGULAR, de.IMPERATIVE)), ("sein", "seien", (de.PRESENT, 1, de.PLURAL, de.IMPERATIVE)), ("sein", "seid", (de.PRESENT, 2, de.PLURAL, de.IMPERATIVE)), ("sein", u"sei", (de.PRESENT, 1, de.SINGULAR, de.SUBJUNCTIVE)), ("sein", u"seiest", (de.PRESENT, 2, de.SINGULAR, de.SUBJUNCTIVE)), ("sein", u"sei", (de.PRESENT, 3, de.SINGULAR, de.SUBJUNCTIVE)), ("sein", u"seien", (de.PRESENT, 1, de.PLURAL, de.SUBJUNCTIVE)), ("sein", u"seiet", (de.PRESENT, 2, de.PLURAL, de.SUBJUNCTIVE)), ("sein", u"seien", (de.PRESENT, 3, de.PLURAL, de.SUBJUNCTIVE)), ("sein", u"wäre", (de.PAST, 1, de.SINGULAR, de.SUBJUNCTIVE)), ("sein", u"wärest", (de.PAST, 2, de.SINGULAR, de.SUBJUNCTIVE)), ("sein", u"wäre", (de.PAST, 3, de.SINGULAR, de.SUBJUNCTIVE)), ("sein", u"wären", (de.PAST, 1, de.PLURAL, de.SUBJUNCTIVE)), ("sein", u"wäret", (de.PAST, 2, de.PLURAL, de.SUBJUNCTIVE)), ("sein", u"wären", (de.PAST, 3, de.PLURAL, de.SUBJUNCTIVE))): self.assertEqual(de.conjugate(v1, tense), v2) print("pattern.de.conjugate()") def test_lexeme(self): # Assert all inflections of "sein". v = de.lexeme("sein") self.assertEqual(v, [ "sein", "bin", "bist", "ist", "sind", "seid", "seiend", "war", "warst", "waren", "wart", "gewesen", "sei", "seien", "seiest", "seiet", u"wäre", u"wärest", u"wären", u"wäret" ]) print("pattern.de.inflect.lexeme()") def test_tenses(self): # Assert tense recognition. self.assertTrue((de.PRESENT, 3, de.SG) in de.tenses("ist")) self.assertTrue("2sg" in de.tenses("bist")) print("pattern.de.tenses()") #--------------------------------------------------------------------------------------------------- class TestParser(unittest.TestCase): def setUp(self): pass def test_find_lemmata(self): # Assert lemmata for nouns, adjectives and verbs. v = de.parser.find_lemmata([["Ich", "PRP"], ["sage", "VB"], [u"schöne", "JJ"], [u"Dinge", "NNS"]]) self.assertEqual(v, [ ["Ich", "PRP", "ich"], ["sage", "VB", "sagen"], [u"schöne", "JJ", u"schön"], ["Dinge", "NNS", "ding"]]) print("pattern.de.parser.find_lemmata()") def test_parse(self): # Assert parsed output with Penn Treebank II tags (slash-formatted). # 1) "der große Hund" is a noun phrase, "auf der Matte" is a prepositional noun phrase. v = de.parser.parse(u"Der große Hund sitzt auf der Matte.") self.assertEqual(v, u"Der/DT/B-NP/O große/JJ/I-NP/O Hund/NN/I-NP/O " + \ u"sitzt/VB/B-VP/O " + \ u"auf/IN/B-PP/B-PNP der/DT/B-NP/I-PNP Matte/NN/I-NP/I-PNP ././O/O" ) # 2) "große" and "sitzt" lemmata are "groß" and "sitzen". # Note how articles are problematic ("der" can be male subject but also plural possessive). v = de.parser.parse(u"Der große Hund sitzt auf der Matte.", lemmata=True) self.assertEqual(v, u"Der/DT/B-NP/O/der große/JJ/I-NP/O/groß Hund/NN/I-NP/O/hund " + \ u"sitzt/VB/B-VP/O/sitzen " + \ u"auf/IN/B-PP/B-PNP/auf der/DT/B-NP/I-PNP/der Matte/NN/I-NP/I-PNP/matte ././O/O/." ) # 3) Assert the accuracy of the German tagger. i, n = 0, 0 for sentence in open(os.path.join(PATH, "corpora", "tagged-de-tiger.txt")).readlines(): sentence = sentence.decode("utf-8").strip() s1 = [w.split("/") for w in sentence.split(" ")] s1 = [de.stts2penntreebank(w, pos) for w, pos in s1] s2 = [[w for w, pos in s1]] s2 = de.parse(s2, tokenize=False) s2 = [w.split("/") for w in s2.split(" ")] for j in range(len(s1)): if s1[j][1] == s2[j][1]: i += 1 n += 1 self.assertTrue(float(i) / n > 0.844) print("pattern.de.parse()") def test_tag(self): # Assert [("der", "DT"), ("grosse", "JJ"), ("Hund", "NN")]. v = de.tag("der grosse Hund") self.assertEqual(v, [("der", "DT"), ("grosse", "JJ"), ("Hund", "NN")]) print("pattern.de.tag()") def test_command_line(self): # Assert parsed output from the command-line (example from the documentation). p = ["python", "-m", "pattern.de", "-s", "Der grosse Hund.", "-OTCRL"] p = subprocess.Popen(p, stdout=subprocess.PIPE) p.wait() v = p.stdout.read() v = v.strip() self.assertEqual(v, "Der/DT/B-NP/O/O/der grosse/JJ/I-NP/O/O/gross Hund/NN/I-NP/O/O/hund ././O/O/O/.") print("python -m pattern.de") #--------------------------------------------------------------------------------------------------- def suite(): suite = unittest.TestSuite() suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestInflection)) suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestParser)) return suite if __name__ == "__main__": unittest.TextTestRunner(verbosity=1).run(suite())
bsd-3-clause
llooker/python_sdk
lookerapi/apis/project_api.py
1
83417
# coding: utf-8 """ Looker API 3.0 Reference ### Authorization The Looker API uses Looker **API3** credentials for authorization and access control. Looker admins can create API3 credentials on Looker's **Admin/Users** page. Pass API3 credentials to the **/login** endpoint to obtain a temporary access_token. Include that access_token in the Authorization header of Looker API requests. For details, see [Looker API Authorization](https://looker.com/docs/r/api/authorization) ### Client SDKs The Looker API is a RESTful system that should be usable by any programming language capable of making HTTPS requests. Client SDKs for a variety of programming languages can be generated from the Looker API's Swagger JSON metadata to streamline use of the Looker API in your applications. A client SDK for Ruby is available as an example. For more information, see [Looker API Client SDKs](https://looker.com/docs/r/api/client_sdks) ### Try It Out! The 'api-docs' page served by the Looker instance includes 'Try It Out!' buttons for each API method. After logging in with API3 credentials, you can use the \"Try It Out!\" buttons to call the API directly from the documentation page to interactively explore API features and responses. ### Versioning Future releases of Looker will expand this API release-by-release to securely expose more and more of the core power of Looker to API client applications. API endpoints marked as \"beta\" may receive breaking changes without warning. Stable (non-beta) API endpoints should not receive breaking changes in future releases. For more information, see [Looker API Versioning](https://looker.com/docs/r/api/versioning) OpenAPI spec version: 3.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient class ProjectApi(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): config = Configuration() if api_client: self.api_client = api_client else: if not config.api_client: config.api_client = ApiClient() self.api_client = config.api_client def all_git_branches(self, project_id, **kwargs): """ Get All Git Branchs ### Get All Git Branches Returns a list of git branches in the project repository This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.all_git_branches(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :return: list[GitBranch] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.all_git_branches_with_http_info(project_id, **kwargs) else: (data) = self.all_git_branches_with_http_info(project_id, **kwargs) return data def all_git_branches_with_http_info(self, project_id, **kwargs): """ Get All Git Branchs ### Get All Git Branches Returns a list of git branches in the project repository This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.all_git_branches_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :return: list[GitBranch] If the method is called asynchronously, returns the request thread. """ all_params = ['project_id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method all_git_branches" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `all_git_branches`") collection_formats = {} resource_path = '/projects/{project_id}/git_branches'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[GitBranch]', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def all_git_connection_tests(self, project_id, **kwargs): """ Get All Git Connection Tests ### Get All Git Connection Tests Returns a list of tests which can be run against a project's git connection This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.all_git_connection_tests(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :return: list[GitConnectionTest] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.all_git_connection_tests_with_http_info(project_id, **kwargs) else: (data) = self.all_git_connection_tests_with_http_info(project_id, **kwargs) return data def all_git_connection_tests_with_http_info(self, project_id, **kwargs): """ Get All Git Connection Tests ### Get All Git Connection Tests Returns a list of tests which can be run against a project's git connection This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.all_git_connection_tests_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :return: list[GitConnectionTest] If the method is called asynchronously, returns the request thread. """ all_params = ['project_id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method all_git_connection_tests" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `all_git_connection_tests`") collection_formats = {} resource_path = '/projects/{project_id}/git_connection_tests'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[GitConnectionTest]', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def all_project_files(self, project_id, **kwargs): """ Get All Project Files ### Get All Project Files Returns a list of the files in the project This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.all_project_files(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: list[ProjectFile] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.all_project_files_with_http_info(project_id, **kwargs) else: (data) = self.all_project_files_with_http_info(project_id, **kwargs) return data def all_project_files_with_http_info(self, project_id, **kwargs): """ Get All Project Files ### Get All Project Files Returns a list of the files in the project This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.all_project_files_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: list[ProjectFile] If the method is called asynchronously, returns the request thread. """ all_params = ['project_id', 'fields'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method all_project_files" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `all_project_files`") collection_formats = {} resource_path = '/projects/{project_id}/files'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} if 'fields' in params: query_params['fields'] = params['fields'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[ProjectFile]', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def all_projects(self, **kwargs): """ Get All Projects ### Get All Projects Returns all projects visible to the current user This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.all_projects(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str fields: Requested fields :return: list[Project] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.all_projects_with_http_info(**kwargs) else: (data) = self.all_projects_with_http_info(**kwargs) return data def all_projects_with_http_info(self, **kwargs): """ Get All Projects ### Get All Projects Returns all projects visible to the current user This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.all_projects_with_http_info(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str fields: Requested fields :return: list[Project] If the method is called asynchronously, returns the request thread. """ all_params = ['fields'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method all_projects" % key ) params[key] = val del params['kwargs'] collection_formats = {} resource_path = '/projects'.replace('{format}', 'json') path_params = {} query_params = {} if 'fields' in params: query_params['fields'] = params['fields'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[Project]', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def create_git_deploy_key(self, project_id, **kwargs): """ Create Deploy Key ### Create Git Deploy Key Create a public/private key pair for authenticating ssh git requests from Looker to a remote git repository for a particular Looker project. Returns the public key of the generated ssh key pair. Copy this public key to your remote git repository's ssh keys configuration so that the remote git service can validate and accept git requests from the Looker server. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_git_deploy_key(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.create_git_deploy_key_with_http_info(project_id, **kwargs) else: (data) = self.create_git_deploy_key_with_http_info(project_id, **kwargs) return data def create_git_deploy_key_with_http_info(self, project_id, **kwargs): """ Create Deploy Key ### Create Git Deploy Key Create a public/private key pair for authenticating ssh git requests from Looker to a remote git repository for a particular Looker project. Returns the public key of the generated ssh key pair. Copy this public key to your remote git repository's ssh keys configuration so that the remote git service can validate and accept git requests from the Looker server. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_git_deploy_key_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :return: str If the method is called asynchronously, returns the request thread. """ all_params = ['project_id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_git_deploy_key" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `create_git_deploy_key`") collection_formats = {} resource_path = '/projects/{project_id}/git/deploy_key'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['text/plain']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='str', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def create_project(self, **kwargs): """ Create Project ### Create A Project dev mode required. - Call `update_session` to select the 'dev' workspace. `name` is required. `git_remote_url` is not allowed. To configure Git for the newly created project, follow the instructions in `update_project`. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_project(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Project body: Project :return: Project If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.create_project_with_http_info(**kwargs) else: (data) = self.create_project_with_http_info(**kwargs) return data def create_project_with_http_info(self, **kwargs): """ Create Project ### Create A Project dev mode required. - Call `update_session` to select the 'dev' workspace. `name` is required. `git_remote_url` is not allowed. To configure Git for the newly created project, follow the instructions in `update_project`. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_project_with_http_info(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Project body: Project :return: Project If the method is called asynchronously, returns the request thread. """ all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_project" % key ) params[key] = val del params['kwargs'] collection_formats = {} resource_path = '/projects'.replace('{format}', 'json') path_params = {} query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Project', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def git_deploy_key(self, project_id, **kwargs): """ Git Deploy Key ### Git Deploy Key Returns the ssh public key previously created for a project's git repository. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.git_deploy_key(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.git_deploy_key_with_http_info(project_id, **kwargs) else: (data) = self.git_deploy_key_with_http_info(project_id, **kwargs) return data def git_deploy_key_with_http_info(self, project_id, **kwargs): """ Git Deploy Key ### Git Deploy Key Returns the ssh public key previously created for a project's git repository. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.git_deploy_key_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :return: str If the method is called asynchronously, returns the request thread. """ all_params = ['project_id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method git_deploy_key" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `git_deploy_key`") collection_formats = {} resource_path = '/projects/{project_id}/git/deploy_key'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['text/plain']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='str', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def project(self, project_id, **kwargs): """ Get Project ### Get A Project Returns the project with the given project id This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.project(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: Project If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.project_with_http_info(project_id, **kwargs) else: (data) = self.project_with_http_info(project_id, **kwargs) return data def project_with_http_info(self, project_id, **kwargs): """ Get Project ### Get A Project Returns the project with the given project id This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.project_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: Project If the method is called asynchronously, returns the request thread. """ all_params = ['project_id', 'fields'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method project" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `project`") collection_formats = {} resource_path = '/projects/{project_id}'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} if 'fields' in params: query_params['fields'] = params['fields'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Project', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def project_file(self, project_id, file_id, **kwargs): """ Get Project File ### Get Project File Info Returns information about a file in the project This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.project_file(project_id, file_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str file_id: File Id (required) :param str fields: Requested fields :return: ProjectFile If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.project_file_with_http_info(project_id, file_id, **kwargs) else: (data) = self.project_file_with_http_info(project_id, file_id, **kwargs) return data def project_file_with_http_info(self, project_id, file_id, **kwargs): """ Get Project File ### Get Project File Info Returns information about a file in the project This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.project_file_with_http_info(project_id, file_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str file_id: File Id (required) :param str fields: Requested fields :return: ProjectFile If the method is called asynchronously, returns the request thread. """ all_params = ['project_id', 'file_id', 'fields'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method project_file" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `project_file`") # verify the required parameter 'file_id' is set if ('file_id' not in params) or (params['file_id'] is None): raise ValueError("Missing the required parameter `file_id` when calling `project_file`") collection_formats = {} resource_path = '/projects/{project_id}/files/file'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} if 'file_id' in params: query_params['file_id'] = params['file_id'] if 'fields' in params: query_params['fields'] = params['fields'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ProjectFile', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def project_validation_results(self, project_id, **kwargs): """ Cached Project Validation Results ### Get Cached Project Validation Results Returns the cached results of a previous project validation calculation, if any. Returns http status 204 No Content if no validation results exist. Validating the content of all the files in a project can be computationally intensive for large projects. Use this API to simply fetch the results of the most recent project validation rather than revalidating the entire project from scratch. A value of `\"stale\": true` in the response indicates that the project has changed since the cached validation results were computed. The cached validation results may no longer reflect the current state of the project. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.project_validation_results(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: ProjectValidationCache If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.project_validation_results_with_http_info(project_id, **kwargs) else: (data) = self.project_validation_results_with_http_info(project_id, **kwargs) return data def project_validation_results_with_http_info(self, project_id, **kwargs): """ Cached Project Validation Results ### Get Cached Project Validation Results Returns the cached results of a previous project validation calculation, if any. Returns http status 204 No Content if no validation results exist. Validating the content of all the files in a project can be computationally intensive for large projects. Use this API to simply fetch the results of the most recent project validation rather than revalidating the entire project from scratch. A value of `\"stale\": true` in the response indicates that the project has changed since the cached validation results were computed. The cached validation results may no longer reflect the current state of the project. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.project_validation_results_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: ProjectValidationCache If the method is called asynchronously, returns the request thread. """ all_params = ['project_id', 'fields'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method project_validation_results" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `project_validation_results`") collection_formats = {} resource_path = '/projects/{project_id}/validate'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} if 'fields' in params: query_params['fields'] = params['fields'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ProjectValidationCache', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def project_workspace(self, project_id, **kwargs): """ Get Project Workspace ### Get Project Workspace Returns information about the state of the project files in the currently selected workspace This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.project_workspace(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: ProjectWorkspace If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.project_workspace_with_http_info(project_id, **kwargs) else: (data) = self.project_workspace_with_http_info(project_id, **kwargs) return data def project_workspace_with_http_info(self, project_id, **kwargs): """ Get Project Workspace ### Get Project Workspace Returns information about the state of the project files in the currently selected workspace This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.project_workspace_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: ProjectWorkspace If the method is called asynchronously, returns the request thread. """ all_params = ['project_id', 'fields'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method project_workspace" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `project_workspace`") collection_formats = {} resource_path = '/projects/{project_id}/current_workspace'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} if 'fields' in params: query_params['fields'] = params['fields'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ProjectWorkspace', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def reset_project_to_production(self, project_id, **kwargs): """ Reset To Production ### Reset a project to the revision of the project that is in production. **DANGER** this will delete any changes that have not been pushed to a remote repository. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.reset_project_to_production(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Id of project (required) :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.reset_project_to_production_with_http_info(project_id, **kwargs) else: (data) = self.reset_project_to_production_with_http_info(project_id, **kwargs) return data def reset_project_to_production_with_http_info(self, project_id, **kwargs): """ Reset To Production ### Reset a project to the revision of the project that is in production. **DANGER** this will delete any changes that have not been pushed to a remote repository. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.reset_project_to_production_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Id of project (required) :return: str If the method is called asynchronously, returns the request thread. """ all_params = ['project_id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method reset_project_to_production" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `reset_project_to_production`") collection_formats = {} resource_path = '/projects/{project_id}/reset_to_production'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='str', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def reset_project_to_remote(self, project_id, **kwargs): """ Reset To Remote ### Reset a project development branch to the revision of the project that is on the remote. **DANGER** this will delete any changes that have not been pushed to a remote repository. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.reset_project_to_remote(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Id of project (required) :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.reset_project_to_remote_with_http_info(project_id, **kwargs) else: (data) = self.reset_project_to_remote_with_http_info(project_id, **kwargs) return data def reset_project_to_remote_with_http_info(self, project_id, **kwargs): """ Reset To Remote ### Reset a project development branch to the revision of the project that is on the remote. **DANGER** this will delete any changes that have not been pushed to a remote repository. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.reset_project_to_remote_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Id of project (required) :return: str If the method is called asynchronously, returns the request thread. """ all_params = ['project_id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method reset_project_to_remote" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `reset_project_to_remote`") collection_formats = {} resource_path = '/projects/{project_id}/reset_to_remote'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='str', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def run_git_connection_test(self, project_id, test_id, **kwargs): """ Run Git Connection Test ### Run a git connection test Run the named test on the git service used by this project and return the result. This is intended to help debug git connections when things do not work properly, to give more helpful information about why a git url is not working with Looker. They are intended to be run in the order they are returned from the /projects/ID/git_connection_tests endpoint. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.run_git_connection_test(project_id, test_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str test_id: Test Id (required) :return: GitConnectionTestResult If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.run_git_connection_test_with_http_info(project_id, test_id, **kwargs) else: (data) = self.run_git_connection_test_with_http_info(project_id, test_id, **kwargs) return data def run_git_connection_test_with_http_info(self, project_id, test_id, **kwargs): """ Run Git Connection Test ### Run a git connection test Run the named test on the git service used by this project and return the result. This is intended to help debug git connections when things do not work properly, to give more helpful information about why a git url is not working with Looker. They are intended to be run in the order they are returned from the /projects/ID/git_connection_tests endpoint. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.run_git_connection_test_with_http_info(project_id, test_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str test_id: Test Id (required) :return: GitConnectionTestResult If the method is called asynchronously, returns the request thread. """ all_params = ['project_id', 'test_id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method run_git_connection_test" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `run_git_connection_test`") # verify the required parameter 'test_id' is set if ('test_id' not in params) or (params['test_id'] is None): raise ValueError("Missing the required parameter `test_id` when calling `run_git_connection_test`") collection_formats = {} resource_path = '/projects/{project_id}/git_connection_tests/{test_id}'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] if 'test_id' in params: path_params['test_id'] = params['test_id'] query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='GitConnectionTestResult', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_project(self, project_id, body, **kwargs): """ Update Project ### Update Project Configuration Apply changes to a project's configuration. #### Configuring Git for a Project To set up a Looker project with a remote git repository, follow these steps: 1. Call `update_session` to select the 'dev' workspace. 1. Call `create_git_deploy_key` to create a new deploy key for the project 1. Copy the deploy key text into the remote git repository's ssh key configuration 1. Call `update_project` to set project's `git_remote_url` ()and `git_service_name`, if necessary). When you modify a project's `git_remote_url`, Looker connects to the remote repository to fetch metadata. The remote git repository MUST be configured with the Looker-generated deploy key for this project prior to setting the project's `git_remote_url`. To set up a Looker project with a git repository residing on the Looker server (a 'bare' git repo): 1. Call `update_session` to select the 'dev' workspace. 1. Call `update_project` setting `git_remote_url` to nil and `git_service_name` to \"bare\". This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_project(project_id, body, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param Project body: Project (required) :param str fields: Requested fields :return: Project If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.update_project_with_http_info(project_id, body, **kwargs) else: (data) = self.update_project_with_http_info(project_id, body, **kwargs) return data def update_project_with_http_info(self, project_id, body, **kwargs): """ Update Project ### Update Project Configuration Apply changes to a project's configuration. #### Configuring Git for a Project To set up a Looker project with a remote git repository, follow these steps: 1. Call `update_session` to select the 'dev' workspace. 1. Call `create_git_deploy_key` to create a new deploy key for the project 1. Copy the deploy key text into the remote git repository's ssh key configuration 1. Call `update_project` to set project's `git_remote_url` ()and `git_service_name`, if necessary). When you modify a project's `git_remote_url`, Looker connects to the remote repository to fetch metadata. The remote git repository MUST be configured with the Looker-generated deploy key for this project prior to setting the project's `git_remote_url`. To set up a Looker project with a git repository residing on the Looker server (a 'bare' git repo): 1. Call `update_session` to select the 'dev' workspace. 1. Call `update_project` setting `git_remote_url` to nil and `git_service_name` to \"bare\". This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_project_with_http_info(project_id, body, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param Project body: Project (required) :param str fields: Requested fields :return: Project If the method is called asynchronously, returns the request thread. """ all_params = ['project_id', 'body', 'fields'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_project" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `update_project`") # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_project`") collection_formats = {} resource_path = '/projects/{project_id}'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} if 'fields' in params: query_params['fields'] = params['fields'] header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Project', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def validate_project(self, project_id, **kwargs): """ Validate Project ### Validate Project Performs lint validation of all lookml files in the project. Returns a list of errors found, if any. Validating the content of all the files in a project can be computationally intensive for large projects. For best performance, call `validate_project(project_id)` only when you really want to recompute project validation. To quickly display the results of the most recent project validation (without recomputing), use `project_validation_results(project_id)` This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.validate_project(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: ProjectValidation If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.validate_project_with_http_info(project_id, **kwargs) else: (data) = self.validate_project_with_http_info(project_id, **kwargs) return data def validate_project_with_http_info(self, project_id, **kwargs): """ Validate Project ### Validate Project Performs lint validation of all lookml files in the project. Returns a list of errors found, if any. Validating the content of all the files in a project can be computationally intensive for large projects. For best performance, call `validate_project(project_id)` only when you really want to recompute project validation. To quickly display the results of the most recent project validation (without recomputing), use `project_validation_results(project_id)` This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.validate_project_with_http_info(project_id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str project_id: Project Id (required) :param str fields: Requested fields :return: ProjectValidation If the method is called asynchronously, returns the request thread. """ all_params = ['project_id', 'fields'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method validate_project" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'project_id' is set if ('project_id' not in params) or (params['project_id'] is None): raise ValueError("Missing the required parameter `project_id` when calling `validate_project`") collection_formats = {} resource_path = '/projects/{project_id}/validate'.replace('{format}', 'json') path_params = {} if 'project_id' in params: path_params['project_id'] = params['project_id'] query_params = {} if 'fields' in params: query_params['fields'] = params['fields'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ProjectValidation', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
mit
PetePriority/home-assistant
homeassistant/components/verisure/binary_sensor.py
5
1913
""" Interfaces with Verisure sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.verisure/ """ import logging from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.components.verisure import CONF_DOOR_WINDOW from homeassistant.components.verisure import HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure binary sensors.""" sensors = [] hub.update_overview() if int(hub.config.get(CONF_DOOR_WINDOW, 1)): sensors.extend([ VerisureDoorWindowSensor(device_label) for device_label in hub.get( "$.doorWindow.doorWindowDevice[*].deviceLabel")]) add_entities(sensors) class VerisureDoorWindowSensor(BinarySensorDevice): """Representation of a Verisure door window sensor.""" def __init__(self, device_label): """Initialize the Verisure door window sensor.""" self._device_label = device_label @property def name(self): """Return the name of the binary sensor.""" return hub.get_first( "$.doorWindow.doorWindowDevice[?(@.deviceLabel=='%s')].area", self._device_label) @property def is_on(self): """Return the state of the sensor.""" return hub.get_first( "$.doorWindow.doorWindowDevice[?(@.deviceLabel=='%s')].state", self._device_label) == "OPEN" @property def available(self): """Return True if entity is available.""" return hub.get_first( "$.doorWindow.doorWindowDevice[?(@.deviceLabel=='%s')]", self._device_label) is not None # pylint: disable=no-self-use def update(self): """Update the state of the sensor.""" hub.update_overview()
apache-2.0
radjkarl/fancyTools
fancytools/fcollections/TwoDArraySliceIterator.py
1
1824
# coding=utf-8 from __future__ import division class TwoDArraySliceIterator(object): """ a simple iterator that build small slices from a big array >>> import numpy as np >>> arr = np.random.rand(100,100) >>> n_pieces = (2,4) >>> i = TwoDArraySliceIterator( arr.shape, n_pieces ) than iterate through your array as follows: for (s1,s2) in i: print(s1,s2, arr[s1,s2]) """ def __init__(self, main_size, slice_size): self.main_size = main_size self.fx = int(main_size[0] / slice_size[0]) self.fy = int(main_size[1] / slice_size[1]) self.slice_size = slice_size if slice_size in (None, (1, 1)): self.next = self._none def _none(self): if self._stop_next: raise StopIteration() self._stop_next = True return None, None, None, None def __iter__(self): self._reset() return self def _reset(self): self._stop_next = False self.i = 0 self.j = 0 def __next__(self): if self._stop_next: raise StopIteration() p0x = self.i * self.fx p0y = self.j * self.fy if self.i + 1 == self.slice_size[0]: # at border p1x = self.main_size[0] else: p1x = (self.i + 1) * self.fx if self.j + 1 == self.slice_size[1]: # at border p1y = self.main_size[1] else: p1y = (self.j + 1) * self.fy self.i += 1 if self.i == self.slice_size[0]: self.i = 0 self.j += 1 if self.j == self.slice_size[1]: self._reset() self._stop_next = True return slice(p0x, p1x), slice(p0y, p1y) if __name__ == '__main__': import doctest doctest.testmod()
gpl-3.0
kenshay/ImageScripter
Script_Runner/PYTHON/Lib/encodings/cp775.py
272
34476
""" Python Character Mapping Codec cp775 generated from 'VENDORS/MICSFT/PC/CP775.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp775', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x0101, # LATIN SMALL LETTER A WITH MACRON 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0087: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x0088: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x0089: 0x0113, # LATIN SMALL LETTER E WITH MACRON 0x008a: 0x0156, # LATIN CAPITAL LETTER R WITH CEDILLA 0x008b: 0x0157, # LATIN SMALL LETTER R WITH CEDILLA 0x008c: 0x012b, # LATIN SMALL LETTER I WITH MACRON 0x008d: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x0093: 0x014d, # LATIN SMALL LETTER O WITH MACRON 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA 0x0096: 0x00a2, # CENT SIGN 0x0097: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x0098: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: 0x00a4, # CURRENCY SIGN 0x00a0: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON 0x00a1: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00a4: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00a5: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00a6: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00a7: 0x00a6, # BROKEN BAR 0x00a8: 0x00a9, # COPYRIGHT SIGN 0x00a9: 0x00ae, # REGISTERED SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00b6: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00b7: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00b8: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK 0x00be: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK 0x00c7: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00d0: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00d1: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00d2: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00d3: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE 0x00d4: 0x012f, # LATIN SMALL LETTER I WITH OGONEK 0x00d5: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00d6: 0x0173, # LATIN SMALL LETTER U WITH OGONEK 0x00d7: 0x016b, # LATIN SMALL LETTER U WITH MACRON 0x00d8: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S (GERMAN) 0x00e2: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON 0x00e3: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00e4: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00e5: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00e8: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA 0x00e9: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA 0x00ea: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA 0x00eb: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA 0x00ec: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA 0x00ed: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON 0x00ee: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA 0x00ef: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00f3: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00f4: 0x00b6, # PILCROW SIGN 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x00b9, # SUPERSCRIPT ONE 0x00fc: 0x00b3, # SUPERSCRIPT THREE 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Decoding Table decoding_table = ( '\x00' # 0x0000 -> NULL '\x01' # 0x0001 -> START OF HEADING '\x02' # 0x0002 -> START OF TEXT '\x03' # 0x0003 -> END OF TEXT '\x04' # 0x0004 -> END OF TRANSMISSION '\x05' # 0x0005 -> ENQUIRY '\x06' # 0x0006 -> ACKNOWLEDGE '\x07' # 0x0007 -> BELL '\x08' # 0x0008 -> BACKSPACE '\t' # 0x0009 -> HORIZONTAL TABULATION '\n' # 0x000a -> LINE FEED '\x0b' # 0x000b -> VERTICAL TABULATION '\x0c' # 0x000c -> FORM FEED '\r' # 0x000d -> CARRIAGE RETURN '\x0e' # 0x000e -> SHIFT OUT '\x0f' # 0x000f -> SHIFT IN '\x10' # 0x0010 -> DATA LINK ESCAPE '\x11' # 0x0011 -> DEVICE CONTROL ONE '\x12' # 0x0012 -> DEVICE CONTROL TWO '\x13' # 0x0013 -> DEVICE CONTROL THREE '\x14' # 0x0014 -> DEVICE CONTROL FOUR '\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x0016 -> SYNCHRONOUS IDLE '\x17' # 0x0017 -> END OF TRANSMISSION BLOCK '\x18' # 0x0018 -> CANCEL '\x19' # 0x0019 -> END OF MEDIUM '\x1a' # 0x001a -> SUBSTITUTE '\x1b' # 0x001b -> ESCAPE '\x1c' # 0x001c -> FILE SEPARATOR '\x1d' # 0x001d -> GROUP SEPARATOR '\x1e' # 0x001e -> RECORD SEPARATOR '\x1f' # 0x001f -> UNIT SEPARATOR ' ' # 0x0020 -> SPACE '!' # 0x0021 -> EXCLAMATION MARK '"' # 0x0022 -> QUOTATION MARK '#' # 0x0023 -> NUMBER SIGN '$' # 0x0024 -> DOLLAR SIGN '%' # 0x0025 -> PERCENT SIGN '&' # 0x0026 -> AMPERSAND "'" # 0x0027 -> APOSTROPHE '(' # 0x0028 -> LEFT PARENTHESIS ')' # 0x0029 -> RIGHT PARENTHESIS '*' # 0x002a -> ASTERISK '+' # 0x002b -> PLUS SIGN ',' # 0x002c -> COMMA '-' # 0x002d -> HYPHEN-MINUS '.' # 0x002e -> FULL STOP '/' # 0x002f -> SOLIDUS '0' # 0x0030 -> DIGIT ZERO '1' # 0x0031 -> DIGIT ONE '2' # 0x0032 -> DIGIT TWO '3' # 0x0033 -> DIGIT THREE '4' # 0x0034 -> DIGIT FOUR '5' # 0x0035 -> DIGIT FIVE '6' # 0x0036 -> DIGIT SIX '7' # 0x0037 -> DIGIT SEVEN '8' # 0x0038 -> DIGIT EIGHT '9' # 0x0039 -> DIGIT NINE ':' # 0x003a -> COLON ';' # 0x003b -> SEMICOLON '<' # 0x003c -> LESS-THAN SIGN '=' # 0x003d -> EQUALS SIGN '>' # 0x003e -> GREATER-THAN SIGN '?' # 0x003f -> QUESTION MARK '@' # 0x0040 -> COMMERCIAL AT 'A' # 0x0041 -> LATIN CAPITAL LETTER A 'B' # 0x0042 -> LATIN CAPITAL LETTER B 'C' # 0x0043 -> LATIN CAPITAL LETTER C 'D' # 0x0044 -> LATIN CAPITAL LETTER D 'E' # 0x0045 -> LATIN CAPITAL LETTER E 'F' # 0x0046 -> LATIN CAPITAL LETTER F 'G' # 0x0047 -> LATIN CAPITAL LETTER G 'H' # 0x0048 -> LATIN CAPITAL LETTER H 'I' # 0x0049 -> LATIN CAPITAL LETTER I 'J' # 0x004a -> LATIN CAPITAL LETTER J 'K' # 0x004b -> LATIN CAPITAL LETTER K 'L' # 0x004c -> LATIN CAPITAL LETTER L 'M' # 0x004d -> LATIN CAPITAL LETTER M 'N' # 0x004e -> LATIN CAPITAL LETTER N 'O' # 0x004f -> LATIN CAPITAL LETTER O 'P' # 0x0050 -> LATIN CAPITAL LETTER P 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q 'R' # 0x0052 -> LATIN CAPITAL LETTER R 'S' # 0x0053 -> LATIN CAPITAL LETTER S 'T' # 0x0054 -> LATIN CAPITAL LETTER T 'U' # 0x0055 -> LATIN CAPITAL LETTER U 'V' # 0x0056 -> LATIN CAPITAL LETTER V 'W' # 0x0057 -> LATIN CAPITAL LETTER W 'X' # 0x0058 -> LATIN CAPITAL LETTER X 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y 'Z' # 0x005a -> LATIN CAPITAL LETTER Z '[' # 0x005b -> LEFT SQUARE BRACKET '\\' # 0x005c -> REVERSE SOLIDUS ']' # 0x005d -> RIGHT SQUARE BRACKET '^' # 0x005e -> CIRCUMFLEX ACCENT '_' # 0x005f -> LOW LINE '`' # 0x0060 -> GRAVE ACCENT 'a' # 0x0061 -> LATIN SMALL LETTER A 'b' # 0x0062 -> LATIN SMALL LETTER B 'c' # 0x0063 -> LATIN SMALL LETTER C 'd' # 0x0064 -> LATIN SMALL LETTER D 'e' # 0x0065 -> LATIN SMALL LETTER E 'f' # 0x0066 -> LATIN SMALL LETTER F 'g' # 0x0067 -> LATIN SMALL LETTER G 'h' # 0x0068 -> LATIN SMALL LETTER H 'i' # 0x0069 -> LATIN SMALL LETTER I 'j' # 0x006a -> LATIN SMALL LETTER J 'k' # 0x006b -> LATIN SMALL LETTER K 'l' # 0x006c -> LATIN SMALL LETTER L 'm' # 0x006d -> LATIN SMALL LETTER M 'n' # 0x006e -> LATIN SMALL LETTER N 'o' # 0x006f -> LATIN SMALL LETTER O 'p' # 0x0070 -> LATIN SMALL LETTER P 'q' # 0x0071 -> LATIN SMALL LETTER Q 'r' # 0x0072 -> LATIN SMALL LETTER R 's' # 0x0073 -> LATIN SMALL LETTER S 't' # 0x0074 -> LATIN SMALL LETTER T 'u' # 0x0075 -> LATIN SMALL LETTER U 'v' # 0x0076 -> LATIN SMALL LETTER V 'w' # 0x0077 -> LATIN SMALL LETTER W 'x' # 0x0078 -> LATIN SMALL LETTER X 'y' # 0x0079 -> LATIN SMALL LETTER Y 'z' # 0x007a -> LATIN SMALL LETTER Z '{' # 0x007b -> LEFT CURLY BRACKET '|' # 0x007c -> VERTICAL LINE '}' # 0x007d -> RIGHT CURLY BRACKET '~' # 0x007e -> TILDE '\x7f' # 0x007f -> DELETE '\u0106' # 0x0080 -> LATIN CAPITAL LETTER C WITH ACUTE '\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS '\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE '\u0101' # 0x0083 -> LATIN SMALL LETTER A WITH MACRON '\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS '\u0123' # 0x0085 -> LATIN SMALL LETTER G WITH CEDILLA '\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE '\u0107' # 0x0087 -> LATIN SMALL LETTER C WITH ACUTE '\u0142' # 0x0088 -> LATIN SMALL LETTER L WITH STROKE '\u0113' # 0x0089 -> LATIN SMALL LETTER E WITH MACRON '\u0156' # 0x008a -> LATIN CAPITAL LETTER R WITH CEDILLA '\u0157' # 0x008b -> LATIN SMALL LETTER R WITH CEDILLA '\u012b' # 0x008c -> LATIN SMALL LETTER I WITH MACRON '\u0179' # 0x008d -> LATIN CAPITAL LETTER Z WITH ACUTE '\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS '\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE '\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE '\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE '\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE '\u014d' # 0x0093 -> LATIN SMALL LETTER O WITH MACRON '\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS '\u0122' # 0x0095 -> LATIN CAPITAL LETTER G WITH CEDILLA '\xa2' # 0x0096 -> CENT SIGN '\u015a' # 0x0097 -> LATIN CAPITAL LETTER S WITH ACUTE '\u015b' # 0x0098 -> LATIN SMALL LETTER S WITH ACUTE '\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS '\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS '\xf8' # 0x009b -> LATIN SMALL LETTER O WITH STROKE '\xa3' # 0x009c -> POUND SIGN '\xd8' # 0x009d -> LATIN CAPITAL LETTER O WITH STROKE '\xd7' # 0x009e -> MULTIPLICATION SIGN '\xa4' # 0x009f -> CURRENCY SIGN '\u0100' # 0x00a0 -> LATIN CAPITAL LETTER A WITH MACRON '\u012a' # 0x00a1 -> LATIN CAPITAL LETTER I WITH MACRON '\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE '\u017b' # 0x00a3 -> LATIN CAPITAL LETTER Z WITH DOT ABOVE '\u017c' # 0x00a4 -> LATIN SMALL LETTER Z WITH DOT ABOVE '\u017a' # 0x00a5 -> LATIN SMALL LETTER Z WITH ACUTE '\u201d' # 0x00a6 -> RIGHT DOUBLE QUOTATION MARK '\xa6' # 0x00a7 -> BROKEN BAR '\xa9' # 0x00a8 -> COPYRIGHT SIGN '\xae' # 0x00a9 -> REGISTERED SIGN '\xac' # 0x00aa -> NOT SIGN '\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF '\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER '\u0141' # 0x00ad -> LATIN CAPITAL LETTER L WITH STROKE '\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\u2591' # 0x00b0 -> LIGHT SHADE '\u2592' # 0x00b1 -> MEDIUM SHADE '\u2593' # 0x00b2 -> DARK SHADE '\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL '\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT '\u0104' # 0x00b5 -> LATIN CAPITAL LETTER A WITH OGONEK '\u010c' # 0x00b6 -> LATIN CAPITAL LETTER C WITH CARON '\u0118' # 0x00b7 -> LATIN CAPITAL LETTER E WITH OGONEK '\u0116' # 0x00b8 -> LATIN CAPITAL LETTER E WITH DOT ABOVE '\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT '\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL '\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT '\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT '\u012e' # 0x00bd -> LATIN CAPITAL LETTER I WITH OGONEK '\u0160' # 0x00be -> LATIN CAPITAL LETTER S WITH CARON '\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT '\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT '\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL '\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL '\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT '\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL '\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL '\u0172' # 0x00c6 -> LATIN CAPITAL LETTER U WITH OGONEK '\u016a' # 0x00c7 -> LATIN CAPITAL LETTER U WITH MACRON '\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT '\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT '\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL '\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL '\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT '\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL '\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL '\u017d' # 0x00cf -> LATIN CAPITAL LETTER Z WITH CARON '\u0105' # 0x00d0 -> LATIN SMALL LETTER A WITH OGONEK '\u010d' # 0x00d1 -> LATIN SMALL LETTER C WITH CARON '\u0119' # 0x00d2 -> LATIN SMALL LETTER E WITH OGONEK '\u0117' # 0x00d3 -> LATIN SMALL LETTER E WITH DOT ABOVE '\u012f' # 0x00d4 -> LATIN SMALL LETTER I WITH OGONEK '\u0161' # 0x00d5 -> LATIN SMALL LETTER S WITH CARON '\u0173' # 0x00d6 -> LATIN SMALL LETTER U WITH OGONEK '\u016b' # 0x00d7 -> LATIN SMALL LETTER U WITH MACRON '\u017e' # 0x00d8 -> LATIN SMALL LETTER Z WITH CARON '\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT '\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT '\u2588' # 0x00db -> FULL BLOCK '\u2584' # 0x00dc -> LOWER HALF BLOCK '\u258c' # 0x00dd -> LEFT HALF BLOCK '\u2590' # 0x00de -> RIGHT HALF BLOCK '\u2580' # 0x00df -> UPPER HALF BLOCK '\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE '\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S (GERMAN) '\u014c' # 0x00e2 -> LATIN CAPITAL LETTER O WITH MACRON '\u0143' # 0x00e3 -> LATIN CAPITAL LETTER N WITH ACUTE '\xf5' # 0x00e4 -> LATIN SMALL LETTER O WITH TILDE '\xd5' # 0x00e5 -> LATIN CAPITAL LETTER O WITH TILDE '\xb5' # 0x00e6 -> MICRO SIGN '\u0144' # 0x00e7 -> LATIN SMALL LETTER N WITH ACUTE '\u0136' # 0x00e8 -> LATIN CAPITAL LETTER K WITH CEDILLA '\u0137' # 0x00e9 -> LATIN SMALL LETTER K WITH CEDILLA '\u013b' # 0x00ea -> LATIN CAPITAL LETTER L WITH CEDILLA '\u013c' # 0x00eb -> LATIN SMALL LETTER L WITH CEDILLA '\u0146' # 0x00ec -> LATIN SMALL LETTER N WITH CEDILLA '\u0112' # 0x00ed -> LATIN CAPITAL LETTER E WITH MACRON '\u0145' # 0x00ee -> LATIN CAPITAL LETTER N WITH CEDILLA '\u2019' # 0x00ef -> RIGHT SINGLE QUOTATION MARK '\xad' # 0x00f0 -> SOFT HYPHEN '\xb1' # 0x00f1 -> PLUS-MINUS SIGN '\u201c' # 0x00f2 -> LEFT DOUBLE QUOTATION MARK '\xbe' # 0x00f3 -> VULGAR FRACTION THREE QUARTERS '\xb6' # 0x00f4 -> PILCROW SIGN '\xa7' # 0x00f5 -> SECTION SIGN '\xf7' # 0x00f6 -> DIVISION SIGN '\u201e' # 0x00f7 -> DOUBLE LOW-9 QUOTATION MARK '\xb0' # 0x00f8 -> DEGREE SIGN '\u2219' # 0x00f9 -> BULLET OPERATOR '\xb7' # 0x00fa -> MIDDLE DOT '\xb9' # 0x00fb -> SUPERSCRIPT ONE '\xb3' # 0x00fc -> SUPERSCRIPT THREE '\xb2' # 0x00fd -> SUPERSCRIPT TWO '\u25a0' # 0x00fe -> BLACK SQUARE '\xa0' # 0x00ff -> NO-BREAK SPACE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0025: 0x0025, # PERCENT SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00ff, # NO-BREAK SPACE 0x00a2: 0x0096, # CENT SIGN 0x00a3: 0x009c, # POUND SIGN 0x00a4: 0x009f, # CURRENCY SIGN 0x00a6: 0x00a7, # BROKEN BAR 0x00a7: 0x00f5, # SECTION SIGN 0x00a9: 0x00a8, # COPYRIGHT SIGN 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ac: 0x00aa, # NOT SIGN 0x00ad: 0x00f0, # SOFT HYPHEN 0x00ae: 0x00a9, # REGISTERED SIGN 0x00b0: 0x00f8, # DEGREE SIGN 0x00b1: 0x00f1, # PLUS-MINUS SIGN 0x00b2: 0x00fd, # SUPERSCRIPT TWO 0x00b3: 0x00fc, # SUPERSCRIPT THREE 0x00b5: 0x00e6, # MICRO SIGN 0x00b6: 0x00f4, # PILCROW SIGN 0x00b7: 0x00fa, # MIDDLE DOT 0x00b9: 0x00fb, # SUPERSCRIPT ONE 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER 0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF 0x00be: 0x00f3, # VULGAR FRACTION THREE QUARTERS 0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE 0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE 0x00d5: 0x00e5, # LATIN CAPITAL LETTER O WITH TILDE 0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00d7: 0x009e, # MULTIPLICATION SIGN 0x00d8: 0x009d, # LATIN CAPITAL LETTER O WITH STROKE 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S (GERMAN) 0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS 0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE 0x00e6: 0x0091, # LATIN SMALL LIGATURE AE 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE 0x00f5: 0x00e4, # LATIN SMALL LETTER O WITH TILDE 0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS 0x00f7: 0x00f6, # DIVISION SIGN 0x00f8: 0x009b, # LATIN SMALL LETTER O WITH STROKE 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS 0x0100: 0x00a0, # LATIN CAPITAL LETTER A WITH MACRON 0x0101: 0x0083, # LATIN SMALL LETTER A WITH MACRON 0x0104: 0x00b5, # LATIN CAPITAL LETTER A WITH OGONEK 0x0105: 0x00d0, # LATIN SMALL LETTER A WITH OGONEK 0x0106: 0x0080, # LATIN CAPITAL LETTER C WITH ACUTE 0x0107: 0x0087, # LATIN SMALL LETTER C WITH ACUTE 0x010c: 0x00b6, # LATIN CAPITAL LETTER C WITH CARON 0x010d: 0x00d1, # LATIN SMALL LETTER C WITH CARON 0x0112: 0x00ed, # LATIN CAPITAL LETTER E WITH MACRON 0x0113: 0x0089, # LATIN SMALL LETTER E WITH MACRON 0x0116: 0x00b8, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x0117: 0x00d3, # LATIN SMALL LETTER E WITH DOT ABOVE 0x0118: 0x00b7, # LATIN CAPITAL LETTER E WITH OGONEK 0x0119: 0x00d2, # LATIN SMALL LETTER E WITH OGONEK 0x0122: 0x0095, # LATIN CAPITAL LETTER G WITH CEDILLA 0x0123: 0x0085, # LATIN SMALL LETTER G WITH CEDILLA 0x012a: 0x00a1, # LATIN CAPITAL LETTER I WITH MACRON 0x012b: 0x008c, # LATIN SMALL LETTER I WITH MACRON 0x012e: 0x00bd, # LATIN CAPITAL LETTER I WITH OGONEK 0x012f: 0x00d4, # LATIN SMALL LETTER I WITH OGONEK 0x0136: 0x00e8, # LATIN CAPITAL LETTER K WITH CEDILLA 0x0137: 0x00e9, # LATIN SMALL LETTER K WITH CEDILLA 0x013b: 0x00ea, # LATIN CAPITAL LETTER L WITH CEDILLA 0x013c: 0x00eb, # LATIN SMALL LETTER L WITH CEDILLA 0x0141: 0x00ad, # LATIN CAPITAL LETTER L WITH STROKE 0x0142: 0x0088, # LATIN SMALL LETTER L WITH STROKE 0x0143: 0x00e3, # LATIN CAPITAL LETTER N WITH ACUTE 0x0144: 0x00e7, # LATIN SMALL LETTER N WITH ACUTE 0x0145: 0x00ee, # LATIN CAPITAL LETTER N WITH CEDILLA 0x0146: 0x00ec, # LATIN SMALL LETTER N WITH CEDILLA 0x014c: 0x00e2, # LATIN CAPITAL LETTER O WITH MACRON 0x014d: 0x0093, # LATIN SMALL LETTER O WITH MACRON 0x0156: 0x008a, # LATIN CAPITAL LETTER R WITH CEDILLA 0x0157: 0x008b, # LATIN SMALL LETTER R WITH CEDILLA 0x015a: 0x0097, # LATIN CAPITAL LETTER S WITH ACUTE 0x015b: 0x0098, # LATIN SMALL LETTER S WITH ACUTE 0x0160: 0x00be, # LATIN CAPITAL LETTER S WITH CARON 0x0161: 0x00d5, # LATIN SMALL LETTER S WITH CARON 0x016a: 0x00c7, # LATIN CAPITAL LETTER U WITH MACRON 0x016b: 0x00d7, # LATIN SMALL LETTER U WITH MACRON 0x0172: 0x00c6, # LATIN CAPITAL LETTER U WITH OGONEK 0x0173: 0x00d6, # LATIN SMALL LETTER U WITH OGONEK 0x0179: 0x008d, # LATIN CAPITAL LETTER Z WITH ACUTE 0x017a: 0x00a5, # LATIN SMALL LETTER Z WITH ACUTE 0x017b: 0x00a3, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x017c: 0x00a4, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x017d: 0x00cf, # LATIN CAPITAL LETTER Z WITH CARON 0x017e: 0x00d8, # LATIN SMALL LETTER Z WITH CARON 0x2019: 0x00ef, # RIGHT SINGLE QUOTATION MARK 0x201c: 0x00f2, # LEFT DOUBLE QUOTATION MARK 0x201d: 0x00a6, # RIGHT DOUBLE QUOTATION MARK 0x201e: 0x00f7, # DOUBLE LOW-9 QUOTATION MARK 0x2219: 0x00f9, # BULLET OPERATOR 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2580: 0x00df, # UPPER HALF BLOCK 0x2584: 0x00dc, # LOWER HALF BLOCK 0x2588: 0x00db, # FULL BLOCK 0x258c: 0x00dd, # LEFT HALF BLOCK 0x2590: 0x00de, # RIGHT HALF BLOCK 0x2591: 0x00b0, # LIGHT SHADE 0x2592: 0x00b1, # MEDIUM SHADE 0x2593: 0x00b2, # DARK SHADE 0x25a0: 0x00fe, # BLACK SQUARE }
gpl-3.0
PanDAWMS/pilot
RunJobArgo.py
2
36685
# Class definition: # RunJobMira # [Add description here] # Instances are generated with RunJobFactory via pUtil::getRunJob() # Implemented as a singleton class # http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern # Import relevant python/pilot modules from RunJobHPC import RunJobHPC # Parent RunJobHPC class import Site, pUtil, Job, Node, RunJobUtilities from pUtil import tolog, isAnalysisJob, readpar, getExperiment from FileStateClient import updateFileStates, dumpFileStates from ErrorDiagnosis import ErrorDiagnosis # import here to avoid issues seen at BU with missing module from PilotErrors import PilotErrors from datetime import datetime from MessageInterface import MessageInterface from ArgoJob import ArgoJob, ArgoJobStatus from BalsamJob import BalsamJob from SiteInformation import SiteInformation # Standard python modules import os, sys, commands, time, optparse, shlex, stat import traceback import atexit, signal class RunJobArgo(RunJobHPC): # private data members __runjob = "RunJobArgo" # String defining the sub class __instance = None # Boolean used by subclasses to become a Singleton __error = PilotErrors() # PilotErrors object # public data members process = ""# zjet, wjet, wqq, wcjet, etc. base_filename = "alpout" # should be the same as in the input cards # controls for warmup warmup_phase0_number_events = None warmup_phase0_number_iterations = None warmup_phase1_number_events = None warmup_wall_minutes = None warmup_preprocess = 'alpgen_warmup_presubmit.sh' warmup_preprocess_args = None # controls for event generation (weighted gen + unweighting) evtgen_phase0_number_events = None evtgen_phase0_number_iterations = None evtgen_phase1_number_events = None evtgen_nodes = None evtgen_processes_per_node = None evtgen_wall_minutes = None evtgen_executable = 'alpgenCombo.sh' evtgen_scheduler_args = '--mode=script' evtgen_preprocess = 'alpgen_presubmit.sh' evtgen_postprocess = 'alpgen_postsubmit.sh' working_path = None input_url = None output_url = None pdf_filename = 'cteq6l1.tbl' username = None serial_site = 'argo_cluster' parallel_site = None group_identifier = None athena_input_card_executable = 'get_alpgen_input_card.py' athena_postprocess = 'alpgen_create_input_cards.py' athena_postprocess_log = 'alpgen_create_input_cards.log' ecm = None run_number = None job_config = None evgen_job_opts = None athena_input_card_name = 'input_card.mode_1.dat' # card output by Generate_trf grid_ftp_server = 'atlasgridftp02.hep.anl.gov' grid_ftp_protocol = 'gsiftp://' job_working_path = '/grid/atlas/hpc/argo/jobs' argo_job = [] # Required methods def __init__(self): """ Default initialization """ pass def __new__(cls, *args, **kwargs): """ Override the __new__ method to make the class a singleton """ if not cls.__instance: cls.__instance = super(RunJobHPC, cls).__new__(cls, *args, **kwargs) return cls.__instance def getRunJob(self): """ Return a string with the experiment name """ return self.__runjob def getRunJobFileName(self): """ Return the filename of the module """ return super(RunJobArgo, self).getRunJobFileName() # def argumentParser(self): <-- see example in RunJob.py def allowLoopingJobKiller(self): """ Should the pilot search for looping jobs? """ # The pilot has the ability to monitor the payload work directory. If there are no updated files within a certain # time limit, the pilot will consider the as stuck (looping) and will kill it. The looping time limits are set # in environment.py (see e.g. loopingLimitDefaultProd) return False def get_argo_job(self, job): ##----------------------- # create argo job ##----------------------- argo_job = ArgoJob() argo_job.input_url = None #self.GRID_FTP_PROTOCOL + self.GRID_FTP_SERVER + self.job_path if self.input_url is not None: argo_job.input_url = self.input_url argo_job.output_url = self.grid_ftp_protocol + self.grid_ftp_server + self.job_path if self.output_url is not None: argo_job.output_url = self.output_url argo_job.username = self.username argo_job.group_identifier = self.group_identifier ##----------------------- # create get alpgen input cards balsam job ##----------------------- input_file_imode0 = self.base_filename + '.input.0' input_file_imode1 = self.base_filename + '.input.1' input_file_imode2 = self.base_filename + '.input.2' input_cards_job = BalsamJob() input_cards_job.executable = self.athena_input_card_executable input_cards_job.executable_args = ('-e ' + self.ecm + ' -r ' + self.run_number + ' -o ' + self.job_config + ' -j ' + self.evgen_job_opts) input_cards_job.output_files = [input_file_imode0, input_file_imode1, input_file_imode2, self.athena_postprocess_log] input_cards_job.nodes = 1 input_cards_job.processes_per_node = 1 input_cards_job.wall_minutes = 0 # running on condor cluster so does not need time input_cards_job.username = self.username input_cards_job.target_site = self.serial_site input_cards_job.postprocess = self.athena_postprocess input_cards_job.postprocess_args = (' -i ' + self.athena_input_card_name + ' -p ' + self.process + ' -n ' + str(self.evtgen_phase1_number_events) + ' --log-filename=' + str(self.athena_postprocess_log)) if self.warmup_phase0_number_events is not None: input_cards_job.postprocess_args += ' --wmp-evts-itr=' + str(self.warmup_phase0_number_events) if self.warmup_phase0_number_iterations is not None: input_cards_job.postprocess_args += ' --wmp-nitr=' + str(self.warmup_phase0_number_iterations) if self.warmup_phase1_number_events is not None: input_cards_job.postprocess_args += ' --wmp-evts=' + str(self.warmup_phase1_number_events) argo_job.add_job(input_cards_job) ##----------------------- # create warm-up job ##----------------------- # create grid filenames grid1 = self.base_filename + '.grid1' grid2 = self.base_filename + '.grid2' # create warmup balsam job warmup = BalsamJob() warmup.executable = self.process + 'gen90_mpi' warmup.executable_args = input_file_imode0 warmup.input_files = [input_file_imode0] warmup.output_files = [grid1,grid2] warmup.nodes = 1 warmup.processes_per_node = 1 warmup.wall_minutes = 0 # running on condor cluster so does not need time warmup.username = self.username warmup.target_site = self.serial_site warmup.preprocess = self.warmup_preprocess argo_job.add_job(warmup) ##----------------------- # create event generation job ##----------------------- # create executable alpgen_exe = self.process + 'gen90_mpi_ramdisk_nomrstpdfs' if 'argo_cluster' in self.parallel_site: # no ramdisk needed on argo_cluster alpgen_exe = self.process + 'gen90_mpi' # create filenames unw = self.base_filename + '.unw.gz' unw_par = self.base_filename + '_unw.par' wgt = self.base_filename + '.wgt' wgt_par = self.base_filename + '.par' directoryList_before = 'directoryList_before.txt' directoryList_after = 'directoryList_after.txt' # create event gen balsam job evtgen = BalsamJob() evtgen.executable = self.evtgen_executable evtgen.executable_args = (alpgen_exe + ' ' + input_file_imode1 + ' ' + input_file_imode2 + ' ' + str(self.evtgen_processes_per_node)) evtgen.input_files = [grid1, grid2, input_file_imode1, input_file_imode2] evtgen.output_files = [unw, unw_par, directoryList_before, directoryList_after, self.evtgen_postprocess + '.out', self.evtgen_postprocess + '.err', ] evtgen.preprocess = self.evtgen_preprocess evtgen.postprocess = self.evtgen_postprocess evtgen.postprocess_args = self.base_filename evtgen.nodes = self.evtgen_nodes evtgen.processes_per_node = self.evtgen_processes_per_node evtgen.wall_minutes = self.evtgen_wall_minutes evtgen.username = self.username evtgen.scheduler_args = self.evtgen_scheduler_args evtgen.target_site = self.parallel_site argo_job.add_job(evtgen) return argo_job def setup(self, job, jobSite, thisExperiment): """ prepare the setup and get the run command list """ # start setup time counter t0 = time.time() ec = 0 # split up the job parameters to be able to loop over the tasks jobParameters = job.jobPars.split("\n")[0] jobTrf = job.trf.split("\n")[0] parser = optparse.OptionParser(description=' program to submit alpgen jobs like a pilot') parser.add_option('-p','--process',dest='process',help='Alpgen Process, i.e. zjet, wjet, wqq, etc.') parser.add_option('-n','--nevts',dest='nevts',help='Number of weighted events requested in input file for weighted event generation',type='int') parser.add_option('-g','--group-id',dest='group_identifier',help='User specified string that helps the user group jobs together.') parser.add_option('-e','--ecm',dest='ecm',help='Center of Mass Energy.') parser.add_option('-r','--run-number',dest='run_number',help='Run Number') parser.add_option('-c','--jobConfig',dest='jobConfig',help='Job Options that will used from the Job Config tarball, i.e. MC12JobOptions/MC12.<Run Number>.<description>.py') parser.add_option('-j','--evgenJobOpts',dest='evgenJobOpts',help='Job Config tarball, i.e. MC12JobOpts-XX-YY-ZZ.tar.gz') parser.add_option('','--dev',dest='dev',help='For development only.',action='store_true',default=False) parser.add_option('-q','--status-queue',dest='enable_status_queue',help='Enable the setting of the message queue parameter in the ArgoJob, which means ARGO will not send message updates for this job to the queue with its job ID.',action='store_true',default=False) #parser.add_option('-a','--warmup-evts',dest='warmup_evts',help='For Warmup Step: Three numbers seperated by commas giving the number of events per iteration, number of iterations, and final number of events to generate. Example: "10000,10,1000000"') parser.add_option('-b','--evtgen-evts',dest='evtgen_evts',help='For Event Generation Step: The number of events to generation in the event generation step. The ouput of unweighted events tends to be less so request more than you want. For example W+0jets gives you 70\%, W+1jet gives you 16%, W+2jet gives you 5%, W+3jet gives you 1%, and so on.', type='int') parser.add_option('-o','--num-nodes',dest='numnodes',help='number of nodes to use on destination machine',type='int') parser.add_option('-u','--ranks-per-node',dest='ranks_per_node',help='number of MPI ranks per node to use on destination machine',type='int') parser.add_option('-t','--wall-time',dest='walltime',help='The wall time to submit to the queue in minutes.',type='int') parser.add_option('-s','--site',dest='site',help='Balsam site name on which to run the event generation') parser.add_option('-x','--no-submit',dest='submit',help='do not submit the message to ARGO. For testing purposes.',action='store_false',default=True) parser.add_option('','--wmp-evts-itr',dest='wm_evts_per_itr',help='Warmup: Number of weighted events per interation.') parser.add_option('','--wmp-nitr',dest='wm_nitr',help='Warmup: Number of iterations') parser.add_option('','--wmp-evts',dest='wm_evts',help='Warmup: Number of final events to produce.') try: options, args = parser.parse_args(shlex.split(jobParameters)) except: ec = self.__error.ERR_SETUPFAILURE job.pilotErrorDiag = "Failure to parse job arguments" tolog("Failure to parse job arguments for ARGO job") return ec, job tolog("ARGO job will be launched with next parameters: %s" % jobParameters) self.process = options.process self.username = 'pilot, %s' % job.prodUserID[:120] #os.environ['USER'] self.group_identifier = options.group_identifier self.ecm = options.ecm self.run_number = options.run_number self.job_config = options.jobConfig self.evgen_job_opts = options.evgenJobOpts self.warmup_phase0_number_events = options.wm_evts_per_itr self.warmup_phase0_number_iterations = options.wm_nitr self.warmup_phase1_number_events = options.wm_evts self.evtgen_phase1_number_events = options.evtgen_evts self.evtgen_nodes = options.numnodes self.evtgen_processes_per_node = options.ranks_per_node self.evtgen_wall_minutes = options.walltime self.parallel_site = options.site self.dev = options.dev self.job_path = os.path.join(self.job_working_path,job.jobId) tolog("ARGO job path: %s" % self.job_path) self.argo_job = self.get_argo_job(job) if options.dev: job.serial_site = 'argo_cluster_dev' # verify that the multi-trf job is setup properly os.chdir(jobSite.workdir) tolog("Current job workdir is %s" % os.getcwd()) job.timeSetup = int(time.time() - t0) tolog("Total setup time: %d s" % (job.timeSetup)) return ec, job def executePayload(self, thisExperiment, job): t0 = os.times() res_tuple = None # loop over all run commands (only >1 for multi-trfs) getstatusoutput_was_interrupted = False job_status = None tolog("About to launch ARGO job") # Poll MQ for Job Status try: # Initiate MQ interface and send job self.argo_job.job_status_routing_key = '%s_job_status' % job.jobId #'status_' + jobID si = SiteInformation() mi = MessageInterface() mi.host = 'atlasgridftp02.hep.anl.gov' mi.port = 5671 mi.ssl_cert = si.getSSLCertificate() #'/grid/atlas/hpc/pilot_certs/xrootdsrv-cert.pem' proxy_cert_path = si.getSSLCertificate() mi.ssl_cert = os.path.dirname(proxy_cert_path) + "/rabbitmq-cert.pem" if 'X509_USER_CERT' in os.environ.keys(): mi.ssl_cert = os.environ['X509_USER_CERT'] #'/users/hpcusers/balsam_dev/gridsecurity/jchilders/xrootdsrv-cert.pem' mi.ssl_key = mi.ssl_cert #'/grid/atlas/hpc/pilot_certs/xrootdsrv-key.pem' mi.ssl_key = os.path.dirname(proxy_cert_path) + "/rabbitmq-key.pem" if 'X509_USER_KEY' in os.environ.keys(): mi.ssl_key = os.environ['X509_USER_KEY'] #'/users/hpcusers/balsam_dev/gridsecurity/jchilders/xrootdsrv-key.pem' #mi.ssl_ca_certs = os.path.dirname(proxy_cert_path) + "/rabbitmq-cacerts.pem" mi.ssl_ca_certs = '/grid/atlas/hpc/pilot_certs/cacerts.pem' #if 'X509_CA_CERTS' in os.environ.keys(): # mi.ssl_ca_certs = os.environ['X509_CA_CERTS'] #'/users/hpcusers/balsam_dev/gridsecurity/jchilders/cacerts.pem' #tolog("CA certs: %s" % (mi.ssl_ca_certs)) ca_certs = os.path.dirname(proxy_cert_path) + "/rabbitmq-cacerts.pem" if os.path.isfile(ca_certs): mi.ssl_ca_certs = ca_certs mi.exchange_name = 'argo_users' #Create queue to get messages about ARGO Job status from MQ tolog('Opening connection with MQ') mi.open_blocking_connection() tolog('Create queue [%s] to retrieve messages with job status' % self.argo_job.job_status_routing_key) mi.create_queue(self.argo_job.job_status_routing_key, self.argo_job.job_status_routing_key) # submit ARGO job to MQ #tolog('Opening connection with MQ') #mi.open_blocking_connection() routing_key = 'argo_job' if self.dev: routing_key = 'argo_job_dev' tolog('Sending msg with job to ARGO') mi.send_msg(self.argo_job.serialize(), routing_key) tolog(' done sending ') # Waiting till job done or failed ARGO_err_msg = '' while True: time.sleep(5) message = mi.receive_msg(self.argo_job.job_status_routing_key, True) if message[2]: tolog ("Got message from queue [%s]: method [%s], properties [%s], body [ %s ]" % (self.argo_job.job_status_routing_key, message[0], message[1], message[2])) job_status = ArgoJobStatus.get_from_message(message[2]) job.hpcStatus = job_status.state rt = RunJobUtilities.updatePilotServer(job, self.getPilotServer(), self.getPilotPort()) tolog("Extracted state: %s" % job_status.state) if job_status.state == job_status.HISTORY: res_tuple = (0, "Done") break elif job_status.is_failed(): res_tuple = (1, "Failed") ARGO_err_msg = ARGO_err_msg + ' ' + job_status.message elif job_status.state == job_status.FAILED: res_tuple = (1, "Failed") ARGO_err_msg = ARGO_err_msg + ' ' + job_status.message runJob.failJob(1, 0, job, ins=job.inFiles, pilotErrorDiag=ARGO_err_msg) break time.sleep(5) mi.close() tolog(' closing connection to MQ') tolog("Job State: %s" % (job_status.state)) #job.timeExe = int(fork_job.finished - fork_job.started) #################################################### except Exception, e: tolog("!!FAILED!!3000!! Failed to run command %s" % str(e)) getstatusoutput_was_interrupted = True res_tuple = (1, "Failed") self.failJob(0, self.__error.ERR_GENERALERROR, job, pilotErrorDiag=str(e)) else: if res_tuple[0] == 0: tolog("ARGO Job finished") else: tolog("ARGO Job failed: res = %s" % (str(res_tuple))) t1 = os.times() job.timeExe = int(round(t1[4] - t0[4])) tolog("Original exit code: %s" % (res_tuple[0])) if res_tuple[0] != None: tolog("Exit code: %s (returned from OS)" % (res_tuple[0]%255)) res0 = res_tuple[0]%255 if job_status: exitMsg = job_status.message else: exitMsg = res_tuple[1] else: tolog("Exit code: None (returned from OS, Job was canceled or interrupted)") res0 = None exitMsg = "Job was canceled by internal call" # check the job report for any exit code that should replace the res_tuple[0] res = (res0, res_tuple[1], exitMsg) # dump an extract of the payload output tolog("NOTE: For %s output, see files %s, %s" % (job.payload, job.stdout, job.stderr)) # JEM job-end callback try: from JEMstub import notifyJobEnd2JEM notifyJobEnd2JEM(job, tolog) except: pass # don't care (fire and forget) return res, job, getstatusoutput_was_interrupted if __name__ == "__main__": tolog("Starting RunJobArgo") # Get error handler error = PilotErrors() # Get runJob object runJob = RunJobArgo() # Define a new parent group os.setpgrp() # Protect the runJob code with exception handling hP_ret = False try: # always use this filename as the new jobDef module name import newJobDef jobSite = Site.Site() return_tuple = runJob.argumentParser() tolog("argumentParser returned: %s" % str(return_tuple)) jobSite.setSiteInfo(return_tuple) # jobSite.setSiteInfo(argParser(sys.argv[1:])) # reassign workdir for this job jobSite.workdir = jobSite.wntmpdir if runJob.getPilotLogFilename() != "": pUtil.setPilotlogFilename(runJob.getPilotLogFilename()) # set node info node = Node.Node() node.setNodeName(os.uname()[1]) node.collectWNInfo(jobSite.workdir) # redirect stder sys.stderr = open("%s/runjob.stderr" % (jobSite.workdir), "w") tolog("Current job workdir is: %s" % os.getcwd()) tolog("Site workdir is: %s" % jobSite.workdir) # get the experiment object thisExperiment = getExperiment(runJob.getExperiment()) tolog("RunJob will serve experiment: %s" % (thisExperiment.getExperiment())) # set the cache (used e.g. by LSST) #if runJob.getCache(): # thisExperiment.setCache(runJob.getCache()) #JR = JobRecovery() try: job = Job.Job() job.setJobDef(newJobDef.job) job.workdir = jobSite.workdir job.experiment = runJob.getExperiment() # figure out and set payload file names job.setPayloadName(thisExperiment.getPayloadName(job)) except Exception, e: pilotErrorDiag = "Failed to process job info: %s" % str(e) tolog("!!WARNING!!3000!! %s" % (pilotErrorDiag)) runJob.failJob(0, error.ERR_UNKNOWN, job, pilotErrorDiag=pilotErrorDiag) # prepare for the output file data directory # (will only created for jobs that end up in a 'holding' state) job.datadir = runJob.getParentWorkDir() + "/PandaJob_%s_data" % (job.jobId) # register cleanup function atexit.register(runJob.cleanup, job) # to trigger an exception so that the SIGTERM signal can trigger cleanup function to run # because by default signal terminates process without cleanup. def sig2exc(sig, frm): """ signal handler """ error = PilotErrors() runJob.setGlobalPilotErrorDiag("!!FAILED!!3000!! SIGTERM Signal %s is caught in child pid=%d!\n" % (sig, os.getpid())) tolog(runJob.getGlobalPilotErrorDiag()) if sig == signal.SIGTERM: runJob.setGlobalErrorCode(error.ERR_SIGTERM) elif sig == signal.SIGQUIT: runJob.setGlobalErrorCode(error.ERR_SIGQUIT) elif sig == signal.SIGSEGV: runJob.setGlobalErrorCode(error.ERR_SIGSEGV) elif sig == signal.SIGXCPU: runJob.setGlobalErrorCode(error.ERR_SIGXCPU) elif sig == signal.SIGBUS: runJob.setGlobalErrorCode(error.ERR_SIGBUS) elif sig == signal.SIGUSR1: runJob.setGlobalErrorCode(error.ERR_SIGUSR1) else: runJob.setGlobalErrorCode(error.ERR_KILLSIGNAL) runJob.setFailureCode(runJob.getGlobalErrorCode) # print to stderr print >> sys.stderr, runJob.getGlobalPilotErrorDiag() raise SystemError(sig) signal.signal(signal.SIGTERM, sig2exc) signal.signal(signal.SIGQUIT, sig2exc) signal.signal(signal.SIGSEGV, sig2exc) signal.signal(signal.SIGXCPU, sig2exc) signal.signal(signal.SIGBUS, sig2exc) # see if it's an analysis job or not analysisJob = isAnalysisJob(job.trf.split(",")[0]) if analysisJob: tolog("User analysis job") else: tolog("Production job") tolog("runJobArgo received a job with prodSourceLabel=%s" % (job.prodSourceLabel)) # setup starts here ................................................................................ # update the job state file job.jobState = "setup" #_retjs = JR.updateJobStateTest(job, jobSite, node, mode="test") # send [especially] the process group back to the pilot job.setState([job.jobState, 0, 0]) rt = RunJobUtilities.updatePilotServer(job, runJob.getPilotServer(), runJob.getPilotPort()) # prepare the setup and get the run command list ec, job = runJob.setup(job, jobSite, thisExperiment) if ec != 0: tolog("!!WARNING!!2999!! runJob setup failed: %s" % (job.pilotErrorDiag)) runJob.failJob(0, ec, job, pilotErrorDiag=job.pilotErrorDiag) tolog("Setup has finished successfully") # job has been updated, display it again job.displayJob() # (setup ends here) ................................................................................ tolog("Setting stage-in state until all input files have been copied") job.setState(["stagein", 0, 0]) # send the special setup string back to the pilot (needed for the log transfer on xrdcp systems) rt = RunJobUtilities.updatePilotServer(job, runJob.getPilotServer(), runJob.getPilotPort()) # stage-in ......................................................................................... # update the job state file job.jobState = "stagein" #_retjs = JR.updateJobStateTest(job, jobSite, node, mode="test") # update copysetup[in] for production jobs if brokerage has decided that remote I/O should be used if job.transferType == 'direct': tolog('Brokerage has set transfer type to \"%s\" (remote I/O will be attempted for input files, any special access mode will be ignored)' %\ (job.transferType)) RunJobUtilities.updateCopysetups('', transferType=job.transferType) # stage-in all input files (if necessary) job, ins, statusPFCTurl, usedFAXandDirectIO = runJob.stageIn(job, jobSite, analysisJob) if job.result[2] != 0: tolog("Failing job with ec: %d" % (ec)) runJob.failJob(0, job.result[2], job, ins=ins, pilotErrorDiag=job.pilotErrorDiag) # after stageIn, all file transfer modes are known (copy_to_scratch, file_stager, remote_io) # consult the FileState file dictionary if cmd3 should be updated (--directIn should not be set if all # remote_io modes have been changed to copy_to_scratch as can happen with ByteStream files) # and update the run command list if necessary. # in addition to the above, if FAX is used as a primary site mover and direct access is enabled, then # the run command should not contain the --oldPrefix, --newPrefix options but use --usePFCTurl #if job.inFiles != ['']: # runCommandList = RunJobUtilities.updateRunCommandList(runCommandList, runJob.getParentWorkDir(), job.jobId, statusPFCTurl, analysisJob, usedFAXandDirectIO) # (stage-in ends here) ............................................................................. # change to running state since all input files have been staged tolog("Changing to running state since all input files have been staged") job.setState(["running", 0, 0]) rt = RunJobUtilities.updatePilotServer(job, runJob.getPilotServer(), runJob.getPilotPort()) # update the job state file job.jobState = "running" #_retjs = JR.updateJobStateTest(job, jobSite, node, mode="test") # run the job(s) ................................................................................... # Set ATLAS_CONDDB if necessary, and other env vars RunJobUtilities.setEnvVars(jobSite.sitename) # execute the payload res, job, getstatusoutput_was_interrupted = runJob.executePayload(thisExperiment, job) tolog("Check ARGO output: %s" % runJob.job_path) # if payload leaves the input files, delete them explicitly if ins: ec = pUtil.removeFiles(job.workdir, ins) # payload error handling ed = ErrorDiagnosis() if res[0] == None: job.jobState = "cancelled" job.setState(["cancelled", 0, 0]) rt = RunJobUtilities.updatePilotServer(job, runJob.getPilotServer(), runJob.getPilotPort()) #else: # job = ed.interpretPayload(job, res, getstatusoutput_was_interrupted, current_job_number, runCommandList, runJob.getFailureCode()) if job.result[1] != 0 or job.result[2] != 0: runJob.failJob(job.result[1], job.result[2], job, pilotErrorDiag=job.pilotErrorDiag) # stage-out ........................................................................................ # update the job state file tolog(runJob.getOutputDir()) job.jobState = "stageout" #_retjs = JR.updateJobStateTest(job, jobSite, node, mode="test") # verify and prepare and the output files for transfer ec, pilotErrorDiag, outs, outsDict = RunJobUtilities.prepareOutFiles(job.outFiles, job.logFile, runJob.job_path) if ec: # missing output file (only error code from prepareOutFiles) runJob.failJob(job.result[1], ec, job, pilotErrorDiag=pilotErrorDiag) tolog("outsDict: %s" % str(outsDict)) # update the current file states updateFileStates(outs, runJob.getParentWorkDir(), job.jobId, mode="file_state", state="created") dumpFileStates(runJob.getParentWorkDir(), job.jobId) # create xml string to pass to dispatcher for atlas jobs outputFileInfo = {} if outs or (job.logFile and job.logFile != ''): # get the datasets for the output files dsname, datasetDict = runJob.getDatasets(job) # re-create the metadata.xml file, putting guids of ALL output files into it. # output files that miss guids from the job itself will get guids in PFCxml function # first rename and copy the trf metadata file for non-build jobs if not pUtil.isBuildJob(outs): runJob.moveTrfMetadata(job.workdir, job.jobId) # create the metadata for the output + log files ec, job, outputFileInfo = runJob.createFileMetadata(list(outs), job, outsDict, dsname, datasetDict, jobSite.sitename, analysisJob=analysisJob) if ec: runJob.failJob(0, ec, job, pilotErrorDiag=job.pilotErrorDiag) # move output files from workdir to local DDM area finalUpdateDone = False if outs: tolog("Setting stage-out state until all output files have been copied") job.setState(["stageout", 0, 0]) rt = RunJobUtilities.updatePilotServer(job, runJob.getPilotServer(), runJob.getPilotPort()) # stage-out output files ec, job, rf, latereg = runJob.stageOut(job, jobSite, outs, analysisJob, dsname, datasetDict, outputFileInfo) # error handling if job.result[0] == "finished" or ec == error.ERR_PUTFUNCNOCALL: rt = RunJobUtilities.updatePilotServer(job, runJob.getPilotServer(), runJob.getPilotPort(), final=True) else: rt = RunJobUtilities.updatePilotServer(job, runJob.getPilotServer(), runJob.getPilotPort(), final=True, latereg=latereg) if ec == error.ERR_NOSTORAGE: # update the current file states for all files since nothing could be transferred updateFileStates(outs, runJob.getParentWorkDir(), job.jobId, mode="file_state", state="not_transferred") dumpFileStates(runJob.getParentWorkDir(), job.jobId) finalUpdateDone = True if ec != 0: runJob.sysExit(job, rf) # (stage-out ends here) ....................................................................... job.setState(["finished", 0, 0]) if not finalUpdateDone: rt = RunJobUtilities.updatePilotServer(job, runJob.getPilotServer(), runJob.getPilotPort(), final=True) runJob.sysExit(job) except Exception, errorMsg: error = PilotErrors() if runJob.getGlobalPilotErrorDiag() != "": pilotErrorDiag = "Exception caught in runJobArgo: %s" % (runJob.getGlobalPilotErrorDiag()) else: pilotErrorDiag = "Exception caught in runJobArgo: %s" % str(errorMsg) if 'format_exc' in traceback.__all__: pilotErrorDiag += ", " + traceback.format_exc() try: tolog("!!FAILED!!3001!! %s" % (pilotErrorDiag)) except Exception, e: if len(pilotErrorDiag) > 10000: pilotErrorDiag = pilotErrorDiag[:10000] tolog("!!FAILED!!3001!! Truncated (%s): %s" % (e, pilotErrorDiag)) else: pilotErrorDiag = "Exception caught in runJob: %s" % (e) tolog("!!FAILED!!3001!! %s" % (pilotErrorDiag)) # # restore the proxy if necessary # if hP_ret: # rP_ret = proxyguard.restoreProxy() # if not rP_ret: # tolog("Warning: Problems with storage can occur since proxy could not be restored") # else: # hP_ret = False # tolog("ProxyGuard has finished successfully") tolog("sys.path=%s" % str(sys.path)) cmd = "pwd;ls -lF %s;ls -lF;ls -lF .." % (runJob.getPilotInitDir()) tolog("Executing command: %s" % (cmd)) out = commands.getoutput(cmd) tolog("%s" % (out)) job = Job.Job() job.setJobDef(newJobDef.job) job.pilotErrorDiag = pilotErrorDiag job.result[0] = "failed" if runJob.getGlobalErrorCode() != 0: job.result[2] = runJob.getGlobalErrorCode() else: job.result[2] = error.ERR_RUNJOBEXC tolog("Failing job with error code: %d" % (job.result[2])) # fail the job without calling sysExit/cleanup (will be called anyway) runJob.failJob(0, job.result[2], job, pilotErrorDiag=pilotErrorDiag, docleanup=False)
apache-2.0
gauribhoite/personfinder
env/site-packages/django/core/cache/backends/db.py
104
8808
"Database cache backend." import base64 from datetime import datetime from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.db import DatabaseError, connections, router, transaction from django.db.backends.utils import typecast_timestamp from django.utils import six, timezone from django.utils.encoding import force_bytes try: from django.utils.six.moves import cPickle as pickle except ImportError: import pickle class Options(object): """A class that will quack like a Django model _meta class. This allows cache operations to be controlled by the router """ def __init__(self, table): self.db_table = table self.app_label = 'django_cache' self.model_name = 'cacheentry' self.verbose_name = 'cache entry' self.verbose_name_plural = 'cache entries' self.object_name = 'CacheEntry' self.abstract = False self.managed = True self.proxy = False self.swapped = False class BaseDatabaseCache(BaseCache): def __init__(self, table, params): BaseCache.__init__(self, params) self._table = table class CacheEntry(object): _meta = Options(table) self.cache_model_class = CacheEntry class DatabaseCache(BaseDatabaseCache): # This class uses cursors provided by the database connection. This means # it reads expiration values as aware or naive datetimes depending on the # value of USE_TZ. They must be compared to aware or naive representations # of "now" respectively. # But it bypasses the ORM for write operations. As a consequence, aware # datetimes aren't made naive for databases that don't support time zones. # We work around this problem by always using naive datetimes when writing # expiration values, in UTC when USE_TZ = True and in local time otherwise. def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) with connections[db].cursor() as cursor: cursor.execute("SELECT cache_key, value, expires FROM %s " "WHERE cache_key = %%s" % table, [key]) row = cursor.fetchone() if row is None: return default now = timezone.now() expires = row[2] if connections[db].features.needs_datetime_string_cast and not isinstance(expires, datetime): # Note: typecasting is needed by some 3rd party database backends. # All core backends work without typecasting, so be careful about # changes here - test suite will NOT pick regressions here. expires = typecast_timestamp(str(expires)) if expires < now: db = router.db_for_write(self.cache_model_class) with connections[db].cursor() as cursor: cursor.execute("DELETE FROM %s " "WHERE cache_key = %%s" % table, [key]) return default value = connections[db].ops.process_clob(row[1]) return pickle.loads(base64.b64decode(force_bytes(value))) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) self._base_set('set', key, value, timeout) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) return self._base_set('add', key, value, timeout) def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT): timeout = self.get_backend_timeout(timeout) db = router.db_for_write(self.cache_model_class) table = connections[db].ops.quote_name(self._table) with connections[db].cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM %s" % table) num = cursor.fetchone()[0] now = timezone.now() now = now.replace(microsecond=0) if timeout is None: exp = datetime.max elif settings.USE_TZ: exp = datetime.utcfromtimestamp(timeout) else: exp = datetime.fromtimestamp(timeout) exp = exp.replace(microsecond=0) if num > self._max_entries: self._cull(db, cursor, now) pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) b64encoded = base64.b64encode(pickled) # The DB column is expecting a string, so make sure the value is a # string, not bytes. Refs #19274. if six.PY3: b64encoded = b64encoded.decode('latin1') try: # Note: typecasting for datetimes is needed by some 3rd party # database backends. All core backends work without typecasting, # so be careful about changes here - test suite will NOT pick # regressions. with transaction.atomic(using=db): cursor.execute("SELECT cache_key, expires FROM %s " "WHERE cache_key = %%s" % table, [key]) result = cursor.fetchone() if result: current_expires = result[1] if (connections[db].features.needs_datetime_string_cast and not isinstance(current_expires, datetime)): current_expires = typecast_timestamp(str(current_expires)) exp = connections[db].ops.value_to_db_datetime(exp) if result and (mode == 'set' or (mode == 'add' and current_expires < now)): cursor.execute("UPDATE %s SET value = %%s, expires = %%s " "WHERE cache_key = %%s" % table, [b64encoded, exp, key]) else: cursor.execute("INSERT INTO %s (cache_key, value, expires) " "VALUES (%%s, %%s, %%s)" % table, [key, b64encoded, exp]) except DatabaseError: # To be threadsafe, updates/inserts are allowed to fail silently return False else: return True def delete(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_write(self.cache_model_class) table = connections[db].ops.quote_name(self._table) with connections[db].cursor() as cursor: cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % table, [key]) def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) if settings.USE_TZ: now = datetime.utcnow() else: now = datetime.now() now = now.replace(microsecond=0) with connections[db].cursor() as cursor: cursor.execute("SELECT cache_key FROM %s " "WHERE cache_key = %%s and expires > %%s" % table, [key, connections[db].ops.value_to_db_datetime(now)]) return cursor.fetchone() is not None def _cull(self, db, cursor, now): if self._cull_frequency == 0: self.clear() else: # When USE_TZ is True, 'now' will be an aware datetime in UTC. now = now.replace(tzinfo=None) table = connections[db].ops.quote_name(self._table) cursor.execute("DELETE FROM %s WHERE expires < %%s" % table, [connections[db].ops.value_to_db_datetime(now)]) cursor.execute("SELECT COUNT(*) FROM %s" % table) num = cursor.fetchone()[0] if num > self._max_entries: cull_num = num // self._cull_frequency cursor.execute( connections[db].ops.cache_key_culling_sql() % table, [cull_num]) cursor.execute("DELETE FROM %s " "WHERE cache_key < %%s" % table, [cursor.fetchone()[0]]) def clear(self): db = router.db_for_write(self.cache_model_class) table = connections[db].ops.quote_name(self._table) with connections[db].cursor() as cursor: cursor.execute('DELETE FROM %s' % table)
apache-2.0
tago-io/tago-python
tago/account/plan.py
1
1281
import requests # Used to make HTTP requests import json # Used to parse JSON import os # Used to infer environment variables API_TAGO = os.environ.get('TAGO_API') or 'https://api.tago.io' REALTIME = os.environ.get('TAGO_REALTIME') or 'https://realtime.tago.io' class Plan: def __init__(self, acc_token): self.token = acc_token self.default_headers = { 'content-type': 'application/json', 'Account-Token': acc_token} return def setPlanParameters(self, data): data = data if data else {} return requests.post('{api_endpoint}/account/plan'.format(api_endpoint=API_TAGO), headers=self.default_headers, json=data).json() def getPriceToUpdate(self, data): return requests.get('{api_endpoint}/account/plan_value'.format(api_endpoint=API_TAGO), headers=self.default_headers, params=json.dumps(data)).json() def getActivePlan(self): return requests.get('{api_endpoint}/account/plan'.format(api_endpoint=API_TAGO), headers=self.default_headers).json() def getCurrentPrices(self): return requests.get('{api_endpoint}/pricing'.format(api_endpoint=API_TAGO), headers=self.default_headers).json() def summary(self): return requests.get('{api_endpoint}/billing'.format(api_endpoint=API_TAGO), headers=self.default_headers).json()
mit
maestro-hybrid-cloud/keystone
keystone/common/sql/migration_helpers.py
10
8055
# Copyright 2013 OpenStack Foundation # Copyright 2013 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import sys import migrate from migrate import exceptions from oslo_config import cfg from oslo_db.sqlalchemy import migration from oslo_serialization import jsonutils from oslo_utils import importutils import six import sqlalchemy from keystone.common import sql from keystone.common.sql import migrate_repo from keystone import contrib from keystone import exception from keystone.i18n import _ CONF = cfg.CONF DEFAULT_EXTENSIONS = ['endpoint_filter', 'endpoint_policy', 'federation', 'oauth1', 'revoke', ] def get_default_domain(): # Return the reference used for the default domain structure during # sql migrations. return { 'id': CONF.identity.default_domain_id, 'name': 'Default', 'enabled': True, 'extra': jsonutils.dumps({'description': 'Owns users and tenants ' '(i.e. projects) available ' 'on Identity API v2.'})} # Different RDBMSs use different schemes for naming the Foreign Key # Constraints. SQLAlchemy does not yet attempt to determine the name # for the constraint, and instead attempts to deduce it from the column. # This fails on MySQL. def get_constraints_names(table, column_name): fkeys = [fk.name for fk in table.constraints if (isinstance(fk, sqlalchemy.ForeignKeyConstraint) and column_name in fk.columns)] return fkeys # remove_constraints and add_constraints both accept a list of dictionaries # that contain: # {'table': a sqlalchemy table. The constraint is added to dropped from # this table. # 'fk_column': the name of a column on the above table, The constraint # is added to or dropped from this column # 'ref_column':a sqlalchemy column object. This is the reference column # for the constraint. def remove_constraints(constraints): for constraint_def in constraints: constraint_names = get_constraints_names(constraint_def['table'], constraint_def['fk_column']) for constraint_name in constraint_names: migrate.ForeignKeyConstraint( columns=[getattr(constraint_def['table'].c, constraint_def['fk_column'])], refcolumns=[constraint_def['ref_column']], name=constraint_name).drop() def add_constraints(constraints): for constraint_def in constraints: if constraint_def['table'].kwargs.get('mysql_engine') == 'MyISAM': # Don't try to create constraint when using MyISAM because it's # not supported. continue ref_col = constraint_def['ref_column'] ref_engine = ref_col.table.kwargs.get('mysql_engine') if ref_engine == 'MyISAM': # Don't try to create constraint when using MyISAM because it's # not supported. continue migrate.ForeignKeyConstraint( columns=[getattr(constraint_def['table'].c, constraint_def['fk_column'])], refcolumns=[constraint_def['ref_column']]).create() def rename_tables_with_constraints(renames, constraints, engine): """Renames tables with foreign key constraints. Tables are renamed after first removing constraints. The constraints are replaced after the rename is complete. This works on databases that don't support renaming tables that have constraints on them (DB2). `renames` is a dict, mapping {'to_table_name': from_table, ...} """ if engine.name != 'sqlite': # Sqlite doesn't support constraints, so nothing to remove. remove_constraints(constraints) for to_table_name in renames: from_table = renames[to_table_name] from_table.rename(to_table_name) if engine != 'sqlite': add_constraints(constraints) def find_migrate_repo(package=None, repo_name='migrate_repo'): package = package or sql path = os.path.abspath(os.path.join( os.path.dirname(package.__file__), repo_name)) if os.path.isdir(path): return path raise exception.MigrationNotProvided(package.__name__, path) def _sync_common_repo(version): abs_path = find_migrate_repo() init_version = migrate_repo.DB_INIT_VERSION engine = sql.get_engine() _assert_not_schema_downgrade(version=version) migration.db_sync(engine, abs_path, version=version, init_version=init_version, sanity_check=False) def _assert_not_schema_downgrade(extension=None, version=None): if version is not None: try: current_ver = int(six.text_type(get_db_version(extension))) if int(version) < current_ver: raise migration.exception.DbMigrationError() except exceptions.DatabaseNotControlledError: # NOTE(morganfainberg): The database is not controlled, this action # cannot be a downgrade. pass def _sync_extension_repo(extension, version): init_version = 0 engine = sql.get_engine() try: package_name = '.'.join((contrib.__name__, extension)) package = importutils.import_module(package_name) except ImportError: raise ImportError(_("%s extension does not exist.") % package_name) try: abs_path = find_migrate_repo(package) try: migration.db_version_control(sql.get_engine(), abs_path) # Register the repo with the version control API # If it already knows about the repo, it will throw # an exception that we can safely ignore except exceptions.DatabaseAlreadyControlledError: pass except exception.MigrationNotProvided as e: print(e) sys.exit(1) _assert_not_schema_downgrade(extension=extension, version=version) migration.db_sync(engine, abs_path, version=version, init_version=init_version, sanity_check=False) def sync_database_to_version(extension=None, version=None): if not extension: _sync_common_repo(version) # If version is greater than 0, it is for the common # repository only, and only that will be synchronized. if version is None: for default_extension in DEFAULT_EXTENSIONS: _sync_extension_repo(default_extension, version) else: _sync_extension_repo(extension, version) def get_db_version(extension=None): if not extension: return migration.db_version(sql.get_engine(), find_migrate_repo(), migrate_repo.DB_INIT_VERSION) try: package_name = '.'.join((contrib.__name__, extension)) package = importutils.import_module(package_name) except ImportError: raise ImportError(_("%s extension does not exist.") % package_name) return migration.db_version( sql.get_engine(), find_migrate_repo(package), 0) def print_db_version(extension=None): try: db_version = get_db_version(extension=extension) print(db_version) except exception.MigrationNotProvided as e: print(e) sys.exit(1)
apache-2.0
RacingTornado/harvester_scraper
discovery/DNS/lazy.py
23
1499
# $Id: lazy.py,v 1.5.2.1 2007/05/22 20:23:38 customdesigned Exp $ # # This file is part of the pydns project. # Homepage: http://pydns.sourceforge.net # # This code is covered by the standard Python License. # # routines for lazy people. import Base import string def revlookup(name): "convenience routine for doing a reverse lookup of an address" if Base.defaults['server'] == []: Base.DiscoverNameServers() a = string.split(name, '.') a.reverse() b = string.join(a, '.') + '.in-addr.arpa' # this will only return one of any records returned. return Base.DnsRequest(b, qtype='ptr').req().answers[0]['data'] def mxlookup(name): """ convenience routine for doing an MX lookup of a name. returns a sorted list of (preference, mail exchanger) records """ if Base.defaults['server'] == []: Base.DiscoverNameServers() a = Base.DnsRequest(name, qtype='mx').req().answers l = sorted(map(lambda x: x['data'], a)) return l # # $Log: lazy.py,v $ # Revision 1.5.2.1 2007/05/22 20:23:38 customdesigned # Lazy call to DiscoverNameServers # # Revision 1.5 2002/05/06 06:14:38 anthonybaxter # reformat, move import to top of file. # # Revision 1.4 2002/03/19 12:41:33 anthonybaxter # tabnannied and reindented everything. 4 space indent, no tabs. # yay. # # Revision 1.3 2001/08/09 09:08:55 anthonybaxter # added identifying header to top of each file # # Revision 1.2 2001/07/19 06:57:07 anthony # cvs keywords added # #
gpl-2.0
Don42/youtube-dl
youtube_dl/extractor/videofyme.py
111
1750
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( int_or_none, parse_iso8601, ) class VideofyMeIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.videofy\.me/.+?|p\.videofy\.me/v)/(?P<id>\d+)(&|#|$)' IE_NAME = 'videofy.me' _TEST = { 'url': 'http://www.videofy.me/thisisvideofyme/1100701', 'md5': 'c77d700bdc16ae2e9f3c26019bd96143', 'info_dict': { 'id': '1100701', 'ext': 'mp4', 'title': 'This is VideofyMe', 'description': '', 'upload_date': '20130326', 'timestamp': 1364288959, 'uploader': 'VideofyMe', 'uploader_id': 'thisisvideofyme', 'view_count': int, 'likes': int, 'comment_count': int, }, } def _real_extract(self, url): video_id = self._match_id(url) config = self._download_json('http://vf-player-info-loader.herokuapp.com/%s.json' % video_id, video_id)['videoinfo'] video = config.get('video') blog = config.get('blog', {}) return { 'id': video_id, 'title': video['title'], 'url': video['sources']['source']['url'], 'thumbnail': video.get('thumb'), 'description': video.get('description'), 'timestamp': parse_iso8601(video.get('date')), 'uploader': blog.get('name'), 'uploader_id': blog.get('identifier'), 'view_count': int_or_none(self._search_regex(r'([0-9]+)', video.get('views'), 'view count', fatal=False)), 'likes': int_or_none(video.get('likes')), 'comment_count': int_or_none(video.get('nrOfComments')), }
unlicense
c0defreak/python-for-android
python-modules/twisted/twisted/test/test_udp.py
56
24076
# -*- test-case-name: twisted.test.test_udp -*- # Copyright (c) 2001-2010 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for implementations of L{IReactorUDP} and L{IReactorMulticast}. """ from twisted.trial import unittest, util from twisted.internet.defer import Deferred, gatherResults, maybeDeferred from twisted.internet import protocol, reactor, error, defer, interfaces, udp from twisted.python import runtime class Mixin: started = 0 stopped = 0 startedDeferred = None def __init__(self): self.packets = [] def startProtocol(self): self.started = 1 if self.startedDeferred is not None: d, self.startedDeferred = self.startedDeferred, None d.callback(None) def stopProtocol(self): self.stopped = 1 class Server(Mixin, protocol.DatagramProtocol): packetReceived = None refused = 0 def datagramReceived(self, data, addr): self.packets.append((data, addr)) if self.packetReceived is not None: d, self.packetReceived = self.packetReceived, None d.callback(None) class Client(Mixin, protocol.ConnectedDatagramProtocol): packetReceived = None refused = 0 def datagramReceived(self, data): self.packets.append(data) if self.packetReceived is not None: d, self.packetReceived = self.packetReceived, None d.callback(None) def connectionFailed(self, failure): if self.startedDeferred is not None: d, self.startedDeferred = self.startedDeferred, None d.errback(failure) self.failure = failure def connectionRefused(self): if self.startedDeferred is not None: d, self.startedDeferred = self.startedDeferred, None d.errback(error.ConnectionRefusedError("yup")) self.refused = 1 class GoodClient(Server): def connectionRefused(self): if self.startedDeferred is not None: d, self.startedDeferred = self.startedDeferred, None d.errback(error.ConnectionRefusedError("yup")) self.refused = 1 class BadClientError(Exception): """ Raised by BadClient at the end of every datagramReceived call to try and screw stuff up. """ class BadClient(protocol.DatagramProtocol): """ A DatagramProtocol which always raises an exception from datagramReceived. Used to test error handling behavior in the reactor for that method. """ d = None def setDeferred(self, d): """ Set the Deferred which will be called back when datagramReceived is called. """ self.d = d def datagramReceived(self, bytes, addr): if self.d is not None: d, self.d = self.d, None d.callback(bytes) raise BadClientError("Application code is very buggy!") class UDPTestCase(unittest.TestCase): def testOldAddress(self): server = Server() d = server.startedDeferred = defer.Deferred() p = reactor.listenUDP(0, server, interface="127.0.0.1") def cbStarted(ignored): addr = p.getHost() self.assertEquals(addr, ('INET_UDP', addr.host, addr.port)) return p.stopListening() return d.addCallback(cbStarted) testOldAddress.suppress = [ util.suppress(message='IPv4Address.__getitem__', category=DeprecationWarning)] def testStartStop(self): server = Server() d = server.startedDeferred = defer.Deferred() port1 = reactor.listenUDP(0, server, interface="127.0.0.1") def cbStarted(ignored): self.assertEquals(server.started, 1) self.assertEquals(server.stopped, 0) return port1.stopListening() def cbStopped(ignored): self.assertEquals(server.stopped, 1) return d.addCallback(cbStarted).addCallback(cbStopped) def testRebind(self): # Ensure binding the same DatagramProtocol repeatedly invokes all # the right callbacks. server = Server() d = server.startedDeferred = defer.Deferred() p = reactor.listenUDP(0, server, interface="127.0.0.1") def cbStarted(ignored, port): return port.stopListening() def cbStopped(ignored): d = server.startedDeferred = defer.Deferred() p = reactor.listenUDP(0, server, interface="127.0.0.1") return d.addCallback(cbStarted, p) return d.addCallback(cbStarted, p) def testBindError(self): server = Server() d = server.startedDeferred = defer.Deferred() port = reactor.listenUDP(0, server, interface='127.0.0.1') def cbStarted(ignored): self.assertEquals(port.getHost(), server.transport.getHost()) server2 = Server() self.assertRaises( error.CannotListenError, reactor.listenUDP, port.getHost().port, server2, interface='127.0.0.1') d.addCallback(cbStarted) def cbFinished(ignored): return port.stopListening() d.addCallback(cbFinished) return d def testSendPackets(self): server = Server() serverStarted = server.startedDeferred = defer.Deferred() port1 = reactor.listenUDP(0, server, interface="127.0.0.1") client = GoodClient() clientStarted = client.startedDeferred = defer.Deferred() def cbServerStarted(ignored): self.port2 = reactor.listenUDP(0, client, interface="127.0.0.1") return clientStarted d = serverStarted.addCallback(cbServerStarted) def cbClientStarted(ignored): client.transport.connect("127.0.0.1", server.transport.getHost().port) cAddr = client.transport.getHost() sAddr = server.transport.getHost() serverSend = client.packetReceived = defer.Deferred() server.transport.write("hello", (cAddr.host, cAddr.port)) clientWrites = [ ("a",), ("b", None), ("c", (sAddr.host, sAddr.port))] def cbClientSend(ignored): if clientWrites: nextClientWrite = server.packetReceived = defer.Deferred() nextClientWrite.addCallback(cbClientSend) client.transport.write(*clientWrites.pop(0)) return nextClientWrite # No one will ever call .errback on either of these Deferreds, # but there is a non-trivial amount of test code which might # cause them to fail somehow. So fireOnOneErrback=True. return defer.DeferredList([ cbClientSend(None), serverSend], fireOnOneErrback=True) d.addCallback(cbClientStarted) def cbSendsFinished(ignored): cAddr = client.transport.getHost() sAddr = server.transport.getHost() self.assertEquals( client.packets, [("hello", (sAddr.host, sAddr.port))]) clientAddr = (cAddr.host, cAddr.port) self.assertEquals( server.packets, [("a", clientAddr), ("b", clientAddr), ("c", clientAddr)]) d.addCallback(cbSendsFinished) def cbFinished(ignored): return defer.DeferredList([ defer.maybeDeferred(port1.stopListening), defer.maybeDeferred(self.port2.stopListening)], fireOnOneErrback=True) d.addCallback(cbFinished) return d def testConnectionRefused(self): # assume no one listening on port 80 UDP client = GoodClient() clientStarted = client.startedDeferred = defer.Deferred() port = reactor.listenUDP(0, client, interface="127.0.0.1") server = Server() serverStarted = server.startedDeferred = defer.Deferred() port2 = reactor.listenUDP(0, server, interface="127.0.0.1") d = defer.DeferredList( [clientStarted, serverStarted], fireOnOneErrback=True) def cbStarted(ignored): connectionRefused = client.startedDeferred = defer.Deferred() client.transport.connect("127.0.0.1", 80) for i in range(10): client.transport.write(str(i)) server.transport.write(str(i), ("127.0.0.1", 80)) return self.assertFailure( connectionRefused, error.ConnectionRefusedError) d.addCallback(cbStarted) def cbFinished(ignored): return defer.DeferredList([ defer.maybeDeferred(port.stopListening), defer.maybeDeferred(port2.stopListening)], fireOnOneErrback=True) d.addCallback(cbFinished) return d def testBadConnect(self): client = GoodClient() port = reactor.listenUDP(0, client, interface="127.0.0.1") self.assertRaises(ValueError, client.transport.connect, "localhost", 80) client.transport.connect("127.0.0.1", 80) self.assertRaises(RuntimeError, client.transport.connect, "127.0.0.1", 80) return port.stopListening() def testDatagramReceivedError(self): """ Test that when datagramReceived raises an exception it is logged but the port is not disconnected. """ finalDeferred = defer.Deferred() def cbCompleted(ign): """ Flush the exceptions which the reactor should have logged and make sure they're actually there. """ errs = self.flushLoggedErrors(BadClientError) self.assertEquals(len(errs), 2, "Incorrectly found %d errors, expected 2" % (len(errs),)) finalDeferred.addCallback(cbCompleted) client = BadClient() port = reactor.listenUDP(0, client, interface='127.0.0.1') def cbCleanup(result): """ Disconnect the port we started and pass on whatever was given to us in case it was a Failure. """ return defer.maybeDeferred(port.stopListening).addBoth(lambda ign: result) finalDeferred.addBoth(cbCleanup) addr = port.getHost() # UDP is not reliable. Try to send as many as 60 packets before giving # up. Conceivably, all sixty could be lost, but they probably won't be # unless all UDP traffic is being dropped, and then the rest of these # UDP tests will likely fail as well. Ideally, this test (and probably # others) wouldn't even use actual UDP traffic: instead, they would # stub out the socket with a fake one which could be made to behave in # whatever way the test desires. Unfortunately, this is hard because # of differences in various reactor implementations. attempts = range(60) succeededAttempts = [] def makeAttempt(): """ Send one packet to the listening BadClient. Set up a 0.1 second timeout to do re-transmits in case the packet is dropped. When two packets have been received by the BadClient, stop sending and let the finalDeferred's callbacks do some assertions. """ if not attempts: try: self.fail("Not enough packets received") except: finalDeferred.errback() self.failIfIdentical(client.transport, None, "UDP Protocol lost its transport") packet = str(attempts.pop(0)) packetDeferred = defer.Deferred() client.setDeferred(packetDeferred) client.transport.write(packet, (addr.host, addr.port)) def cbPacketReceived(packet): """ A packet arrived. Cancel the timeout for it, record it, and maybe finish the test. """ timeoutCall.cancel() succeededAttempts.append(packet) if len(succeededAttempts) == 2: # The second error has not yet been logged, since the # exception which causes it hasn't even been raised yet. # Give the datagramReceived call a chance to finish, then # let the test finish asserting things. reactor.callLater(0, finalDeferred.callback, None) else: makeAttempt() def ebPacketTimeout(err): """ The packet wasn't received quickly enough. Try sending another one. It doesn't matter if the packet for which this was the timeout eventually arrives: makeAttempt throws away the Deferred on which this function is the errback, so when datagramReceived callbacks, so it won't be on this Deferred, so it won't raise an AlreadyCalledError. """ makeAttempt() packetDeferred.addCallbacks(cbPacketReceived, ebPacketTimeout) packetDeferred.addErrback(finalDeferred.errback) timeoutCall = reactor.callLater( 0.1, packetDeferred.errback, error.TimeoutError( "Timed out in testDatagramReceivedError")) makeAttempt() return finalDeferred def testPortRepr(self): client = GoodClient() p = reactor.listenUDP(0, client) portNo = str(p.getHost().port) self.failIf(repr(p).find(portNo) == -1) def stoppedListening(ign): self.failIf(repr(p).find(portNo) != -1) d = defer.maybeDeferred(p.stopListening) d.addCallback(stoppedListening) return d def test_NoWarningOnBroadcast(self): """ C{'<broadcast>'} is an alternative way to say C{'255.255.255.255'} ({socket.gethostbyname("<broadcast>")} returns C{'255.255.255.255'}), so because it becomes a valid IP address, no deprecation warning about passing hostnames to L{twisted.internet.udp.Port.write} needs to be emitted by C{write()} in this case. """ class fakeSocket: def sendto(self, foo, bar): pass p = udp.Port(0, Server()) p.socket = fakeSocket() p.write("test", ("<broadcast>", 1234)) warnings = self.flushWarnings([self.test_NoWarningOnBroadcast]) self.assertEquals(len(warnings), 0) class ReactorShutdownInteraction(unittest.TestCase): """Test reactor shutdown interaction""" def setUp(self): """Start a UDP port""" self.server = Server() self.port = reactor.listenUDP(0, self.server, interface='127.0.0.1') def tearDown(self): """Stop the UDP port""" return self.port.stopListening() def testShutdownFromDatagramReceived(self): """Test reactor shutdown while in a recvfrom() loop""" # udp.Port's doRead calls recvfrom() in a loop, as an optimization. # It is important this loop terminate under various conditions. # Previously, if datagramReceived synchronously invoked # reactor.stop(), under certain reactors, the Port's socket would # synchronously disappear, causing an AttributeError inside that # loop. This was mishandled, causing the loop to spin forever. # This test is primarily to ensure that the loop never spins # forever. finished = defer.Deferred() pr = self.server.packetReceived = defer.Deferred() def pktRece(ignored): # Simulate reactor.stop() behavior :( self.server.transport.connectionLost() # Then delay this Deferred chain until the protocol has been # disconnected, as the reactor should do in an error condition # such as we are inducing. This is very much a whitebox test. reactor.callLater(0, finished.callback, None) pr.addCallback(pktRece) def flushErrors(ignored): # We are breaking abstraction and calling private APIs, any # number of horrible errors might occur. As long as the reactor # doesn't hang, this test is satisfied. (There may be room for # another, stricter test.) self.flushLoggedErrors() finished.addCallback(flushErrors) self.server.transport.write('\0' * 64, ('127.0.0.1', self.server.transport.getHost().port)) return finished class MulticastTestCase(unittest.TestCase): def setUp(self): self.server = Server() self.client = Client() # multicast won't work if we listen over loopback, apparently self.port1 = reactor.listenMulticast(0, self.server) self.port2 = reactor.listenMulticast(0, self.client) self.client.transport.connect( "127.0.0.1", self.server.transport.getHost().port) def tearDown(self): return gatherResults([ maybeDeferred(self.port1.stopListening), maybeDeferred(self.port2.stopListening)]) def testTTL(self): for o in self.client, self.server: self.assertEquals(o.transport.getTTL(), 1) o.transport.setTTL(2) self.assertEquals(o.transport.getTTL(), 2) def test_loopback(self): """ Test that after loopback mode has been set, multicast packets are delivered to their sender. """ self.assertEquals(self.server.transport.getLoopbackMode(), 1) addr = self.server.transport.getHost() joined = self.server.transport.joinGroup("225.0.0.250") def cbJoined(ignored): d = self.server.packetReceived = Deferred() self.server.transport.write("hello", ("225.0.0.250", addr.port)) return d joined.addCallback(cbJoined) def cbPacket(ignored): self.assertEqual(len(self.server.packets), 1) self.server.transport.setLoopbackMode(0) self.assertEquals(self.server.transport.getLoopbackMode(), 0) self.server.transport.write("hello", ("225.0.0.250", addr.port)) # This is fairly lame. d = Deferred() reactor.callLater(0, d.callback, None) return d joined.addCallback(cbPacket) def cbNoPacket(ignored): self.assertEqual(len(self.server.packets), 1) joined.addCallback(cbNoPacket) return joined def test_interface(self): """ Test C{getOutgoingInterface} and C{setOutgoingInterface}. """ self.assertEqual( self.client.transport.getOutgoingInterface(), "0.0.0.0") self.assertEqual( self.server.transport.getOutgoingInterface(), "0.0.0.0") d1 = self.client.transport.setOutgoingInterface("127.0.0.1") d2 = self.server.transport.setOutgoingInterface("127.0.0.1") result = gatherResults([d1, d2]) def cbInterfaces(ignored): self.assertEqual( self.client.transport.getOutgoingInterface(), "127.0.0.1") self.assertEqual( self.server.transport.getOutgoingInterface(), "127.0.0.1") result.addCallback(cbInterfaces) return result def test_joinLeave(self): """ Test that multicast a group can be joined and left. """ d = self.client.transport.joinGroup("225.0.0.250") def clientJoined(ignored): return self.client.transport.leaveGroup("225.0.0.250") d.addCallback(clientJoined) def clientLeft(ignored): return self.server.transport.joinGroup("225.0.0.250") d.addCallback(clientLeft) def serverJoined(ignored): return self.server.transport.leaveGroup("225.0.0.250") d.addCallback(serverJoined) return d def test_joinFailure(self): """ Test that an attempt to join an address which is not a multicast address fails with L{error.MulticastJoinError}. """ # 127.0.0.1 is not a multicast address, so joining it should fail. return self.assertFailure( self.client.transport.joinGroup("127.0.0.1"), error.MulticastJoinError) if runtime.platform.isWindows() and not runtime.platform.isVista(): test_joinFailure.todo = "Windows' multicast is wonky" def test_multicast(self): """ Test that a multicast group can be joined and messages sent to and received from it. """ c = Server() p = reactor.listenMulticast(0, c) addr = self.server.transport.getHost() joined = self.server.transport.joinGroup("225.0.0.250") def cbJoined(ignored): d = self.server.packetReceived = Deferred() c.transport.write("hello world", ("225.0.0.250", addr.port)) return d joined.addCallback(cbJoined) def cbPacket(ignored): self.assertEquals(self.server.packets[0][0], "hello world") joined.addCallback(cbPacket) def cleanup(passthrough): result = maybeDeferred(p.stopListening) result.addCallback(lambda ign: passthrough) return result joined.addCallback(cleanup) return joined def test_multiListen(self): """ Test that multiple sockets can listen on the same multicast port and that they both receive multicast messages directed to that address. """ firstClient = Server() firstPort = reactor.listenMulticast( 0, firstClient, listenMultiple=True) portno = firstPort.getHost().port secondClient = Server() secondPort = reactor.listenMulticast( portno, secondClient, listenMultiple=True) joined = self.server.transport.joinGroup("225.0.0.250") def serverJoined(ignored): d1 = firstClient.packetReceived = Deferred() d2 = secondClient.packetReceived = Deferred() firstClient.transport.write("hello world", ("225.0.0.250", portno)) return gatherResults([d1, d2]) joined.addCallback(serverJoined) def gotPackets(ignored): self.assertEquals(firstClient.packets[0][0], "hello world") self.assertEquals(secondClient.packets[0][0], "hello world") joined.addCallback(gotPackets) def cleanup(passthrough): result = gatherResults([ maybeDeferred(firstPort.stopListening), maybeDeferred(secondPort.stopListening)]) result.addCallback(lambda ign: passthrough) return result joined.addBoth(cleanup) return joined if runtime.platform.isWindows(): test_multiListen.skip = ("on non-linux platforms it appears multiple " "processes can listen, but not multiple sockets " "in same process?") if not interfaces.IReactorUDP(reactor, None): UDPTestCase.skip = "This reactor does not support UDP" ReactorShutdownInteraction.skip = "This reactor does not support UDP" if not interfaces.IReactorMulticast(reactor, None): MulticastTestCase.skip = "This reactor does not support multicast" def checkForLinux22(): import os if os.path.exists("/proc/version"): s = open("/proc/version").read() if s.startswith("Linux version"): s = s.split()[2] if s.split(".")[:2] == ["2", "2"]: f = MulticastTestCase.testInterface.im_func f.todo = "figure out why this fails in linux 2.2" checkForLinux22()
apache-2.0
WeerakoonOS/iShop
Ishop 10.12.2017/Ishop/assets/bootstrap-datepicker/docs/conf.py
171
8002
# -*- coding: utf-8 -*- # # bootstrap-datepicker documentation build configuration file, created by # sphinx-quickstart on Fri Aug 2 14:45:57 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. #version = '' # The full version, including alpha/beta/rc tags. #release = '' import sphinx_rtd_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' primary_domain = 'js' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'bootstrap-datepicker' copyright = u'2016, eternicode' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' highlight_language = 'javascript' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = ['_themes',] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'bootstrap-datepickerdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'bootstrap-datepicker.tex', u'bootstrap-datepicker Documentation', u'eternicode', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'bootstrap-datepicker', u'bootstrap-datepicker Documentation', [u'eternicode'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'bootstrap-datepicker', u'bootstrap-datepicker Documentation', u'eternicode', 'bootstrap-datepicker', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
mit
kushG/osf.io
website/addons/s3/routes.py
1
1822
from framework.routing import Rule, json_renderer from website.addons.s3 import views settings_routes = { 'rules': [ Rule( [ '/project/<pid>/s3/newbucket/', '/project/<pid>/node/<nid>/s3/newbucket/', ], 'post', views.crud.create_new_bucket, json_renderer ), Rule( '/settings/s3/', 'post', views.config.s3_authorize_user, json_renderer ), Rule( [ '/project/<pid>/s3/settings/', '/project/<pid>/node/<nid>/s3/settings/', ], 'post', views.config.s3_node_settings, json_renderer, ), Rule( [ '/project/<pid>/s3/settings/', '/project/<pid>/node/<nid>/s3/settings/', '/project/<pid>/s3/config/', '/project/<pid>/node/<nid>/s3/config/', ], 'delete', views.config.s3_remove_node_settings, json_renderer, ), Rule( [ '/project/<pid>/s3/import-auth/', '/project/<pid>/node/<nid>/s3/import-auth/', ], 'post', views.config.s3_node_import_auth, json_renderer, ), Rule( [ '/project/<pid>/s3/authorize/', '/project/<pid>/node/<nid>/s3/authorize/', ], 'post', views.config.s3_authorize_node, json_renderer, ), Rule( '/settings/s3/', 'delete', views.config.s3_remove_user_settings, json_renderer, ), ], 'prefix': '/api/v1', }
apache-2.0
Charlex/django-calaccess-raw-data
calaccess_raw/admin/other.py
29
6985
from __future__ import unicode_literals from django.contrib import admin from calaccess_raw import models from .base import BaseAdmin class AcronymsCdAdmin(BaseAdmin): list_display = ("acronym", "stands_for", "effect_dt", "a_desc") date_hierarchy = 'effect_dt' search_fields = ("acronym", "a_desc") class AddressCdAdmin(BaseAdmin): pass class BallotMeasuresCdAdmin(BaseAdmin): list_display = ("measure_name", "election_date", "jurisdiction") list_filter = ("jurisdiction",) search_fields = ("measure_name",) class EfsFilingLogCdAdmin(BaseAdmin): list_display = ( "id", "filing_date", "filingstatus", "filer_id", "vendor", "form_type", ) class FilersCdAdmin(BaseAdmin): pass class FilerAcronymsCdAdmin(BaseAdmin): pass class FilerAddressCdAdmin(BaseAdmin): list_display = ( "filer_id", "adrid", "effect_dt", "add_type" ) class FilerEthicsClassCdAdmin(BaseAdmin): pass class FilerInterestsCdAdmin(BaseAdmin): pass @admin.register(models.FilerLinksCd) class FilerLinksCdAdmin(BaseAdmin): list_display = ( "filer_id_a", "filer_id_b", "link_type", "active_flg", "effect_dt", "termination_dt", ) list_filter = ( "active_flg", "link_type" ) search_fields = ("filer_id_a", "filer_id_b") class FilerStatusTypesCdAdmin(BaseAdmin): list_display = ( "status_type", "status_desc" ) class FilerToFilerTypeCdAdmin(BaseAdmin): list_display = ( "filer_id", "filer_type", "effect_dt", "active", "session_id", "race", "district_cd", "party_cd" ) list_filter = ( "active", "filer_type", "category", "sub_category", "category_type", "party_cd", "session_id" ) date_hierarchy = "effect_dt" search_fields = ( "filer_id", ) class FilerTypesCdAdmin(BaseAdmin): list_display = ( "filer_type", "description", "grp_type", "calc_use", "grace_period", ) class FilerXrefCdAdmin(BaseAdmin): pass class FilingPeriodCdAdmin(BaseAdmin): list_display = ( "period_id", "start_date", "end_date", "period_desc", ) search_fields = ( "period_id", ) class GroupTypesCdAdmin(BaseAdmin): pass class HeaderCdAdmin(BaseAdmin): pass class HdrCdAdmin(BaseAdmin): pass class ImageLinksCdAdmin(BaseAdmin): pass class LegislativeSessionsCdAdmin(BaseAdmin): pass class LobbyingChgLogCdAdmin(BaseAdmin): pass class LobbyistContributions1CdAdmin(BaseAdmin): pass class LobbyistContributions2CdAdmin(BaseAdmin): pass class LobbyistContributions3CdAdmin(BaseAdmin): pass class LobbyistEmployer1CdAdmin(BaseAdmin): pass class LobbyistEmployer2CdAdmin(BaseAdmin): pass class LobbyistEmployer3CdAdmin(BaseAdmin): pass class LobbyistEmployerFirms1CdAdmin(BaseAdmin): pass class LobbyistEmployerFirms2CdAdmin(BaseAdmin): pass class LobbyistEmpLobbyist1CdAdmin(BaseAdmin): pass class LobbyistEmpLobbyist2CdAdmin(BaseAdmin): pass class LobbyistFirm1CdAdmin(BaseAdmin): pass class LobbyistFirm2CdAdmin(BaseAdmin): pass class LobbyistFirm3CdAdmin(BaseAdmin): pass class LobbyistFirmEmployer1CdAdmin(BaseAdmin): pass class LobbyistFirmEmployer2CdAdmin(BaseAdmin): pass class LobbyistFirmLobbyist1CdAdmin(BaseAdmin): pass class LobbyistFirmLobbyist2CdAdmin(BaseAdmin): pass class LookupCodeAdmin(BaseAdmin): list_display = ( "code_type", "code_id", "code_desc", ) list_filter = ( "code_type", ) search_fields = ( "code_type", "code_id", "code_desc", ) class NamesCdAdmin(BaseAdmin): pass class ReceivedFilingsCdAdmin(BaseAdmin): pass class ReportsCdAdmin(BaseAdmin): pass admin.site.register(models.AcronymsCd, AcronymsCdAdmin) admin.site.register(models.AddressCd, AddressCdAdmin) admin.site.register(models.BallotMeasuresCd, BallotMeasuresCdAdmin) admin.site.register(models.EfsFilingLogCd, EfsFilingLogCdAdmin) admin.site.register(models.FilersCd, FilersCdAdmin) admin.site.register(models.FilerAcronymsCd, FilerAcronymsCdAdmin) admin.site.register(models.FilerAddressCd, FilerAddressCdAdmin) admin.site.register(models.FilerEthicsClassCd, FilerEthicsClassCdAdmin) admin.site.register(models.FilerInterestsCd, FilerInterestsCdAdmin) admin.site.register(models.FilerStatusTypesCd, FilerStatusTypesCdAdmin) admin.site.register(models.FilerToFilerTypeCd, FilerToFilerTypeCdAdmin) admin.site.register(models.FilerTypesCd, FilerTypesCdAdmin) admin.site.register(models.FilerXrefCd, FilerXrefCdAdmin) admin.site.register(models.FilingPeriodCd, FilingPeriodCdAdmin) admin.site.register(models.GroupTypesCd, GroupTypesCdAdmin) admin.site.register(models.HeaderCd, HeaderCdAdmin) admin.site.register(models.HdrCd, HdrCdAdmin) admin.site.register(models.ImageLinksCd, ImageLinksCdAdmin) admin.site.register(models.LegislativeSessionsCd, LegislativeSessionsCdAdmin) admin.site.register(models.LobbyingChgLogCd, LobbyingChgLogCdAdmin) admin.site.register( models.LobbyistContributions1Cd, LobbyistContributions1CdAdmin ) admin.site.register( models.LobbyistContributions2Cd, LobbyistContributions2CdAdmin ) admin.site.register( models.LobbyistContributions3Cd, LobbyistContributions3CdAdmin ) admin.site.register(models.LobbyistEmployer1Cd, LobbyistEmployer1CdAdmin) admin.site.register(models.LobbyistEmployer2Cd, LobbyistEmployer2CdAdmin) admin.site.register(models.LobbyistEmployer3Cd, LobbyistEmployer3CdAdmin) admin.site.register( models.LobbyistEmployerFirms1Cd, LobbyistEmployerFirms1CdAdmin ) admin.site.register( models.LobbyistEmployerFirms2Cd, LobbyistEmployerFirms2CdAdmin ) admin.site.register( models.LobbyistEmpLobbyist1Cd, LobbyistEmpLobbyist1CdAdmin ) admin.site.register( models.LobbyistEmpLobbyist2Cd, LobbyistEmpLobbyist2CdAdmin ) admin.site.register(models.LobbyistFirm1Cd, LobbyistFirm1CdAdmin) admin.site.register(models.LobbyistFirm2Cd, LobbyistFirm2CdAdmin) admin.site.register(models.LobbyistFirm3Cd, LobbyistFirm3CdAdmin) admin.site.register( models.LobbyistFirmEmployer1Cd, LobbyistFirmEmployer1CdAdmin ) admin.site.register( models.LobbyistFirmEmployer2Cd, LobbyistFirmEmployer2CdAdmin ) admin.site.register( models.LobbyistFirmLobbyist1Cd, LobbyistFirmLobbyist1CdAdmin ) admin.site.register( models.LobbyistFirmLobbyist2Cd, LobbyistFirmLobbyist2CdAdmin ) admin.site.register(models.LookupCode, LookupCodeAdmin) admin.site.register(models.NamesCd, NamesCdAdmin) admin.site.register(models.ReceivedFilingsCd, ReceivedFilingsCdAdmin) admin.site.register(models.ReportsCd, ReportsCdAdmin)
mit
orekyuu/intellij-community
python/lib/Lib/site-packages/django/contrib/auth/tests/models.py
318
1493
from django.conf import settings from django.test import TestCase from django.contrib.auth.models import User, SiteProfileNotAvailable class ProfileTestCase(TestCase): fixtures = ['authtestdata.json'] def setUp(self): """Backs up the AUTH_PROFILE_MODULE""" self.old_AUTH_PROFILE_MODULE = getattr(settings, 'AUTH_PROFILE_MODULE', None) def tearDown(self): """Restores the AUTH_PROFILE_MODULE -- if it was not set it is deleted, otherwise the old value is restored""" if self.old_AUTH_PROFILE_MODULE is None and \ hasattr(settings, 'AUTH_PROFILE_MODULE'): del settings.AUTH_PROFILE_MODULE if self.old_AUTH_PROFILE_MODULE is not None: settings.AUTH_PROFILE_MODULE = self.old_AUTH_PROFILE_MODULE def test_site_profile_not_available(self): # calling get_profile without AUTH_PROFILE_MODULE set if hasattr(settings, 'AUTH_PROFILE_MODULE'): del settings.AUTH_PROFILE_MODULE user = User.objects.get(username='testclient') self.assertRaises(SiteProfileNotAvailable, user.get_profile) # Bad syntax in AUTH_PROFILE_MODULE: settings.AUTH_PROFILE_MODULE = 'foobar' self.assertRaises(SiteProfileNotAvailable, user.get_profile) # module that doesn't exist settings.AUTH_PROFILE_MODULE = 'foo.bar' self.assertRaises(SiteProfileNotAvailable, user.get_profile)
apache-2.0
ventosus/jack1
python/jackctl.py
5
7071
from ctypes import * libj = cdll.LoadLibrary( "libjack.so" ) libjs = cdll.LoadLibrary( "libjackserver.so" ) class jackctl_parameter_value( Union ): _fields_ = [ ( "ui", c_uint ), ( "i", c_int ), ( "c", c_char ), ( "ss", c_char * 128 ), ( "b", c_bool ) ] def get_str( self ): return buffer(self.ss) def set_str( self, sss ): self.ss = sss str = property( get_str, set_str ) class jackctl_server_t( Structure ): pass class jackctl_driver_t( Structure ): pass class jackctl_internal_t( Structure ): pass class jackctl_parameter_t( Structure ): pass class JSList( Structure ): pass JSList._fields_ = [ ("data", c_void_p), ("next", POINTER(JSList)) ] class JSIter: def __init__(self, ptr, typ=c_void_p): self.ptr = ptr self.typ = typ def __iter__(self): return self def next( self ): if not self.ptr: raise StopIteration retval = self.ptr.contents.data self.ptr = self.ptr.contents.next return cast( retval, self.typ ) DeviceAcquireFunc = CFUNCTYPE( c_int, c_char_p ) DeviceReleaseFunc = CFUNCTYPE( None, c_char_p ) jackctl_server_start = libjs.jackctl_server_start jackctl_server_start.argtypes = [ POINTER(jackctl_server_t), POINTER(jackctl_driver_t) ] jackctl_server_start.restype = c_bool jackctl_server_stop = libjs.jackctl_server_stop jackctl_server_stop.argtypes = [ POINTER(jackctl_server_t) ] jackctl_server_stop.restype = c_bool jackctl_server_create = libjs.jackctl_server_create jackctl_server_create.argtypes = [ DeviceAcquireFunc, DeviceReleaseFunc ] jackctl_server_create.restype = POINTER(jackctl_server_t) jackctl_server_get_drivers_list = libjs.jackctl_server_get_drivers_list jackctl_server_get_drivers_list.argtypes = [ POINTER(jackctl_server_t) ] jackctl_server_get_drivers_list.restype = POINTER(JSList) jackctl_server_get_parameters = libjs.jackctl_server_get_parameters jackctl_server_get_parameters.argtypes = [ POINTER(jackctl_server_t) ] jackctl_server_get_parameters.restype = POINTER(JSList) jackctl_driver_get_parameters = libjs.jackctl_driver_get_parameters jackctl_driver_get_parameters.argtypes = [ POINTER(jackctl_driver_t) ] jackctl_driver_get_parameters.restype = POINTER(JSList) jackctl_driver_get_name = libjs.jackctl_driver_get_name jackctl_driver_get_name.argtypes = [ POINTER(jackctl_driver_t) ] jackctl_driver_get_name.restype = c_char_p jackctl_parameter_get_name = libjs.jackctl_parameter_get_name jackctl_parameter_get_name.argtypes = [ POINTER(jackctl_parameter_t) ] jackctl_parameter_get_name.restype = c_char_p jackctl_parameter_get_short_description = libjs.jackctl_parameter_get_short_description jackctl_parameter_get_short_description.argtypes = [ POINTER(jackctl_parameter_t) ] jackctl_parameter_get_short_description.restype = c_char_p jackctl_parameter_get_type = libjs.jackctl_parameter_get_type jackctl_parameter_get_type.argtypes = [ POINTER(jackctl_parameter_t) ] jackctl_parameter_get_type.restype = c_uint jackctl_parameter_set_value = libjs.jackctl_parameter_set_value jackctl_parameter_set_value.argtypes = [ POINTER(jackctl_parameter_t), POINTER(jackctl_parameter_value) ] jackctl_parameter_set_value.restype = c_bool jackctl_parameter_get_value = libjs.jackctl_parameter_get_value jackctl_parameter_get_value.argtypes = [ POINTER(jackctl_parameter_t) ] jackctl_parameter_get_value.restype = jackctl_parameter_value jackctl_parameter_get_id = libjs.jackctl_parameter_get_id jackctl_parameter_get_id.argtypes = [ POINTER(jackctl_parameter_t) ] jackctl_parameter_get_id.restype = c_char jackctl_server_switch_master = libjs.jackctl_server_switch_master jackctl_server_switch_master.argtypes = [ POINTER(jackctl_server_t), POINTER(jackctl_driver_t) ] jackctl_server_switch_master.restype = c_bool class Parameter(object): def __init__( self, param_ptr ): self.param_ptr = param_ptr self.param_type = jackctl_parameter_get_type( self.param_ptr ) def get_short_desc( self ): return jackctl_parameter_get_short_description( self.param_ptr ) short_desc = property( get_short_desc ) def get_name( self ): return jackctl_parameter_get_name( self.param_ptr ) name = property( get_name ) def get_id( self ): return jackctl_parameter_get_id( self.param_ptr ) id = property( get_id ) def set_value( self, val ): param_v = jackctl_parameter_value() if self.param_type == 1: # int param_v.i = int(val) elif self.param_type == 2: # uint param_v.ui = int(val) elif self.param_type == 3: # char assert( (type(val) == str) and len(val)==1 ) param_v.c = val elif self.param_type == 4: # string assert( type(val) == str ) param_v.ss = val elif self.param_type == 5: # bool assert( type(val) == bool ) param_v.b = val jackctl_parameter_set_value( self.param_ptr, pointer(param_v) ) def get_value( self ): param_v = jackctl_parameter_get_value( self.param_ptr ) if self.param_type == 1: # int return param_v.i elif self.param_type == 2: # uint return param_v.ui elif self.param_type == 3: # char return param_v.c elif self.param_type == 4: # string return param_v.ss elif self.param_type == 5: # bool return param_v.b value = property( get_value, set_value ) class Driver(object): def __init__( self, drv_ptr ): self.drv_ptr = drv_ptr params_jslist = jackctl_driver_get_parameters( self.drv_ptr ) self.params = {} for i in JSIter( params_jslist, POINTER(jackctl_parameter_t) ): self.params[ jackctl_parameter_get_name( i ) ] = Parameter(i) def get_name( self ): return jackctl_driver_get_name( self.drv_ptr ) name = property( get_name ) class Server(object): def __init__( self ): self.dacqd = DeviceAcquireFunc(self.acquire_card) self.reled = DeviceReleaseFunc(self.release_card) self.srv_ptr = jackctl_server_create( self.dacqd, self.reled ) self.acquire_card_cb = None self.release_card_cb = None driver_jslist = jackctl_server_get_drivers_list( self.srv_ptr ) self.drivers = {} for i in JSIter( driver_jslist, POINTER(jackctl_driver_t) ): self.drivers[ jackctl_driver_get_name( i ) ] = Driver(i) params_jslist = jackctl_server_get_parameters( self.srv_ptr ) self.params = {} for i in JSIter( params_jslist, POINTER(jackctl_parameter_t) ): self.params[ jackctl_parameter_get_name( i ) ] = Parameter(i) def __del__( self ): pass def start( self, driver ): return jackctl_server_start( self.srv_ptr, driver.drv_ptr ) def switch_master( self, driver ): return jackctl_server_switch_master( self.srv_ptr, driver.drv_ptr ) def stop( self ): return jackctl_server_stop( self.srv_ptr ) def acquire_card( self, cardname ): if self.acquire_card_cb: return self.acquire_card_cb(cardname) else: return True def release_card( self, cardname ): if self.release_card_cb: self.release_card_cb(cardname)
lgpl-2.1
fxia22/ASM_xf
PythonD/lib/python2.4/bsddb/test/test_env_close.py
18
2977
"""TestCases for checking that it does not segfault when a DBEnv object is closed before its DB objects. """ import os import sys import tempfile import glob import unittest try: # For Pythons w/distutils pybsddb from bsddb3 import db except ImportError: # For Python 2.3 from bsddb import db from test_all import verbose # We're going to get warnings in this module about trying to close the db when # its env is already closed. Let's just ignore those. try: import warnings except ImportError: pass else: warnings.filterwarnings('ignore', message='DB could not be closed in', category=RuntimeWarning) #---------------------------------------------------------------------- class DBEnvClosedEarlyCrash(unittest.TestCase): def setUp(self): self.homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') try: os.mkdir(self.homeDir) except os.error: pass tempfile.tempdir = self.homeDir self.filename = os.path.split(tempfile.mktemp())[1] tempfile.tempdir = None def tearDown(self): files = glob.glob(os.path.join(self.homeDir, '*')) for file in files: os.remove(file) def test01_close_dbenv_before_db(self): dbenv = db.DBEnv() dbenv.open(self.homeDir, db.DB_INIT_CDB| db.DB_CREATE |db.DB_THREAD|db.DB_INIT_MPOOL, 0666) d = db.DB(dbenv) d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0666) try: dbenv.close() except db.DBError: try: d.close() except db.DBError: return assert 0, \ "DB close did not raise an exception about its "\ "DBEnv being trashed" # XXX This may fail when using older versions of BerkeleyDB. # E.g. 3.2.9 never raised the exception. assert 0, "dbenv did not raise an exception about its DB being open" def test02_close_dbenv_delete_db_success(self): dbenv = db.DBEnv() dbenv.open(self.homeDir, db.DB_INIT_CDB| db.DB_CREATE |db.DB_THREAD|db.DB_INIT_MPOOL, 0666) d = db.DB(dbenv) d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0666) try: dbenv.close() except db.DBError: pass # good, it should raise an exception del d try: import gc except ImportError: gc = None if gc: # force d.__del__ [DB_dealloc] to be called gc.collect() #---------------------------------------------------------------------- def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(DBEnvClosedEarlyCrash)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
gpl-2.0
eirmag/weboob
modules/societegenerale/pages/login.py
1
2921
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Jocelyn Jaubert # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. from logging import error import re from weboob.tools.json import json from weboob.tools.browser import BrowserUnavailable from weboob.tools.mech import ClientForm from .base import BasePage from ..captcha import Captcha, TileError __all__ = ['LoginPage', 'BadLoginPage'] class LoginPage(BasePage): def on_loaded(self): for td in self.document.getroot().cssselect('td.LibelleErreur'): if td.text is None: continue msg = td.text.strip() if 'indisponible' in msg: raise BrowserUnavailable(msg) def login(self, login, password): DOMAIN_LOGIN = self.browser.DOMAIN_LOGIN DOMAIN = self.browser.DOMAIN url_login = 'https://' + DOMAIN_LOGIN + '/index.html' base_url = 'https://' + DOMAIN url = base_url + '//sec/vk/gen_crypto?estSession=0' headers = { 'Referer': url_login } request = self.browser.request_class(url, None, headers) infos_data = self.browser.readurl(request) infos_data = re.match('^_vkCallback\((.*)\);$', infos_data).group(1) infos = json.loads(infos_data.replace("'", '"')) url = base_url + '//sec/vk/gen_ui?modeClavier=0&cryptogramme=' + infos["crypto"] img = Captcha(self.browser.openurl(url), infos) try: img.build_tiles() except TileError, err: error("Error: %s" % err) if err.tile: err.tile.display() self.browser.select_form('n2g_authentification') self.browser.controls.append(ClientForm.TextControl('text', 'codsec', {'value': ''})) self.browser.controls.append(ClientForm.TextControl('text', 'cryptocvcs', {'value': ''})) self.browser.controls.append(ClientForm.TextControl('text', 'vk_op', {'value': 'auth'})) self.browser.set_all_readonly(False) self.browser['codcli'] = login self.browser['user_id'] = login self.browser['codsec'] = img.get_codes(password[:6]) self.browser['cryptocvcs'] = infos["crypto"] self.browser.submit(nologin=True) class BadLoginPage(BasePage): pass
agpl-3.0
CydarLtd/ansible
lib/ansible/modules/cloud/rackspace/rax_files_objects.py
70
19116
#!/usr/bin/python # (c) 2013, Paul Durivage <paul.durivage@rackspace.com> # # This file is part of Ansible. # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # This is a DOCUMENTATION stub specific to this module, it extends # a documentation fragment located in ansible.utils.module_docs_fragments ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: rax_files_objects short_description: Upload, download, and delete objects in Rackspace Cloud Files description: - Upload, download, and delete objects in Rackspace Cloud Files version_added: "1.5" options: clear_meta: description: - Optionally clear existing metadata when applying metadata to existing objects. Selecting this option is only appropriate when setting type=meta choices: - "yes" - "no" default: "no" container: description: - The container to use for file object operations. required: true default: null dest: description: - The destination of a "get" operation; i.e. a local directory, "/home/user/myfolder". Used to specify the destination of an operation on a remote object; i.e. a file name, "file1", or a comma-separated list of remote objects, "file1,file2,file17" expires: description: - Used to set an expiration on a file or folder uploaded to Cloud Files. Requires an integer, specifying expiration in seconds default: null meta: description: - A hash of items to set as metadata values on an uploaded file or folder default: null method: description: - The method of operation to be performed. For example, put to upload files to Cloud Files, get to download files from Cloud Files or delete to delete remote objects in Cloud Files choices: - get - put - delete default: get src: description: - Source from which to upload files. Used to specify a remote object as a source for an operation, i.e. a file name, "file1", or a comma-separated list of remote objects, "file1,file2,file17". src and dest are mutually exclusive on remote-only object operations default: null structure: description: - Used to specify whether to maintain nested directory structure when downloading objects from Cloud Files. Setting to false downloads the contents of a container to a single, flat directory choices: - yes - "no" default: "yes" state: description: - Indicate desired state of the resource choices: ['present', 'absent'] default: present type: description: - Type of object to do work on - Metadata object or a file object choices: - file - meta default: file author: "Paul Durivage (@angstwad)" extends_documentation_fragment: rackspace ''' EXAMPLES = ''' - name: "Test Cloud Files Objects" hosts: local gather_facts: False tasks: - name: "Get objects from test container" rax_files_objects: container: testcont dest: ~/Downloads/testcont - name: "Get single object from test container" rax_files_objects: container: testcont src: file1 dest: ~/Downloads/testcont - name: "Get several objects from test container" rax_files_objects: container: testcont src: file1,file2,file3 dest: ~/Downloads/testcont - name: "Delete one object in test container" rax_files_objects: container: testcont method: delete dest: file1 - name: "Delete several objects in test container" rax_files_objects: container: testcont method: delete dest: file2,file3,file4 - name: "Delete all objects in test container" rax_files_objects: container: testcont method: delete - name: "Upload all files to test container" rax_files_objects: container: testcont method: put src: ~/Downloads/onehundred - name: "Upload one file to test container" rax_files_objects: container: testcont method: put src: ~/Downloads/testcont/file1 - name: "Upload one file to test container with metadata" rax_files_objects: container: testcont src: ~/Downloads/testcont/file2 method: put meta: testkey: testdata who_uploaded_this: someuser@example.com - name: "Upload one file to test container with TTL of 60 seconds" rax_files_objects: container: testcont method: put src: ~/Downloads/testcont/file3 expires: 60 - name: "Attempt to get remote object that does not exist" rax_files_objects: container: testcont method: get src: FileThatDoesNotExist.jpg dest: ~/Downloads/testcont ignore_errors: yes - name: "Attempt to delete remote object that does not exist" rax_files_objects: container: testcont method: delete dest: FileThatDoesNotExist.jpg ignore_errors: yes - name: "Test Cloud Files Objects Metadata" hosts: local gather_facts: false tasks: - name: "Get metadata on one object" rax_files_objects: container: testcont type: meta dest: file2 - name: "Get metadata on several objects" rax_files_objects: container: testcont type: meta src: file2,file1 - name: "Set metadata on an object" rax_files_objects: container: testcont type: meta dest: file17 method: put meta: key1: value1 key2: value2 clear_meta: true - name: "Verify metadata is set" rax_files_objects: container: testcont type: meta src: file17 - name: "Delete metadata" rax_files_objects: container: testcont type: meta dest: file17 method: delete meta: key1: '' key2: '' - name: "Get metadata on all objects" rax_files_objects: container: testcont type: meta ''' try: import pyrax HAS_PYRAX = True except ImportError: HAS_PYRAX = False EXIT_DICT = dict(success=False) META_PREFIX = 'x-object-meta-' def _get_container(module, cf, container): try: return cf.get_container(container) except pyrax.exc.NoSuchContainer as e: module.fail_json(msg=e.message) def _upload_folder(cf, folder, container, ttl=None, headers=None): """ Uploads a folder to Cloud Files. """ total_bytes = 0 for root, dirs, files in os.walk(folder): for fname in files: full_path = os.path.join(root, fname) obj_name = os.path.relpath(full_path, folder) obj_size = os.path.getsize(full_path) cf.upload_file(container, full_path, obj_name=obj_name, return_none=True, ttl=ttl, headers=headers) total_bytes += obj_size return total_bytes def upload(module, cf, container, src, dest, meta, expires): """ Uploads a single object or a folder to Cloud Files Optionally sets an metadata, TTL value (expires), or Content-Disposition and Content-Encoding headers. """ if not src: module.fail_json(msg='src must be specified when uploading') c = _get_container(module, cf, container) src = os.path.abspath(os.path.expanduser(src)) is_dir = os.path.isdir(src) if not is_dir and not os.path.isfile(src) or not os.path.exists(src): module.fail_json(msg='src must be a file or a directory') if dest and is_dir: module.fail_json(msg='dest cannot be set when whole ' 'directories are uploaded') cont_obj = None total_bytes = 0 if dest and not is_dir: try: cont_obj = c.upload_file(src, obj_name=dest, ttl=expires, headers=meta) except Exception as e: module.fail_json(msg=e.message) elif is_dir: try: total_bytes = _upload_folder(cf, src, c, ttl=expires, headers=meta) except Exception as e: module.fail_json(msg=e.message) else: try: cont_obj = c.upload_file(src, ttl=expires, headers=meta) except Exception as e: module.fail_json(msg=e.message) EXIT_DICT['success'] = True EXIT_DICT['container'] = c.name EXIT_DICT['msg'] = "Uploaded %s to container: %s" % (src, c.name) if cont_obj or total_bytes > 0: EXIT_DICT['changed'] = True if meta: EXIT_DICT['meta'] = dict(updated=True) if cont_obj: EXIT_DICT['bytes'] = cont_obj.total_bytes EXIT_DICT['etag'] = cont_obj.etag else: EXIT_DICT['bytes'] = total_bytes module.exit_json(**EXIT_DICT) def download(module, cf, container, src, dest, structure): """ Download objects from Cloud Files to a local path specified by "dest". Optionally disable maintaining a directory structure by by passing a false value to "structure". """ # Looking for an explicit destination if not dest: module.fail_json(msg='dest is a required argument when ' 'downloading from Cloud Files') # Attempt to fetch the container by name c = _get_container(module, cf, container) # Accept a single object name or a comma-separated list of objs # If not specified, get the entire container if src: objs = src.split(',') objs = map(str.strip, objs) else: objs = c.get_object_names() dest = os.path.abspath(os.path.expanduser(dest)) is_dir = os.path.isdir(dest) if not is_dir: module.fail_json(msg='dest must be a directory') results = [] for obj in objs: try: c.download_object(obj, dest, structure=structure) except Exception as e: module.fail_json(msg=e.message) else: results.append(obj) len_results = len(results) len_objs = len(objs) EXIT_DICT['container'] = c.name EXIT_DICT['requested_downloaded'] = results if results: EXIT_DICT['changed'] = True if len_results == len_objs: EXIT_DICT['success'] = True EXIT_DICT['msg'] = "%s objects downloaded to %s" % (len_results, dest) else: EXIT_DICT['msg'] = "Error: only %s of %s objects were " \ "downloaded" % (len_results, len_objs) module.exit_json(**EXIT_DICT) def delete(module, cf, container, src, dest): """ Delete specific objects by proving a single file name or a comma-separated list to src OR dest (but not both). Omitting file name(s) assumes the entire container is to be deleted. """ objs = None if src and dest: module.fail_json(msg="Error: ambiguous instructions; files to be deleted " "have been specified on both src and dest args") elif dest: objs = dest else: objs = src c = _get_container(module, cf, container) if objs: objs = objs.split(',') objs = map(str.strip, objs) else: objs = c.get_object_names() num_objs = len(objs) results = [] for obj in objs: try: result = c.delete_object(obj) except Exception as e: module.fail_json(msg=e.message) else: results.append(result) num_deleted = results.count(True) EXIT_DICT['container'] = c.name EXIT_DICT['deleted'] = num_deleted EXIT_DICT['requested_deleted'] = objs if num_deleted: EXIT_DICT['changed'] = True if num_objs == num_deleted: EXIT_DICT['success'] = True EXIT_DICT['msg'] = "%s objects deleted" % num_deleted else: EXIT_DICT['msg'] = ("Error: only %s of %s objects " "deleted" % (num_deleted, num_objs)) module.exit_json(**EXIT_DICT) def get_meta(module, cf, container, src, dest): """ Get metadata for a single file, comma-separated list, or entire container """ c = _get_container(module, cf, container) objs = None if src and dest: module.fail_json(msg="Error: ambiguous instructions; files to be deleted " "have been specified on both src and dest args") elif dest: objs = dest else: objs = src if objs: objs = objs.split(',') objs = map(str.strip, objs) else: objs = c.get_object_names() results = dict() for obj in objs: try: meta = c.get_object(obj).get_metadata() except Exception as e: module.fail_json(msg=e.message) else: results[obj] = dict() for k, v in meta.items(): meta_key = k.split(META_PREFIX)[-1] results[obj][meta_key] = v EXIT_DICT['container'] = c.name if results: EXIT_DICT['meta_results'] = results EXIT_DICT['success'] = True module.exit_json(**EXIT_DICT) def put_meta(module, cf, container, src, dest, meta, clear_meta): """ Set metadata on a container, single file, or comma-separated list. Passing a true value to clear_meta clears the metadata stored in Cloud Files before setting the new metadata to the value of "meta". """ objs = None if src and dest: module.fail_json(msg="Error: ambiguous instructions; files to set meta" " have been specified on both src and dest args") elif dest: objs = dest else: objs = src objs = objs.split(',') objs = map(str.strip, objs) c = _get_container(module, cf, container) results = [] for obj in objs: try: result = c.get_object(obj).set_metadata(meta, clear=clear_meta) except Exception as e: module.fail_json(msg=e.message) else: results.append(result) EXIT_DICT['container'] = c.name EXIT_DICT['success'] = True if results: EXIT_DICT['changed'] = True EXIT_DICT['num_changed'] = True module.exit_json(**EXIT_DICT) def delete_meta(module, cf, container, src, dest, meta): """ Removes metadata keys and values specified in meta, if any. Deletes on all objects specified by src or dest (but not both), if any; otherwise it deletes keys on all objects in the container """ objs = None if src and dest: module.fail_json(msg="Error: ambiguous instructions; meta keys to be " "deleted have been specified on both src and dest" " args") elif dest: objs = dest else: objs = src objs = objs.split(',') objs = map(str.strip, objs) c = _get_container(module, cf, container) results = [] # Num of metadata keys removed, not objects affected for obj in objs: if meta: for k, v in meta.items(): try: result = c.get_object(obj).remove_metadata_key(k) except Exception as e: module.fail_json(msg=e.message) else: results.append(result) else: try: o = c.get_object(obj) except pyrax.exc.NoSuchObject as e: module.fail_json(msg=e.message) for k, v in o.get_metadata().items(): try: result = o.remove_metadata_key(k) except Exception as e: module.fail_json(msg=e.message) results.append(result) EXIT_DICT['container'] = c.name EXIT_DICT['success'] = True if results: EXIT_DICT['changed'] = True EXIT_DICT['num_deleted'] = len(results) module.exit_json(**EXIT_DICT) def cloudfiles(module, container, src, dest, method, typ, meta, clear_meta, structure, expires): """ Dispatch from here to work with metadata or file objects """ cf = pyrax.cloudfiles if cf is None: module.fail_json(msg='Failed to instantiate client. This ' 'typically indicates an invalid region or an ' 'incorrectly capitalized region name.') if typ == "file": if method == 'put': upload(module, cf, container, src, dest, meta, expires) elif method == 'get': download(module, cf, container, src, dest, structure) elif method == 'delete': delete(module, cf, container, src, dest) else: if method == 'get': get_meta(module, cf, container, src, dest) if method == 'put': put_meta(module, cf, container, src, dest, meta, clear_meta) if method == 'delete': delete_meta(module, cf, container, src, dest, meta) def main(): argument_spec = rax_argument_spec() argument_spec.update( dict( container=dict(required=True), src=dict(), dest=dict(), method=dict(default='get', choices=['put', 'get', 'delete']), type=dict(default='file', choices=['file', 'meta']), meta=dict(type='dict', default=dict()), clear_meta=dict(default=False, type='bool'), structure=dict(default=True, type='bool'), expires=dict(type='int'), ) ) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together() ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') container = module.params.get('container') src = module.params.get('src') dest = module.params.get('dest') method = module.params.get('method') typ = module.params.get('type') meta = module.params.get('meta') clear_meta = module.params.get('clear_meta') structure = module.params.get('structure') expires = module.params.get('expires') if clear_meta and not typ == 'meta': module.fail_json(msg='clear_meta can only be used when setting metadata') setup_rax_module(module, pyrax) cloudfiles(module, container, src, dest, method, typ, meta, clear_meta, structure, expires) from ansible.module_utils.basic import * from ansible.module_utils.rax import * if __name__ == '__main__': main()
gpl-3.0
ThiefMaster/sqlalchemy
lib/sqlalchemy/dialects/postgresql/pypostgresql.py
55
2655
# postgresql/pypostgresql.py # Copyright (C) 2005-2015 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: postgresql+pypostgresql :name: py-postgresql :dbapi: pypostgresql :connectstring: postgresql+pypostgresql://user:password@host:port/dbname\ [?key=value&key=value...] :url: http://python.projects.pgfoundry.org/ """ from ... import util from ... import types as sqltypes from .base import PGDialect, PGExecutionContext from ... import processors class PGNumeric(sqltypes.Numeric): def bind_processor(self, dialect): return processors.to_str def result_processor(self, dialect, coltype): if self.asdecimal: return None else: return processors.to_float class PGExecutionContext_pypostgresql(PGExecutionContext): pass class PGDialect_pypostgresql(PGDialect): driver = 'pypostgresql' supports_unicode_statements = True supports_unicode_binds = True description_encoding = None default_paramstyle = 'pyformat' # requires trunk version to support sane rowcounts # TODO: use dbapi version information to set this flag appropriately supports_sane_rowcount = True supports_sane_multi_rowcount = False execution_ctx_cls = PGExecutionContext_pypostgresql colspecs = util.update_copy( PGDialect.colspecs, { sqltypes.Numeric: PGNumeric, # prevents PGNumeric from being used sqltypes.Float: sqltypes.Float, } ) @classmethod def dbapi(cls): from postgresql.driver import dbapi20 return dbapi20 _DBAPI_ERROR_NAMES = [ "Error", "InterfaceError", "DatabaseError", "DataError", "OperationalError", "IntegrityError", "InternalError", "ProgrammingError", "NotSupportedError" ] @util.memoized_property def dbapi_exception_translation_map(self): if self.dbapi is None: return {} return dict( (getattr(self.dbapi, name).__name__, name) for name in self._DBAPI_ERROR_NAMES ) def create_connect_args(self, url): opts = url.translate_connect_args(username='user') if 'port' in opts: opts['port'] = int(opts['port']) else: opts['port'] = 5432 opts.update(url.query) return ([], opts) def is_disconnect(self, e, connection, cursor): return "connection is closed" in str(e) dialect = PGDialect_pypostgresql
mit
mcus/SickRage
lib/imdb/parser/http/utils.py
59
34532
""" parser.http.utils module (imdb package). This module provides miscellaneous utilities used by the imdb.parser.http classes. Copyright 2004-2012 Davide Alberani <da@erlug.linux.it> 2008 H. Turgut Uyar <uyar@tekir.org> 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 """ import re import logging import warnings from imdb._exceptions import IMDbError from imdb.utils import flatten, _Container from imdb.Movie import Movie from imdb.Person import Person from imdb.Character import Character # Year, imdbIndex and kind. re_yearKind_index = re.compile(r'(\([0-9\?]{4}(?:/[IVXLCDM]+)?\)(?: \(mini\)| \(TV\)| \(V\)| \(VG\))?)') # Match imdb ids in href tags re_imdbid = re.compile(r'(title/tt|name/nm|character/ch|company/co)([0-9]+)') def analyze_imdbid(href): """Return an imdbID from an URL.""" if not href: return None match = re_imdbid.search(href) if not match: return None return str(match.group(2)) _modify_keys = list(Movie.keys_tomodify_list) + list(Person.keys_tomodify_list) def _putRefs(d, re_titles, re_names, re_characters, lastKey=None): """Iterate over the strings inside list items or dictionary values, substitutes movie titles and person names with the (qv) references.""" if isinstance(d, list): for i in xrange(len(d)): if isinstance(d[i], (unicode, str)): if lastKey in _modify_keys: if re_names: d[i] = re_names.sub(ur"'\1' (qv)", d[i]) if re_titles: d[i] = re_titles.sub(ur'_\1_ (qv)', d[i]) if re_characters: d[i] = re_characters.sub(ur'#\1# (qv)', d[i]) elif isinstance(d[i], (list, dict)): _putRefs(d[i], re_titles, re_names, re_characters, lastKey=lastKey) elif isinstance(d, dict): for k, v in d.items(): lastKey = k if isinstance(v, (unicode, str)): if lastKey in _modify_keys: if re_names: d[k] = re_names.sub(ur"'\1' (qv)", v) if re_titles: d[k] = re_titles.sub(ur'_\1_ (qv)', v) if re_characters: d[k] = re_characters.sub(ur'#\1# (qv)', v) elif isinstance(v, (list, dict)): _putRefs(d[k], re_titles, re_names, re_characters, lastKey=lastKey) # Handle HTML/XML/SGML entities. from htmlentitydefs import entitydefs entitydefs = entitydefs.copy() entitydefsget = entitydefs.get entitydefs['nbsp'] = ' ' sgmlentity = {'lt': '<', 'gt': '>', 'amp': '&', 'quot': '"', 'apos': '\'', 'ndash': '-'} sgmlentityget = sgmlentity.get _sgmlentkeys = sgmlentity.keys() entcharrefs = {} entcharrefsget = entcharrefs.get for _k, _v in entitydefs.items(): if _k in _sgmlentkeys: continue if _v[0:2] == '&#': dec_code = _v[1:-1] _v = unichr(int(_v[2:-1])) entcharrefs[dec_code] = _v else: dec_code = '#' + str(ord(_v)) _v = unicode(_v, 'latin_1', 'replace') entcharrefs[dec_code] = _v entcharrefs[_k] = _v del _sgmlentkeys, _k, _v entcharrefs['#160'] = u' ' entcharrefs['#xA0'] = u' ' entcharrefs['#xa0'] = u' ' entcharrefs['#XA0'] = u' ' entcharrefs['#x22'] = u'"' entcharrefs['#X22'] = u'"' # convert &x26; to &amp;, to make BeautifulSoup happy; beware that this # leaves lone '&' in the html broken, but I assume this is better than # the contrary... entcharrefs['#38'] = u'&amp;' entcharrefs['#x26'] = u'&amp;' entcharrefs['#x26'] = u'&amp;' re_entcharrefs = re.compile('&(%s|\#160|\#\d{1,5}|\#x[0-9a-f]{1,4});' % '|'.join(map(re.escape, entcharrefs)), re.I) re_entcharrefssub = re_entcharrefs.sub sgmlentity.update(dict([('#34', u'"'), ('#38', u'&'), ('#60', u'<'), ('#62', u'>'), ('#39', u"'")])) re_sgmlref = re.compile('&(%s);' % '|'.join(map(re.escape, sgmlentity))) re_sgmlrefsub = re_sgmlref.sub # Matches XML-only single tags, like <br/> ; they are invalid in HTML, # but widely used by IMDb web site. :-/ re_xmltags = re.compile('<([a-zA-Z]+)/>') def _replXMLRef(match): """Replace the matched XML/HTML entities and references; replace everything except sgml entities like &lt;, &gt;, ...""" ref = match.group(1) value = entcharrefsget(ref) if value is None: if ref[0] == '#': ref_code = ref[1:] if ref_code in ('34', '38', '60', '62', '39'): return match.group(0) elif ref_code[0].lower() == 'x': #if ref[2:] == '26': # # Don't convert &x26; to &amp;, to make BeautifulSoup happy. # return '&amp;' return unichr(int(ref[2:], 16)) else: return unichr(int(ref[1:])) else: return ref return value def subXMLRefs(s): """Return the given html string with entity and char references replaced.""" return re_entcharrefssub(_replXMLRef, s) # XXX: no more used here; move it to mobile (they are imported by helpers, too)? def _replSGMLRefs(match): """Replace the matched SGML entity.""" ref = match.group(1) return sgmlentityget(ref, ref) def subSGMLRefs(s): """Return the given html string with sgml entity and char references replaced.""" return re_sgmlrefsub(_replSGMLRefs, s) _b_p_logger = logging.getLogger('imdbpy.parser.http.build_person') def build_person(txt, personID=None, billingPos=None, roleID=None, accessSystem='http', modFunct=None): """Return a Person instance from the tipical <tr>...</tr> strings found in the IMDb's web site.""" #if personID is None # _b_p_logger.debug('empty name or personID for "%s"', txt) notes = u'' role = u'' # Search the (optional) separator between name and role/notes. if txt.find('....') != -1: sep = '....' elif txt.find('...') != -1: sep = '...' else: sep = '...' # Replace the first parenthesis, assuming there are only # notes, after. # Rationale: no imdbIndex is (ever?) showed on the web site. txt = txt.replace('(', '...(', 1) txt_split = txt.split(sep, 1) name = txt_split[0].strip() if len(txt_split) == 2: role_comment = txt_split[1].strip() # Strip common endings. if role_comment[-4:] == ' and': role_comment = role_comment[:-4].rstrip() elif role_comment[-2:] == ' &': role_comment = role_comment[:-2].rstrip() elif role_comment[-6:] == '& ....': role_comment = role_comment[:-6].rstrip() # Get the notes. if roleID is not None: if not isinstance(roleID, list): cmt_idx = role_comment.find('(') if cmt_idx != -1: role = role_comment[:cmt_idx].rstrip() notes = role_comment[cmt_idx:] else: # Just a role, without notes. role = role_comment else: role = role_comment else: # We're managing something that doesn't have a 'role', so # everything are notes. notes = role_comment if role == '....': role = u'' roleNotes = [] # Manages multiple roleIDs. if isinstance(roleID, list): rolesplit = role.split('/') role = [] for r in rolesplit: nidx = r.find('(') if nidx != -1: role.append(r[:nidx].rstrip()) roleNotes.append(r[nidx:]) else: role.append(r) roleNotes.append(None) lr = len(role) lrid = len(roleID) if lr > lrid: roleID += [None] * (lrid - lr) elif lr < lrid: roleID = roleID[:lr] for i, rid in enumerate(roleID): if rid is not None: roleID[i] = str(rid) if lr == 1: role = role[0] roleID = roleID[0] notes = roleNotes[0] or u'' elif roleID is not None: roleID = str(roleID) if personID is not None: personID = str(personID) if (not name) or (personID is None): # Set to 'debug', since build_person is expected to receive some crap. _b_p_logger.debug('empty name or personID for "%s"', txt) # XXX: return None if something strange is detected? person = Person(name=name, personID=personID, currentRole=role, roleID=roleID, notes=notes, billingPos=billingPos, modFunct=modFunct, accessSystem=accessSystem) if roleNotes and len(roleNotes) == len(roleID): for idx, role in enumerate(person.currentRole): if roleNotes[idx]: role.notes = roleNotes[idx] return person _re_chrIDs = re.compile('[0-9]{7}') _b_m_logger = logging.getLogger('imdbpy.parser.http.build_movie') # To shrink spaces. re_spaces = re.compile(r'\s+') def build_movie(txt, movieID=None, roleID=None, status=None, accessSystem='http', modFunct=None, _parsingCharacter=False, _parsingCompany=False, year=None, chrRoles=None, rolesNoChar=None, additionalNotes=None): """Given a string as normally seen on the "categorized" page of a person on the IMDb's web site, returns a Movie instance.""" # FIXME: Oook, lets face it: build_movie and build_person are now # two horrible sets of patches to support the new IMDb design. They # must be rewritten from scratch. if _parsingCharacter: _defSep = ' Played by ' elif _parsingCompany: _defSep = ' ... ' else: _defSep = ' .... ' title = re_spaces.sub(' ', txt).strip() # Split the role/notes from the movie title. tsplit = title.split(_defSep, 1) role = u'' notes = u'' roleNotes = [] if len(tsplit) == 2: title = tsplit[0].rstrip() role = tsplit[1].lstrip() if title[-9:] == 'TV Series': title = title[:-9].rstrip() #elif title[-7:] == '(short)': # title = title[:-7].rstrip() #elif title[-11:] == '(TV series)': # title = title[:-11].rstrip() #elif title[-10:] == '(TV movie)': # title = title[:-10].rstrip() elif title[-14:] == 'TV mini-series': title = title[:-14] + ' (mini)' if title and title.endswith(_defSep.rstrip()): title = title[:-len(_defSep)+1] # Try to understand where the movie title ends. while True: if year: break if title[-1:] != ')': # Ignore the silly "TV Series" notice. if title[-9:] == 'TV Series': title = title[:-9].rstrip() continue else: # Just a title: stop here. break # Try to match paired parentheses; yes: sometimes there are # parentheses inside comments... nidx = title.rfind('(') while (nidx != -1 and \ title[nidx:].count('(') != title[nidx:].count(')')): nidx = title[:nidx].rfind('(') # Unbalanced parentheses: stop here. if nidx == -1: break # The last item in parentheses seems to be a year: stop here. first4 = title[nidx+1:nidx+5] if (first4.isdigit() or first4 == '????') and \ title[nidx+5:nidx+6] in (')', '/'): break # The last item in parentheses is a known kind: stop here. if title[nidx+1:-1] in ('TV', 'V', 'mini', 'VG', 'TV movie', 'TV series', 'short'): break # Else, in parentheses there are some notes. # XXX: should the notes in the role half be kept separated # from the notes in the movie title half? if notes: notes = '%s %s' % (title[nidx:], notes) else: notes = title[nidx:] title = title[:nidx].rstrip() if year: year = year.strip() if title[-1:] == ')': fpIdx = title.rfind('(') if fpIdx != -1: if notes: notes = '%s %s' % (title[fpIdx:], notes) else: notes = title[fpIdx:] title = title[:fpIdx].rstrip() title = u'%s (%s)' % (title, year) if _parsingCharacter and roleID and not role: roleID = None if not roleID: roleID = None elif len(roleID) == 1: roleID = roleID[0] if not role and chrRoles and isinstance(roleID, (str, unicode)): roleID = _re_chrIDs.findall(roleID) role = ' / '.join(filter(None, chrRoles.split('@@'))) # Manages multiple roleIDs. if isinstance(roleID, list): tmprole = role.split('/') role = [] for r in tmprole: nidx = r.find('(') if nidx != -1: role.append(r[:nidx].rstrip()) roleNotes.append(r[nidx:]) else: role.append(r) roleNotes.append(None) lr = len(role) lrid = len(roleID) if lr > lrid: roleID += [None] * (lrid - lr) elif lr < lrid: roleID = roleID[:lr] for i, rid in enumerate(roleID): if rid is not None: roleID[i] = str(rid) if lr == 1: role = role[0] roleID = roleID[0] elif roleID is not None: roleID = str(roleID) if movieID is not None: movieID = str(movieID) if (not title) or (movieID is None): _b_m_logger.error('empty title or movieID for "%s"', txt) if rolesNoChar: rolesNoChar = filter(None, [x.strip() for x in rolesNoChar.split('/')]) if not role: role = [] elif not isinstance(role, list): role = [role] role += rolesNoChar notes = notes.strip() if additionalNotes: additionalNotes = re_spaces.sub(' ', additionalNotes).strip() if notes: notes += u' ' notes += additionalNotes if role and isinstance(role, list) and notes.endswith(role[-1].replace('\n', ' ')): role = role[:-1] m = Movie(title=title, movieID=movieID, notes=notes, currentRole=role, roleID=roleID, roleIsPerson=_parsingCharacter, modFunct=modFunct, accessSystem=accessSystem) if roleNotes and len(roleNotes) == len(roleID): for idx, role in enumerate(m.currentRole): try: if roleNotes[idx]: role.notes = roleNotes[idx] except IndexError: break # Status can't be checked here, and must be detected by the parser. if status: m['status'] = status return m class DOMParserBase(object): """Base parser to handle HTML data from the IMDb's web server.""" _defGetRefs = False _containsObjects = False preprocessors = [] extractors = [] usingModule = None _logger = logging.getLogger('imdbpy.parser.http.domparser') def __init__(self, useModule=None): """Initialize the parser. useModule can be used to force it to use 'BeautifulSoup' or 'lxml'; by default, it's auto-detected, using 'lxml' if available and falling back to 'BeautifulSoup' otherwise.""" # Module to use. if useModule is None: useModule = ('lxml', 'BeautifulSoup') if not isinstance(useModule, (tuple, list)): useModule = [useModule] self._useModule = useModule nrMods = len(useModule) _gotError = False for idx, mod in enumerate(useModule): mod = mod.strip().lower() try: if mod == 'lxml': from lxml.html import fromstring from lxml.etree import tostring self._is_xml_unicode = False self.usingModule = 'lxml' elif mod == 'beautifulsoup': from bsouplxml.html import fromstring from bsouplxml.etree import tostring self._is_xml_unicode = True self.usingModule = 'beautifulsoup' else: self._logger.warn('unknown module "%s"' % mod) continue self.fromstring = fromstring self._tostring = tostring if _gotError: warnings.warn('falling back to "%s"' % mod) break except ImportError, e: if idx+1 >= nrMods: # Raise the exception, if we don't have any more # options to try. raise IMDbError('unable to use any parser in %s: %s' % \ (str(useModule), str(e))) else: warnings.warn('unable to use "%s": %s' % (mod, str(e))) _gotError = True continue else: raise IMDbError('unable to use parsers in %s' % str(useModule)) # Fall-back defaults. self._modFunct = None self._as = 'http' self._cname = self.__class__.__name__ self._init() self.reset() def reset(self): """Reset the parser.""" # Names and titles references. self._namesRefs = {} self._titlesRefs = {} self._charactersRefs = {} self._reset() def _init(self): """Subclasses can override this method, if needed.""" pass def _reset(self): """Subclasses can override this method, if needed.""" pass def parse(self, html_string, getRefs=None, **kwds): """Return the dictionary generated from the given html string; getRefs can be used to force the gathering of movies/persons/characters references.""" self.reset() if getRefs is not None: self.getRefs = getRefs else: self.getRefs = self._defGetRefs # Useful only for the testsuite. if not isinstance(html_string, unicode): html_string = unicode(html_string, 'latin_1', 'replace') html_string = subXMLRefs(html_string) # Temporary fix: self.parse_dom must work even for empty strings. html_string = self.preprocess_string(html_string) html_string = html_string.strip() if self.usingModule == 'beautifulsoup': # tag attributes like title="&#x22;Family Guy&#x22;" will be # converted to title=""Family Guy"" and this confuses BeautifulSoup. html_string = html_string.replace('""', '"') # Browser-specific escapes create problems to BeautifulSoup. html_string = html_string.replace('<!--[if IE]>', '"') html_string = html_string.replace('<![endif]-->', '"') #print html_string.encode('utf8') if html_string: dom = self.get_dom(html_string) #print self.tostring(dom).encode('utf8') try: dom = self.preprocess_dom(dom) except Exception, e: self._logger.error('%s: caught exception preprocessing DOM', self._cname, exc_info=True) if self.getRefs: try: self.gather_refs(dom) except Exception, e: self._logger.warn('%s: unable to gather refs: %s', self._cname, exc_info=True) data = self.parse_dom(dom) else: data = {} try: data = self.postprocess_data(data) except Exception, e: self._logger.error('%s: caught exception postprocessing data', self._cname, exc_info=True) if self._containsObjects: self.set_objects_params(data) data = self.add_refs(data) return data def _build_empty_dom(self): from bsouplxml import _bsoup return _bsoup.BeautifulSoup('') def get_dom(self, html_string): """Return a dom object, from the given string.""" try: dom = self.fromstring(html_string) if dom is None: dom = self._build_empty_dom() self._logger.error('%s: using a fake empty DOM', self._cname) return dom except Exception, e: self._logger.error('%s: caught exception parsing DOM', self._cname, exc_info=True) return self._build_empty_dom() def xpath(self, element, path): """Return elements matching the given XPath.""" try: xpath_result = element.xpath(path) if self._is_xml_unicode: return xpath_result result = [] for item in xpath_result: if isinstance(item, str): item = unicode(item) result.append(item) return result except Exception, e: self._logger.error('%s: caught exception extracting XPath "%s"', self._cname, path, exc_info=True) return [] def tostring(self, element): """Convert the element to a string.""" if isinstance(element, (unicode, str)): return unicode(element) else: try: return self._tostring(element, encoding=unicode) except Exception, e: self._logger.error('%s: unable to convert to string', self._cname, exc_info=True) return u'' def clone(self, element): """Clone an element.""" return self.fromstring(self.tostring(element)) def preprocess_string(self, html_string): """Here we can modify the text, before it's parsed.""" if not html_string: return html_string # Remove silly &nbsp;&raquo; and &ndash; chars. html_string = html_string.replace(u' \xbb', u'') html_string = html_string.replace(u'&ndash;', u'-') try: preprocessors = self.preprocessors except AttributeError: return html_string for src, sub in preprocessors: # re._pattern_type is present only since Python 2.5. if callable(getattr(src, 'sub', None)): html_string = src.sub(sub, html_string) elif isinstance(src, str): html_string = html_string.replace(src, sub) elif callable(src): try: html_string = src(html_string) except Exception, e: _msg = '%s: caught exception preprocessing html' self._logger.error(_msg, self._cname, exc_info=True) continue ##print html_string.encode('utf8') return html_string def gather_refs(self, dom): """Collect references.""" grParser = GatherRefs(useModule=self._useModule) grParser._as = self._as grParser._modFunct = self._modFunct refs = grParser.parse_dom(dom) refs = grParser.postprocess_data(refs) self._namesRefs = refs['names refs'] self._titlesRefs = refs['titles refs'] self._charactersRefs = refs['characters refs'] def preprocess_dom(self, dom): """Last chance to modify the dom, before the rules in self.extractors are applied by the parse_dom method.""" return dom def parse_dom(self, dom): """Parse the given dom according to the rules specified in self.extractors.""" result = {} for extractor in self.extractors: ##print extractor.label if extractor.group is None: elements = [(extractor.label, element) for element in self.xpath(dom, extractor.path)] else: groups = self.xpath(dom, extractor.group) elements = [] for group in groups: group_key = self.xpath(group, extractor.group_key) if not group_key: continue group_key = group_key[0] # XXX: always tries the conversion to unicode: # BeautifulSoup.NavigableString is a subclass # of unicode, and so it's never converted. group_key = self.tostring(group_key) normalizer = extractor.group_key_normalize if normalizer is not None: if callable(normalizer): try: group_key = normalizer(group_key) except Exception, e: _m = '%s: unable to apply group_key normalizer' self._logger.error(_m, self._cname, exc_info=True) group_elements = self.xpath(group, extractor.path) elements.extend([(group_key, element) for element in group_elements]) for group_key, element in elements: for attr in extractor.attrs: if isinstance(attr.path, dict): data = {} for field in attr.path.keys(): path = attr.path[field] value = self.xpath(element, path) if not value: data[field] = None else: # XXX: use u'' , to join? data[field] = ''.join(value) else: data = self.xpath(element, attr.path) if not data: data = None else: data = attr.joiner.join(data) if not data: continue attr_postprocess = attr.postprocess if callable(attr_postprocess): try: data = attr_postprocess(data) except Exception, e: _m = '%s: unable to apply attr postprocess' self._logger.error(_m, self._cname, exc_info=True) key = attr.key if key is None: key = group_key elif key.startswith('.'): # assuming this is an xpath try: key = self.xpath(element, key)[0] except IndexError: self._logger.error('%s: XPath returned no items', self._cname, exc_info=True) elif key.startswith('self.'): key = getattr(self, key[5:]) if attr.multi: if key not in result: result[key] = [] result[key].append(data) else: if isinstance(data, dict): result.update(data) else: result[key] = data return result def postprocess_data(self, data): """Here we can modify the data.""" return data def set_objects_params(self, data): """Set parameters of Movie/Person/... instances, since they are not always set in the parser's code.""" for obj in flatten(data, yieldDictKeys=True, scalar=_Container): obj.accessSystem = self._as obj.modFunct = self._modFunct def add_refs(self, data): """Modify data according to the expected output.""" if self.getRefs: titl_re = ur'(%s)' % '|'.join([re.escape(x) for x in self._titlesRefs.keys()]) if titl_re != ur'()': re_titles = re.compile(titl_re, re.U) else: re_titles = None nam_re = ur'(%s)' % '|'.join([re.escape(x) for x in self._namesRefs.keys()]) if nam_re != ur'()': re_names = re.compile(nam_re, re.U) else: re_names = None chr_re = ur'(%s)' % '|'.join([re.escape(x) for x in self._charactersRefs.keys()]) if chr_re != ur'()': re_characters = re.compile(chr_re, re.U) else: re_characters = None _putRefs(data, re_titles, re_names, re_characters) return {'data': data, 'titlesRefs': self._titlesRefs, 'namesRefs': self._namesRefs, 'charactersRefs': self._charactersRefs} class Extractor(object): """Instruct the DOM parser about how to parse a document.""" def __init__(self, label, path, attrs, group=None, group_key=None, group_key_normalize=None): """Initialize an Extractor object, used to instruct the DOM parser about how to parse a document.""" # rarely (never?) used, mostly for debugging purposes. self.label = label self.group = group if group_key is None: self.group_key = ".//text()" else: self.group_key = group_key self.group_key_normalize = group_key_normalize self.path = path # A list of attributes to fetch. if isinstance(attrs, Attribute): attrs = [attrs] self.attrs = attrs def __repr__(self): """String representation of an Extractor object.""" r = '<Extractor id:%s (label=%s, path=%s, attrs=%s, group=%s, ' \ 'group_key=%s group_key_normalize=%s)>' % (id(self), self.label, self.path, repr(self.attrs), self.group, self.group_key, self.group_key_normalize) return r class Attribute(object): """The attribute to consider, for a given node.""" def __init__(self, key, multi=False, path=None, joiner=None, postprocess=None): """Initialize an Attribute object, used to specify the attribute to consider, for a given node.""" # The key under which information will be saved; can be a string or an # XPath. If None, the label of the containing extractor will be used. self.key = key self.multi = multi self.path = path if joiner is None: joiner = '' self.joiner = joiner # Post-process this set of information. self.postprocess = postprocess def __repr__(self): """String representation of an Attribute object.""" r = '<Attribute id:%s (key=%s, multi=%s, path=%s, joiner=%s, ' \ 'postprocess=%s)>' % (id(self), self.key, self.multi, repr(self.path), self.joiner, repr(self.postprocess)) return r def _parse_ref(text, link, info): """Manage links to references.""" if link.find('/title/tt') != -1: yearK = re_yearKind_index.match(info) if yearK and yearK.start() == 0: text += ' %s' % info[:yearK.end()] return (text.replace('\n', ' '), link) class GatherRefs(DOMParserBase): """Parser used to gather references to movies, persons and characters.""" _attrs = [Attribute(key=None, multi=True, path={ 'text': './text()', 'link': './@href', 'info': './following::text()[1]' }, postprocess=lambda x: _parse_ref(x.get('text') or u'', x.get('link') or '', (x.get('info') or u'').strip()))] extractors = [ Extractor(label='names refs', path="//a[starts-with(@href, '/name/nm')][string-length(@href)=16]", attrs=_attrs), Extractor(label='titles refs', path="//a[starts-with(@href, '/title/tt')]" \ "[string-length(@href)=17]", attrs=_attrs), Extractor(label='characters refs', path="//a[starts-with(@href, '/character/ch')]" \ "[string-length(@href)=21]", attrs=_attrs), ] def postprocess_data(self, data): result = {} for item in ('names refs', 'titles refs', 'characters refs'): result[item] = {} for k, v in data.get(item, []): k = k.strip() v = v.strip() if not (k and v): continue if not v.endswith('/'): continue imdbID = analyze_imdbid(v) if item == 'names refs': obj = Person(personID=imdbID, name=k, accessSystem=self._as, modFunct=self._modFunct) elif item == 'titles refs': obj = Movie(movieID=imdbID, title=k, accessSystem=self._as, modFunct=self._modFunct) else: obj = Character(characterID=imdbID, name=k, accessSystem=self._as, modFunct=self._modFunct) # XXX: companies aren't handled: are they ever found in text, # as links to their page? result[item][k] = obj return result def add_refs(self, data): return data
gpl-3.0
rnestler/servo
tests/wpt/web-platform-tests/tools/wptserve/docs/conf.py
467
7855
# -*- coding: utf-8 -*- # # wptserve documentation build configuration file, created by # sphinx-quickstart on Wed Aug 14 17:23:24 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os sys.path.insert(0, os.path.abspath("..")) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'wptserve' copyright = u'2013, Mozilla Foundation and other wptserve contributers' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'wptservedoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'wptserve.tex', u'wptserve Documentation', u'James Graham', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'wptserve', u'wptserve Documentation', [u'James Graham'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'wptserve', u'wptserve Documentation', u'James Graham', 'wptserve', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
mpl-2.0
gfreed/android_external_chromium-org
tools/site_compare/commands/compare2.py
189
6517
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """SiteCompare command to invoke the same page in two versions of a browser. Does the easiest compatibility test: equality comparison between two different versions of the same browser. Invoked with a series of command line options that specify which URLs to check, which browser to use, where to store results, etc. """ import os # Functions for walking the directory tree import tempfile # Get a temporary directory to hold intermediates import command_line import drivers # Functions for driving keyboard/mouse/windows, OS-specific import operators # Functions that, given two bitmaps as input, produce # output depending on the performance of an operation import scrapers # Functions that know how to capture a render from # particular browsers def CreateCommand(cmdline): """Inserts the command and arguments into a command line for parsing.""" cmd = cmdline.AddCommand( ["compare2"], "Compares the output of two browsers on the same URL or list of URLs", ValidateCompare2, ExecuteCompare2) cmd.AddArgument( ["-b1", "--browser1"], "Full path to first browser's executable", type="readfile", metaname="PATH", required=True) cmd.AddArgument( ["-b2", "--browser2"], "Full path to second browser's executable", type="readfile", metaname="PATH", required=True) cmd.AddArgument( ["-b", "--browser"], "Which browser to use", type="string", default="chrome") cmd.AddArgument( ["-b1v", "--browser1ver"], "Version of first browser", metaname="VERSION") cmd.AddArgument( ["-b2v", "--browser2ver"], "Version of second browser", metaname="VERSION") cmd.AddArgument( ["-b1n", "--browser1name"], "Optional name for first browser (used in " "directory to hold intermediate files)", metaname="NAME") cmd.AddArgument( ["-b2n", "--browser2name"], "Optional name for second browser (used in " "directory to hold intermediate files)", metaname="NAME") cmd.AddArgument( ["-o", "--outdir"], "Directory to store scrape files", metaname="DIR") cmd.AddArgument( ["-u", "--url"], "URL to compare") cmd.AddArgument( ["-l", "--list"], "List of URLs to compare", type="readfile") cmd.AddMutualExclusion(["--url", "--list"]) cmd.AddArgument( ["-s", "--startline"], "First line of URL list", type="int") cmd.AddArgument( ["-e", "--endline"], "Last line of URL list (exclusive)", type="int") cmd.AddArgument( ["-c", "--count"], "Number of lines of URL file to use", type="int") cmd.AddDependency("--startline", "--list") cmd.AddRequiredGroup(["--url", "--list"]) cmd.AddDependency("--endline", "--list") cmd.AddDependency("--count", "--list") cmd.AddMutualExclusion(["--count", "--endline"]) cmd.AddDependency("--count", "--startline") cmd.AddArgument( ["-t", "--timeout"], "Amount of time (seconds) to wait for browser to " "finish loading", type="int", default=60) cmd.AddArgument( ["-log", "--logfile"], "File to write output", type="string", required=True) cmd.AddArgument( ["-sz", "--size"], "Browser window size", default=(800, 600), type="coords") cmd.AddArgument( ["-m", "--maskdir"], "Path that holds masks to use for comparison") cmd.AddArgument( ["-d", "--diffdir"], "Path to hold the difference of comparisons that fail") def ValidateCompare2(command): """Validate the arguments to compare2. Raises ParseError if failed.""" executables = [".exe", ".com", ".bat"] if (os.path.splitext(command["--browser1"])[1].lower() not in executables or os.path.splitext(command["--browser2"])[1].lower() not in executables): raise command_line.ParseError("Browser filename must be an executable") def ExecuteCompare2(command): """Executes the Compare2 command.""" if command["--url"]: url_list = [command["--url"]] else: startline = command["--startline"] if command["--count"]: endline = startline+command["--count"] else: endline = command["--endline"] url_list = [url.strip() for url in open(command["--list"], "r").readlines()[startline:endline]] log_file = open(command["--logfile"], "w") outdir = command["--outdir"] if not outdir: outdir = tempfile.gettempdir() scrape_info_list = [] class ScrapeInfo(object): """Helper class to hold information about a scrape.""" __slots__ = ["browser_path", "scraper", "outdir", "result"] for index in xrange(1, 3): scrape_info = ScrapeInfo() scrape_info.browser_path = command["--browser%d" % index] scrape_info.scraper = scrapers.GetScraper( (command["--browser"], command["--browser%dver" % index])) if command["--browser%dname" % index]: scrape_info.outdir = os.path.join(outdir, command["--browser%dname" % index]) else: scrape_info.outdir = os.path.join(outdir, str(index)) drivers.windowing.PreparePath(scrape_info.outdir) scrape_info_list.append(scrape_info) compare = operators.GetOperator("equals_with_mask") for url in url_list: success = True for scrape_info in scrape_info_list: scrape_info.result = scrape_info.scraper.Scrape( [url], scrape_info.outdir, command["--size"], (0, 0), command["--timeout"], path=scrape_info.browser_path) if not scrape_info.result: scrape_info.result = "success" else: success = False result = "unknown" if success: result = "equal" file1 = drivers.windowing.URLtoFilename( url, scrape_info_list[0].outdir, ".bmp") file2 = drivers.windowing.URLtoFilename( url, scrape_info_list[1].outdir, ".bmp") comparison_result = compare.Compare(file1, file2, maskdir=command["--maskdir"]) if comparison_result is not None: result = "not-equal" if command["--diffdir"]: comparison_result[1].save( drivers.windowing.URLtoFilename(url, command["--diffdir"], ".bmp")) # TODO(jhaas): maybe use the logging module rather than raw file writes log_file.write("%s %s %s %s\n" % (url, scrape_info_list[0].result, scrape_info_list[1].result, result))
bsd-3-clause
hyde/hyde
tests/ext/test_sass.py
1
1430
# -*- coding: utf-8 -*- """ Use nose `$ pip install nose` `$ nosetests` """ from hyde.generator import Generator from hyde.site import Site from fswrap import File, Folder from util import assert_no_diff SCSS_SOURCE = File(__file__).parent.child_folder('scss') TEST_SITE = File(__file__).parent.parent.child_folder('_test') class TestSass(object): def setUp(self): TEST_SITE.make() TEST_SITE.parent.child_folder( 'sites/test_jinja').copy_contents_to(TEST_SITE) SCSS_SOURCE.copy_contents_to(TEST_SITE.child('content/media/css')) File(TEST_SITE.child('content/media/css/site.css')).delete() def tearDown(self): TEST_SITE.delete() def test_scss(self): s = Site(TEST_SITE) s.config.mode = 'prod' s.config.plugins = ['hyde.ext.plugins.css.SassPlugin'] s.config.sass = {'files': ['media/css/sass.scss']} source = TEST_SITE.child('content/media/css/sass.scss') target = File( Folder(s.config.deploy_root_path).child('media/css/sass.css')) gen = Generator(s) gen.generate_resource_at_path(source) assert target.exists text = target.read_all() expected_text = File(SCSS_SOURCE.child('expected-sass.css')).read_all() print("TEXT" + "-" * 80) print(text) print("-" * 80) print(expected_text) assert_no_diff(expected_text, text)
mit
btovar/autopyfactory
autopyfactory/plugins/queue/batchsubmit/CondorEC2.py
1
11034
#!/bin/env python # # AutoPyfactory batch plugin for Condor # from CondorBase import CondorBase from autopyfactory import jsd from autopyfactory.condor import killids, mincondorversion import subprocess import time import commands import logging import traceback #mincondorversion(8,1,1) class CondorEC2(CondorBase): id = 'condorec2' def __init__(self, apfqueue, config, section): qcl = config newqcl = qcl.clone().filterkeys('batchsubmit.condorec2', 'batchsubmit.condorbase') super(CondorEC2, self).__init__(apfqueue, newqcl, section) try: self.gridresource = qcl.generic_get(self.apfqname, 'batchsubmit.condorec2.gridresource') self.ami_id = qcl.generic_get(self.apfqname, 'batchsubmit.condorec2.ami_id') self.instance_type = qcl.generic_get(self.apfqname, 'batchsubmit.condorec2.instance_type') self.user_data = qcl.generic_get(self.apfqname, 'batchsubmit.condorec2.user_data') self.user_data_file = qcl.generic_get(self.apfqname, 'batchsubmit.condorec2.user_data_file') self.access_key_id = qcl.generic_get(self.apfqname,'batchsubmit.condorec2.access_key_id') self.secret_access_key = qcl.generic_get(self.apfqname,'batchsubmit.condorec2.secret_access_key') self.spot_price = qcl.generic_get(self.apfqname, 'batchsubmit.condorec2.spot_price') self.usessh = qcl.generic_get(self.apfqname, 'batchsubmit.condorec2.usessh') if self.spot_price: self.spot_price = float(self.spot_price) self.peaceful = qcl.generic_get(self.apfqname, 'batchsubmit.condorec2.peaceful') self.security_groups = qcl.generic_get(self.apfqname, 'batchsubmit.condorec2.security_groups') self.log.debug("Successfully got all config values for EC2BatchSubmit plugin.") self.log.debug('CondorEC2: Object properly initialized.') except Exception, e: self.log.error("Problem getting object configuration variables.") self.log.debug("Exception: %s" % traceback.format_exc()) def _addJSD(self): """ add things to the JSD object """ self.log.debug('CondorEC2.addJSD: Starting.') super(CondorEC2, self)._addJSD() self.JSD.add("universe", "grid") self.JSD.add('grid_resource', 'ec2 %s' % self.gridresource) self.JSD.add("ec2_access_key_id", "%s" % self.access_key_id) self.JSD.add("ec2_secret_access_key", "%s" % self.secret_access_key) # -- EC2 specific parameters -- self.JSD.add("ec2_ami_id", "%s" % self.ami_id) self.JSD.add("executable", "%s" % self.apfqueue.apfqname) self.JSD.add("ec2_instance_type", "%s" % self.instance_type) if self.user_data: self.JSD.add('ec2_user_data', '%s' % self.user_data) if self.user_data_file: self.JSD.add('ec2_user_data_file', '%s' % self.user_data_file) if self.spot_price: self.JSD.add('ec2_spot_price', '%f' % self.spot_price) if self.security_groups: self.JSD.add('ec2_security_groups', '%s' % self.security_groups) self.log.debug('CondorEC2.addJSD: Leaving.') def retire(self, n, order='oldest'): """ trigger retirement of this many nodes, by looking at this parent APF queue's CondorCloudBatchStatus plugin. Scan jobinfo for node start times execute condor_off -peaceful -daemon startd -name <machine> OR ssh <EC2PublicIP> condor_off -peaceful -daemon startd for each desired retirement. We only retire by shutting down startds, never by terminating VM jobs directly. This is to avoid race conditions/slight information mismatches due to time. E.g. just because the last condor_status showed a startd as idle, doesn't mean it is still idle during this queue cycle. But we should preferentially retire nodes that are Idle over ones that we know are busy. If we don't have information about startds, then unconditionally kill N VM jobs for this queue. """ self.log.debug("Beginning to retire %d VM jobs..." % n) self.log.debug("Getting jobinfo for [%s]" % (self.apfqueue.apfqname)) jobinfo = self.apfqueue.batchstatus_plugin.getJobInfo(queue=self.apfqueue.apfqname) self.log.debug("Jobinfo is %s" % jobinfo) if jobinfo: if self.peaceful: numtoretire = n numretired = 0 idlelist = [] busylist = [] for job in jobinfo: if job.executeinfo is not None: self.log.debug("Handling instanceid = %s" % job.executeinfo.instanceid) stat = job.executeinfo.getStatus() if stat == 'busy': busylist.append(job) elif stat == 'idle': idlelist.append(job) sortedlist = idlelist + busylist for job in sortedlist: self._retirenode(job) numtoretire = numtoretire - 1 numretired += 1 self.log.debug("numtoretire = %d" % numtoretire) if numtoretire <= 0: break self.log.debug("Retired %d VM jobs" % numretired) else: self.log.debug("Non-peaceful. Kill VM jobs...") if order == 'oldest': jobinfo.sort(key = lambda x: x.enteredcurrentstatus, reverse=True) elif order == 'newest': jobinfo.sort(key = lambda x: x.enteredcurrentstatus) killlist = [] for i in range(0, n): j = jobinfo.pop() killlist.append( "%s.%s" % (j.clusterid, j.procid)) self.log.debug("About to kill list of %s ids. First one is %s" % (len(killlist), killlist[0] )) killids(killlist) self.log.debug("killids returned.") else: self.log.debug("Some info unavailable. Do nothing.") def _retirenode(self, jobinfo): """ Do whatever is needed to tell the node to retire... """ self.log.debug("Retiring node %s (%s)" % (jobinfo.executeinfo.hostname, jobinfo.ec2instancename)) exeinfo = jobinfo.executeinfo publicip = exeinfo.hostname machine = exeinfo.machine condorid = "%s.%s" % (jobinfo.clusterid, jobinfo.procid) if self.usessh: self.log.debug("Trying to use SSH to retire node %s" % publicip) if self.peaceful: cmd='ssh root@%s "condor_off -peaceful -startd"' % publicip else: cmd='ssh root@%s "condor_off -startd"' % publicip self.log.debug("retire cmd is %s" % cmd) before = time.time() p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out = None (out, err) = p.communicate() delta = time.time() - before self.log.debug('It took %s seconds to issue the command' %delta) self.log.debug('%s seconds to issue command' %delta) if p.returncode == 0: self.log.debug('Leaving with OK return code.') else: self.log.warning('Leaving with bad return code. rc=%s err=%s' %(p.returncode, err )) # invoke ssh to retire node else: # call condor_off locally self.log.debug("Trying local retirement of node %s" % publicip) if machine.strip() != "": if self.peaceful: cmd='condor_off -peaceful -startd -name %s' % machine else: cmd='condor_off -startd -name %s' % machine self.log.debug("retire cmd is %s" % cmd) before = time.time() p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out = None (out, err) = p.communicate() delta = time.time() - before self.log.debug('It took %s seconds to issue the command' %delta) self.log.debug('%s seconds to issue command' %delta) if p.returncode == 0: self.log.debug('Leaving with OK return code.') else: out = out.replace("\n", " ") out = err.replace("\n", " ") self.log.warning('Leaving with bad return code. rc=%s err="%s" out="%s"' %(p.returncode, err, out )) else: self.log.warning("Unable to retire node %s (%s) because it has an empty machine name." % (jobinfo.executeinfo.hostname, jobinfo.ec2instancename)) def cleanup(self): """ """ self.log.debug("Cleanup called in EC2. Retiring...") self._killretired() def _killretired(self): """ scan through jobinfo for this queue with job """ self.log.debug("Killretired process triggered. Searching...") try: jobinfo = self.apfqueue.batchstatus_plugin.getJobInfo(queue=self.apfqueue.apfqname) self.log.debug("Finding and killing VM jobs in 'retired' state.") killlist = [] if jobinfo: for j in jobinfo: self.log.debug("jobinfo is %s " % j) if j.executeinfo: st = j.executeinfo.getStatus() self.log.debug("exe status for %s is %s" % (j.ec2instancename, st) ) if st == 'retired': killlist.append( "%s.%s" % (j.clusterid, j.procid)) else: self.log.warning("There seems to be a VM job without even exeinfo. ec2id: %s" % j.ec2instancename) self.log.debug("killlist length is %s" % len(killlist)) if killlist: self.log.debug("About to kill list of %s ids. First one is %s" % (len(killlist), killlist[0] )) killids(killlist) else: self.log.debug("No VM jobs to kill for apfqueue %s" % self.apfqueue.apfqname ) except NotImplementedError: self.log.debug("Apparently using batchstatus plugin without job info. Skipping.")
apache-2.0
donspaulding/adspygoogle
examples/adspygoogle/dfp/v201204/inventory_service/create_ad_units.py
2
2765
#!/usr/bin/python # # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This code example creates new ad units. To determine which ad units exist, run get_all_ad_units.py Tags: InventoryService.createAdUnits """ __author__ = 'api.shamjeff@gmail.com (Jeff Sham)' # Locate the client library. If module was installed via "setup.py" script, then # the following two lines are not needed. import os import sys sys.path.insert(0, os.path.join('..', '..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle import DfpClient from adspygoogle.common import Utils def main(client, parent_id): # Initialize appropriate service. inventory_service = client.GetService('InventoryService', version='v201204') # Create ad unit size. ad_unit_size = { 'size': { 'width': '300', 'height': '250' }, 'environmentType': 'BROWSER' } # Create ad unit objects. web_ad_unit = { 'name': 'Web_ad_unit_%s' % Utils.GetUniqueName(), 'parentId': parent_id, 'description': 'Web ad unit description.', 'targetWindow': 'BLANK', 'targetPlatform': 'WEB', 'adUnitSizes': [ad_unit_size] } mobile_ad_unit = { 'name': 'Mobile_ad_unit_%s' % Utils.GetUniqueName(), 'parentId': parent_id, 'description': 'Mobile ad unit description.', 'targetWindow': 'BLANK', 'targetPlatform': 'MOBILE', 'adUnitSizes': [ad_unit_size] } # Add ad units. ad_units = inventory_service.CreateAdUnits([web_ad_unit, mobile_ad_unit]) # Display results. for ad_unit in ad_units: print ('Ad unit with ID \'%s\', name \'%s\', and target platform \'%s\' ' 'was created.' % (ad_unit['id'], ad_unit['name'], ad_unit['targetPlatform'])) if __name__ == '__main__': # Initialize client object. dfp_client = DfpClient(path=os.path.join('..', '..', '..', '..', '..')) # Get the Network Service. network_service = dfp_client.GetService('NetworkService', version='v201204') # Set the parent ad unit's ID for all ad units to be created under. parent_id = network_service.GetCurrentNetwork()[0]['effectiveRootAdUnitId'] main(dfp_client, parent_id)
apache-2.0
lxneng/incubator-airflow
tests/contrib/hooks/test_sqoop_hook.py
15
13472
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import collections import json import unittest from airflow import configuration, models from airflow.contrib.hooks.sqoop_hook import SqoopHook from airflow.exceptions import AirflowException from airflow.utils import db from mock import patch, call from io import StringIO class TestSqoopHook(unittest.TestCase): _config = { 'conn_id': 'sqoop_test', 'num_mappers': 22, 'verbose': True, 'properties': { 'mapred.map.max.attempts': '1' }, 'hcatalog_database': 'hive_database', 'hcatalog_table': 'hive_table' } _config_export = { 'table': 'domino.export_data_to', 'export_dir': '/hdfs/data/to/be/exported', 'input_null_string': '\\n', 'input_null_non_string': '\\t', 'staging_table': 'database.staging', 'clear_staging_table': True, 'enclosed_by': '"', 'escaped_by': '\\', 'input_fields_terminated_by': '|', 'input_lines_terminated_by': '\n', 'input_optionally_enclosed_by': '"', 'batch': True, 'relaxed_isolation': True, 'extra_export_options': collections.OrderedDict([ ('update-key', 'id'), ('update-mode', 'allowinsert') ]) } _config_import = { 'target_dir': '/hdfs/data/target/location', 'append': True, 'file_type': 'parquet', 'split_by': '\n', 'direct': True, 'driver': 'com.microsoft.jdbc.sqlserver.SQLServerDriver', 'extra_import_options': { 'hcatalog-storage-stanza': "\"stored as orcfile\"", 'show': '' } } _config_json = { 'namenode': 'http://0.0.0.0:50070/', 'job_tracker': 'http://0.0.0.0:50030/', 'libjars': '/path/to/jars', 'files': '/path/to/files', 'archives': '/path/to/archives' } def setUp(self): configuration.load_test_config() db.merge_conn( models.Connection( conn_id='sqoop_test', conn_type='sqoop', schema='schema', host='rmdbs', port=5050, extra=json.dumps(self._config_json) ) ) @patch('subprocess.Popen') def test_popen(self, mock_popen): # Given mock_popen.return_value.stdout = StringIO(u'stdout') mock_popen.return_value.stderr = StringIO(u'stderr') mock_popen.return_value.returncode = 0 mock_popen.return_value.communicate.return_value = [StringIO(u'stdout\nstdout'), StringIO(u'stderr\nstderr')] # When hook = SqoopHook(conn_id='sqoop_test') hook.export_table(**self._config_export) # Then self.assertEqual(mock_popen.mock_calls[0], call( ['sqoop', 'export', '-fs', self._config_json['namenode'], '-jt', self._config_json['job_tracker'], '-libjars', self._config_json['libjars'], '-files', self._config_json['files'], '-archives', self._config_json['archives'], '--connect', 'rmdbs:5050/schema', '--input-null-string', self._config_export['input_null_string'], '--input-null-non-string', self._config_export['input_null_non_string'], '--staging-table', self._config_export['staging_table'], '--clear-staging-table', '--enclosed-by', self._config_export['enclosed_by'], '--escaped-by', self._config_export['escaped_by'], '--input-fields-terminated-by', self._config_export['input_fields_terminated_by'], '--input-lines-terminated-by', self._config_export['input_lines_terminated_by'], '--input-optionally-enclosed-by', self._config_export['input_optionally_enclosed_by'], '--batch', '--relaxed-isolation', '--export-dir', self._config_export['export_dir'], '--update-key', 'id', '--update-mode', 'allowinsert', '--table', self._config_export['table']], stderr=-2, stdout=-1)) def test_submit_none_mappers(self): """ Test to check that if value of num_mappers is None, then it shouldn't be in the cmd built. """ _config_without_mappers = self._config.copy() _config_without_mappers['num_mappers'] = None hook = SqoopHook(**_config_without_mappers) cmd = ' '.join(hook._prepare_command()) self.assertNotIn('--num-mappers', cmd) def test_submit(self): """ Tests to verify that from connection extra option the options are added to the Sqoop command. """ hook = SqoopHook(**self._config) cmd = ' '.join(hook._prepare_command()) # Check if the config has been extracted from the json if self._config_json['namenode']: self.assertIn("-fs {}".format(self._config_json['namenode']), cmd) if self._config_json['job_tracker']: self.assertIn("-jt {}".format(self._config_json['job_tracker']), cmd) if self._config_json['libjars']: self.assertIn("-libjars {}".format(self._config_json['libjars']), cmd) if self._config_json['files']: self.assertIn("-files {}".format(self._config_json['files']), cmd) if self._config_json['archives']: self.assertIn( "-archives {}".format(self._config_json['archives']), cmd) self.assertIn("--hcatalog-database {}".format(self._config['hcatalog_database']), cmd) self.assertIn("--hcatalog-table {}".format(self._config['hcatalog_table']), cmd) # Check the regulator stuff passed by the default constructor if self._config['verbose']: self.assertIn("--verbose", cmd) if self._config['num_mappers']: self.assertIn( "--num-mappers {}".format(self._config['num_mappers']), cmd) for key, value in self._config['properties'].items(): self.assertIn("-D {}={}".format(key, value), cmd) # We don't have the sqoop binary available, and this is hard to mock, # so just accept an exception for now. with self.assertRaises(OSError): hook.export_table(**self._config_export) with self.assertRaises(OSError): hook.import_table(table='schema.table', target_dir='/sqoop/example/path') with self.assertRaises(OSError): hook.import_query(query='SELECT * FROM sometable', target_dir='/sqoop/example/path') def test_export_cmd(self): """ Tests to verify the hook export command is building correct Sqoop export command. """ hook = SqoopHook() # The subprocess requires an array but we build the cmd by joining on a space cmd = ' '.join( hook._export_cmd( self._config_export['table'], self._config_export['export_dir'], input_null_string=self._config_export['input_null_string'], input_null_non_string=self._config_export[ 'input_null_non_string'], staging_table=self._config_export['staging_table'], clear_staging_table=self._config_export['clear_staging_table'], enclosed_by=self._config_export['enclosed_by'], escaped_by=self._config_export['escaped_by'], input_fields_terminated_by=self._config_export[ 'input_fields_terminated_by'], input_lines_terminated_by=self._config_export[ 'input_lines_terminated_by'], input_optionally_enclosed_by=self._config_export[ 'input_optionally_enclosed_by'], batch=self._config_export['batch'], relaxed_isolation=self._config_export['relaxed_isolation'], extra_export_options=self._config_export['extra_export_options'] ) ) self.assertIn("--input-null-string {}".format( self._config_export['input_null_string']), cmd) self.assertIn("--input-null-non-string {}".format( self._config_export['input_null_non_string']), cmd) self.assertIn("--staging-table {}".format( self._config_export['staging_table']), cmd) self.assertIn("--enclosed-by {}".format( self._config_export['enclosed_by']), cmd) self.assertIn("--escaped-by {}".format( self._config_export['escaped_by']), cmd) self.assertIn("--input-fields-terminated-by {}".format( self._config_export['input_fields_terminated_by']), cmd) self.assertIn("--input-lines-terminated-by {}".format( self._config_export['input_lines_terminated_by']), cmd) self.assertIn("--input-optionally-enclosed-by {}".format( self._config_export['input_optionally_enclosed_by']), cmd) # these options are from the extra export options self.assertIn("--update-key id", cmd) self.assertIn("--update-mode allowinsert", cmd) if self._config_export['clear_staging_table']: self.assertIn("--clear-staging-table", cmd) if self._config_export['batch']: self.assertIn("--batch", cmd) if self._config_export['relaxed_isolation']: self.assertIn("--relaxed-isolation", cmd) def test_import_cmd(self): """ Tests to verify the hook import command is building correct Sqoop import command. """ hook = SqoopHook() # The subprocess requires an array but we build the cmd by joining on a space cmd = ' '.join( hook._import_cmd( self._config_import['target_dir'], append=self._config_import['append'], file_type=self._config_import['file_type'], split_by=self._config_import['split_by'], direct=self._config_import['direct'], driver=self._config_import['driver'], extra_import_options=None ) ) if self._config_import['append']: self.assertIn('--append', cmd) if self._config_import['direct']: self.assertIn('--direct', cmd) self.assertIn('--target-dir {}'.format( self._config_import['target_dir']), cmd) self.assertIn('--driver {}'.format(self._config_import['driver']), cmd) self.assertIn('--split-by {}'.format(self._config_import['split_by']), cmd) # these are from extra options, but not passed to this cmd import command self.assertNotIn('--show', cmd) self.assertNotIn('hcatalog-storage-stanza \"stored as orcfile\"', cmd) cmd = ' '.join( hook._import_cmd( target_dir=None, append=self._config_import['append'], file_type=self._config_import['file_type'], split_by=self._config_import['split_by'], direct=self._config_import['direct'], driver=self._config_import['driver'], extra_import_options=self._config_import['extra_import_options'] ) ) self.assertNotIn('--target-dir', cmd) # these checks are from the extra import options self.assertIn('--show', cmd) self.assertIn('hcatalog-storage-stanza \"stored as orcfile\"', cmd) def test_get_export_format_argument(self): """ Tests to verify the hook get format function is building correct Sqoop command with correct format type. """ hook = SqoopHook() self.assertIn("--as-avrodatafile", hook._get_export_format_argument('avro')) self.assertIn("--as-parquetfile", hook._get_export_format_argument('parquet')) self.assertIn("--as-sequencefile", hook._get_export_format_argument('sequence')) self.assertIn("--as-textfile", hook._get_export_format_argument('text')) with self.assertRaises(AirflowException): hook._get_export_format_argument('unknown') def test_cmd_mask_password(self): """ Tests to verify the hook masking function will correctly mask a user password in Sqoop command. """ hook = SqoopHook() self.assertEqual( hook.cmd_mask_password(['--password', 'supersecret']), ['--password', 'MASKED'] ) cmd = ['--target', 'targettable'] self.assertEqual( hook.cmd_mask_password(cmd), cmd ) if __name__ == '__main__': unittest.main()
apache-2.0
daira/zcash
qa/rpc-tests/finalsaplingroot.py
3
10025
#!/usr/bin/env python3 # Copyright (c) 2018 The Zcash developers # Distributed under the MIT software license, see the accompanying # file COPYING or https://www.opensource.org/licenses/mit-license.php . from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, connect_nodes_bi, get_coinbase_address, start_nodes, wait_and_assert_operationid_status, ) from decimal import Decimal SPROUT_TREE_EMPTY_ROOT = "59d2cde5e65c1414c32ba54f0fe4bdb3d67618125286e6a191317917c812c6d7" SAPLING_TREE_EMPTY_ROOT = "3e49b5f954aa9d3545bc6c37744661eea48d7c34e3000d82b7f0010c30f4c2fb" NULL_FIELD = "0000000000000000000000000000000000000000000000000000000000000000" # Verify block header field 'hashFinalSaplingRoot' (returned in rpc as 'finalsaplingroot') # is updated when Sapling transactions with outputs (commitments) are mined into a block. class FinalSaplingRootTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 4 self.setup_clean_chain = True def setup_network(self, split=False): self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, extra_args=[[ '-txindex' # Avoid JSONRPC error: No information available about transaction ]] * self.num_nodes) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,3) self.is_network_split=False self.sync_all() def run_test(self): self.nodes[0].generate(200) self.sync_all() # Verfify genesis block contains null field for what is now called the final sapling root field. blk = self.nodes[0].getblock("0") assert_equal(blk["finalsaplingroot"], NULL_FIELD) treestate = self.nodes[0].z_gettreestate("0") assert_equal(treestate["height"], 0) assert_equal(treestate["hash"], self.nodes[0].getblockhash(0)) assert_equal(treestate["sprout"]["commitments"]["finalRoot"], SPROUT_TREE_EMPTY_ROOT) assert_equal(treestate["sprout"]["commitments"]["finalState"], "000000") assert("skipHash" not in treestate["sprout"]) assert_equal(treestate["sapling"]["commitments"]["finalRoot"], NULL_FIELD) # There is no sapling state tree yet, and trying to find it in an earlier # block won't succeed (we're at genesis block), so skipHash is absent. assert("finalState" not in treestate["sapling"]) assert("skipHash" not in treestate["sapling"]) # Verify all generated blocks contain the empty root of the Sapling tree. blockcount = self.nodes[0].getblockcount() for height in range(1, blockcount + 1): blk = self.nodes[0].getblock(str(height)) assert_equal(blk["finalsaplingroot"], SAPLING_TREE_EMPTY_ROOT) treestate = self.nodes[0].z_gettreestate(str(height)) assert_equal(treestate["height"], height) assert_equal(treestate["hash"], self.nodes[0].getblockhash(height)) assert("skipHash" not in treestate["sprout"]) assert_equal(treestate["sprout"]["commitments"]["finalRoot"], SPROUT_TREE_EMPTY_ROOT) assert_equal(treestate["sprout"]["commitments"]["finalState"], "000000") assert("skipHash" not in treestate["sapling"]) assert_equal(treestate["sapling"]["commitments"]["finalRoot"], SAPLING_TREE_EMPTY_ROOT) assert_equal(treestate["sapling"]["commitments"]["finalState"], "000000") # Node 0 shields some funds taddr0 = get_coinbase_address(self.nodes[0]) saplingAddr0 = self.nodes[0].z_getnewaddress('sapling') recipients = [] recipients.append({"address": saplingAddr0, "amount": Decimal('20')}) myopid = self.nodes[0].z_sendmany(taddr0, recipients, 1, 0) mytxid = wait_and_assert_operationid_status(self.nodes[0], myopid) self.sync_all() self.nodes[0].generate(1) self.sync_all() # Verify the final Sapling root has changed blk = self.nodes[0].getblock("201") root = blk["finalsaplingroot"] assert(root is not SAPLING_TREE_EMPTY_ROOT) assert(root is not NULL_FIELD) # Verify there is a Sapling output description (its commitment was added to tree) result = self.nodes[0].getrawtransaction(mytxid, 1) assert_equal(len(result["vShieldedOutput"]), 1) # Since there is a now sapling shielded input in the blockchain, # the sapling values should have changed new_treestate = self.nodes[0].z_gettreestate(str(-1)) assert_equal(new_treestate["sapling"]["commitments"]["finalRoot"], root) assert_equal(new_treestate["sprout"], treestate["sprout"]) assert(new_treestate["sapling"]["commitments"]["finalRoot"] != treestate["sapling"]["commitments"]["finalRoot"]) assert(new_treestate["sapling"]["commitments"]["finalState"] != treestate["sapling"]["commitments"]["finalState"]) assert_equal(len(new_treestate["sapling"]["commitments"]["finalRoot"]), 64) assert_equal(len(new_treestate["sapling"]["commitments"]["finalState"]), 70) treestate = new_treestate # Mine an empty block and verify the final Sapling root does not change self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(root, self.nodes[0].getblock("202")["finalsaplingroot"]) # Mine a block with a transparent tx and verify the final Sapling root does not change taddr1 = self.nodes[1].getnewaddress() self.nodes[0].sendtoaddress(taddr1, Decimal("1.23")) self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(len(self.nodes[0].getblock("203")["tx"]), 2) assert_equal(self.nodes[1].z_getbalance(taddr1), Decimal("1.23")) assert_equal(root, self.nodes[0].getblock("203")["finalsaplingroot"]) # Mine a block with a Sprout shielded tx and verify the final Sapling root does not change zaddr1 = self.nodes[1].z_getnewaddress('sprout') recipients = [] recipients.append({"address": zaddr1, "amount": Decimal('10')}) myopid = self.nodes[0].z_sendmany(taddr0, recipients, 1, 0) wait_and_assert_operationid_status(self.nodes[0], myopid) self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(len(self.nodes[0].getblock("204")["tx"]), 2) assert_equal(self.nodes[1].z_getbalance(zaddr1), Decimal("10")) assert_equal(root, self.nodes[0].getblock("204")["finalsaplingroot"]) new_treestate = self.nodes[0].z_gettreestate(str(-1)) assert_equal(new_treestate["sapling"]["commitments"]["finalRoot"], root) assert_equal(new_treestate["sapling"], treestate["sapling"]) assert(new_treestate["sprout"]["commitments"]["finalRoot"] != treestate["sprout"]["commitments"]["finalRoot"]) assert(new_treestate["sprout"]["commitments"]["finalState"] != treestate["sprout"]["commitments"]["finalState"]) assert_equal(len(new_treestate["sprout"]["commitments"]["finalRoot"]), 64) assert_equal(len(new_treestate["sprout"]["commitments"]["finalState"]), 134) treestate = new_treestate # Mine a block with a Sapling shielded recipient and verify the final Sapling root changes saplingAddr1 = self.nodes[1].z_getnewaddress("sapling") recipients = [] recipients.append({"address": saplingAddr1, "amount": Decimal('12.34')}) myopid = self.nodes[0].z_sendmany(saplingAddr0, recipients, 1, 0) mytxid = wait_and_assert_operationid_status(self.nodes[0], myopid) self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(len(self.nodes[0].getblock("205")["tx"]), 2) assert_equal(self.nodes[1].z_getbalance(saplingAddr1), Decimal("12.34")) assert(root is not self.nodes[0].getblock("205")["finalsaplingroot"]) # Verify there is a Sapling output description (its commitment was added to tree) result = self.nodes[0].getrawtransaction(mytxid, 1) assert_equal(len(result["vShieldedOutput"]), 2) # there is Sapling shielded change new_treestate = self.nodes[0].z_gettreestate(str(-1)) assert_equal(new_treestate["sprout"], treestate["sprout"]) assert(new_treestate["sapling"]["commitments"]["finalRoot"] != treestate["sapling"]["commitments"]["finalRoot"]) assert(new_treestate["sapling"]["commitments"]["finalState"] != treestate["sapling"]["commitments"]["finalState"]) assert_equal(len(new_treestate["sapling"]["commitments"]["finalRoot"]), 64) assert_equal(len(new_treestate["sapling"]["commitments"]["finalState"]), 136) treestate = new_treestate # Mine a block with a Sapling shielded sender and transparent recipient and verify the final Sapling root doesn't change taddr2 = self.nodes[0].getnewaddress() recipients = [] recipients.append({"address": taddr2, "amount": Decimal('12.34')}) myopid = self.nodes[1].z_sendmany(saplingAddr1, recipients, 1, 0) mytxid = wait_and_assert_operationid_status(self.nodes[1], myopid) self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(len(self.nodes[0].getblock("206")["tx"]), 2) assert_equal(self.nodes[0].z_getbalance(taddr2), Decimal("12.34")) blk = self.nodes[0].getblock("206") root = blk["finalsaplingroot"] assert_equal(root, self.nodes[0].getblock("205")["finalsaplingroot"]) new_treestate = self.nodes[0].z_gettreestate(str(-1)) assert_equal(new_treestate["sprout"], treestate["sprout"]) assert_equal(new_treestate["sapling"], treestate["sapling"]) if __name__ == '__main__': FinalSaplingRootTest().main()
mit
shauryachats/codechef
codechef/contest.py
1
4271
from utils import * import json import datetime import time from BeautifulSoup import BeautifulSoup import logging def getContestInList(contestList, present, past, future): bucket = [] if future: bucket += contestList['future'] if present: bucket += contestList['present'] if past: bucket += contestList['past'] return bucket """ getContestList() parses all the contests from codechef.com/contests It can also return data of a particular contest, if findContest is not None It can also return contest list according to Future, Present, or Past contests. """ def getContestList(expiryTime = None, writeInFile = None, present = False, past = False, future = False): logging.debug("In getContestList()") expiryTime, writeInFile = getGlobals(expiryTime, writeInFile) contestList = {} if expiryTime > 0: contestList = checkInFile('contests', expiryTime) if contestList is not None: return getContestInList(contestList, present, past, future) else: contestList = {} if not present and not past and not future: present = True past = True future = True soup = downloadContestList() tableList = soup.find('div', { 'class' : 'content-wrapper'}) # # Since "Present Contests", "Future Contests" and the like # are encapsulated in a <h3>, we can use that to find which # all contests are present. # for contestType in tableList.findAll('h3'): key = None if str(contestType.text).startswith('Present'): key = "present" elif str(contestType.text).startswith('Future'): key = "future" elif str(contestType.text).startswith('Past'): key = "past" bucket = [] #The div containing the contest list is next to the h3 tag. for tr in contestType.findNext('div').table.tbody.findAll('tr'): # # 'tr' contains a row containing the contestcode, contestname, start # and end time of all the contests. # contestData = {} tdList = tr.findAll('td') contestData['code'] = tdList[0].text contestData['name'] = tdList[1].text a = datetime.datetime.strptime(tdList[2].text, "%Y-%m-%d %H:%M:%S") contestData['start_time'] = int(time.mktime(a.timetuple())) b = datetime.datetime.strptime(tdList[3].text, "%Y-%m-%d %H:%M:%S") contestData['end_time'] = int(time.mktime(b.timetuple())) bucket.append(contestData) contestList[ key ] = bucket if writeInFile: writeToFile('contests', contestList) logging.debug("getContestList() = " + json.dumps(getContestInList(contestList, present, past, future), indent = 4)) return getContestInList(contestList, present, past, future) # # Parses contest data using CodeChef's sneaky Internal API. # def getContestData(contestCode, expiryTime = None, writeInFile = None): logging.debug("In getContestData("+contestCode+')') expiryTime, writeInFile = getGlobals(expiryTime, writeInFile) data = {} if expiryTime > 0: data = checkInFile('contest/' + contestCode, expiryTime) if data is not None: return data else: data = {} URL = "https://www.codechef.com/api/contests/" + contestCode data = json.loads(requests.get(URL, headers={'User-Agent': 'Mozilla/5.0'}).text) #Make start_time and end_time keys directly in data data['start_time'] = data['time']['start'] data['end_time'] = data['time']['end'] #Removing unnecessary keys. keysToRemove = ['problems_data','time','problemsstats', 'user', 'announcements', 'rules', 'autoRefresh', 'banner', 'todos'] data = removeKeys(data, keysToRemove) #From here too. for contest in data['problems']: data['problems'][contest] = removeKeys(data['problems'][contest], ['status_url','submit_url','problem_url','allow_submission']) if writeInFile: writeToFile('contest/' + contestCode, data) logging.debug("getContestData() = " + json.dumps(data, indent = 4)) return data
mit
josephsuh/extra-specs
nova/api/openstack/compute/contrib/server_start_stop.py
3
2558
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Midokura Japan K.K. # # 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 webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova import exception from nova import log as logging LOG = logging.getLogger(__name__) class ServerStartStopActionController(wsgi.Controller): def __init__(self, *args, **kwargs): super(ServerStartStopActionController, self).__init__(*args, **kwargs) self.compute_api = compute.API() def _get_instance(self, context, instance_uuid): try: return self.compute_api.get(context, instance_uuid) except exception.NotFound: msg = _("Instance not found") raise webob.exc.HTTPNotFound(explanation=msg) @wsgi.action('os-start') def _start_server(self, req, id, body): """Start an instance. """ context = req.environ['nova.context'] instance = self._get_instance(context, id) LOG.debug(_('start instance'), instance=instance) self.compute_api.start(context, instance) return webob.Response(status_int=202) @wsgi.action('os-stop') def _stop_server(self, req, id, body): """Stop an instance.""" context = req.environ['nova.context'] instance = self._get_instance(context, id) LOG.debug(_('stop instance'), instance=instance) self.compute_api.stop(context, instance) return webob.Response(status_int=202) class Server_start_stop(extensions.ExtensionDescriptor): """Start/Stop instance compute API support""" name = "ServerStartStop" alias = "os-server-start-stop" namespace = "http://docs.openstack.org/compute/ext/servers/api/v1.1" updated = "2012-01-23T00:00:00+00:00" def get_controller_extensions(self): controller = ServerStartStopActionController() extension = extensions.ControllerExtension(self, 'servers', controller) return [extension]
apache-2.0
bugobliterator/ardupilot-chibios
Tools/scripts/apj_tool.py
8
7846
#!/usr/bin/env python ''' tool to manipulate ArduPilot firmware files, changing default parameters ''' import os, sys, struct, json, base64, zlib, hashlib import argparse class embedded_defaults(object): '''class to manipulate embedded defaults in a firmware''' def __init__(self, filename): self.filename = filename self.offset = 0 self.extension = os.path.splitext(filename)[1] if self.extension.lower() in ['.apj', '.px4']: self.load_apj() elif self.extension.lower() in ['.abin']: self.load_abin() else: self.load_binary() def load_binary(self): '''load firmware from binary file''' f = open(self.filename,'r') self.firmware = f.read() f.close() print("Loaded binary file of length %u" % len(self.firmware)) def load_abin(self): '''load firmware from abin file''' f = open(self.filename,'r') self.headers = [] while True: line = f.readline().rstrip() if line == '--': break self.headers.append(line) if len(self.headers) > 50: print("Error: too many abin headers") sys.exit(1) self.firmware = f.read() f.close() print("Loaded abin file of length %u" % len(self.firmware)) def load_apj(self): '''load firmware from a json apj or px4 file''' f = open(self.filename,'r') self.fw_json = json.load(f) f.close() self.firmware = zlib.decompress(base64.b64decode(self.fw_json['image'])) print("Loaded apj file of length %u" % len(self.firmware)) def save_binary(self): '''save binary file''' f = open(self.filename, 'w') f.write(self.firmware) f.close() print("Saved binary of length %u" % len(self.firmware)) def save_apj(self): '''save apj file''' self.fw_json['image'] = base64.b64encode(zlib.compress(self.firmware, 9)) f = open(self.filename,'w') json.dump(self.fw_json,f,indent=4) f.truncate() f.close() print("Saved apj of length %u" % len(self.firmware)) def save_abin(self): '''save abin file''' f = open(self.filename,'w') for i in range(len(self.headers)): line = self.headers[i] if line.startswith('MD5: '): h = hashlib.new('md5') h.update(self.firmware) f.write('MD5: %s\n' % h.hexdigest()) else: f.write(line+'\n') f.write('--\n') f.write(self.firmware) f.close() print("Saved abin of length %u" % len(self.firmware)) def find(self): '''find defaults in firmware''' # these are the magic headers from AP_Param.cpp magic_str = "PARMDEF" param_magic = [ 0x55, 0x37, 0xf4, 0xa0, 0x38, 0x5d, 0x48, 0x5b ] while True: i = self.firmware[self.offset:].find(magic_str) if i == -1: return None matched = True for j in range(len(param_magic)): if ord(self.firmware[self.offset+i+j+8]) != param_magic[j]: matched = False break if not matched: self.offset += i+8 continue self.offset += i self.max_len, self.length = struct.unpack("<HH", self.firmware[self.offset+16:self.offset+20]) return True def contents(self): '''return current contents''' contents = self.firmware[self.offset+20:self.offset+20+self.length] # remove carriage returns contents = contents.replace('\r','') return contents def set_contents(self, contents): '''set new defaults as a string''' length = len(contents) if length > self.max_len: print("Error: Length %u larger than maximum %u" % (length, self.max_len)) sys.exit(1) new_fw = self.firmware[:self.offset+18] new_fw += struct.pack("<H", length) new_fw += contents new_fw += self.firmware[self.offset+20+length:] self.firmware = new_fw self.length = len(contents) def set_file(self, filename): '''set defaults to contents of a file''' print("Setting defaults from %s" % filename) f = open(filename, 'r') contents = f.read() f.close() # remove carriage returns from the file contents = contents.replace('\r','') self.set_contents(contents) def split_multi(self, str, separators): '''split a string, handling multiple separators''' for sep in separators: str = str.replace(sep, ' ') return str.split() def set_one(self, set): '''set a single parameter''' v = set.split('=') if len(v) != 2: print("Error: set takes form NAME=VALUE") sys.exit(1) param_name = v[0].upper() param_value = v[1] contents = self.contents() lines = contents.strip().split('\n') changed = False for i in range(len(lines)): a = self.split_multi(lines[i], ", =\t") if len(a) != 2: continue if a[0].upper() == param_name: separator=lines[i][len(param_name)] print("Changing %s from %s to %s" % (param_name, a[1], param_value)) lines[i] = '%s%s%s' % (param_name, separator, param_value) changed = True if not changed: print("Adding %s=%s" % (param_name, param_value)) lines.append('%s=%s' % (param_name, param_value)) contents = '\n'.join(lines) contents = contents.lstrip() + '\n' self.set_contents(contents) def save(self): '''save new firmware''' if self.extension.lower() in ['.apj', '.px4']: self.save_apj() elif self.extension.lower() in ['.abin']: self.save_abin() else: self.save_binary() def extract(self): '''extract firmware image to *.bin''' a = os.path.splitext(self.filename) if len(a) == 1: a.append('.bin') else: a = (a[0], '.bin') binfile = ''.join(a) print("Extracting firmware to %s" % binfile) f = open(binfile,'w') f.write(self.firmware) f.close() def defaults_contents(firmware, ofs, length): '''return current defaults contents''' return firmware parser = argparse.ArgumentParser(description='manipulate parameter defaults in an ArduPilot firmware') parser.add_argument('firmware_file') parser.add_argument('--set-file', type=str, default=None, help='replace parameter defaults from a file') parser.add_argument('--set', type=str, default=None, help='replace one parameter default, in form NAME=VALUE') parser.add_argument('--show', action='store_true', default=False, help='show current parameter defaults') parser.add_argument('--extract', action='store_true', default=False, help='extract firmware image to *.bin') args = parser.parse_args() defaults = embedded_defaults(args.firmware_file) if not defaults.find(): print("Error: Param defaults support not found in firmware") sys.exit(1) print("Found param defaults max_length=%u length=%u" % (defaults.max_len, defaults.length)) if args.set_file: # load new defaults from a file defaults.set_file(args.set_file) defaults.save() if args.set: # set a single parameter defaults.set_one(args.set) defaults.save() if args.show: # show all defaults print(defaults.contents()) if args.extract: defaults.extract()
gpl-3.0
xantin/qualitybots
src/appengine/common/gql_util.py
26
1494
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AppEngine Datastore/GQL related Utilities module. This common util provides helper functionality to extend/support various GQL related queries. """ def FetchEntities(query_obj, limit): """Fetches number of Entities up to limit using query object. Args: query_obj: AppEngine Datastore Query Object. limit: Fetch limit on number of records you want to fetch. Returns: Fetched Entities. """ entities = [] # If Limit is more than 1000 than let's fetch more records using cursor. if limit > 1000: results = query_obj.fetch(1000) entities.extend(results) cursor = query_obj.cursor() while results and limit > len(entities): query_obj.with_cursor(cursor) results = query_obj.fetch(1000) entities.extend(results) cursor = query_obj.cursor() else: entities = query_obj.fetch(limit) return entities
apache-2.0
aidanlister/django
django/core/files/storage.py
281
13339
import errno import os import warnings from datetime import datetime from django.conf import settings from django.core.exceptions import SuspiciousFileOperation from django.core.files import File, locks from django.core.files.move import file_move_safe from django.utils._os import abspathu, safe_join from django.utils.crypto import get_random_string from django.utils.deconstruct import deconstructible from django.utils.deprecation import RemovedInDjango110Warning from django.utils.encoding import filepath_to_uri, force_text from django.utils.functional import LazyObject from django.utils.inspect import func_supports_parameter from django.utils.module_loading import import_string from django.utils.six.moves.urllib.parse import urljoin from django.utils.text import get_valid_filename __all__ = ('Storage', 'FileSystemStorage', 'DefaultStorage', 'default_storage') class Storage(object): """ A base storage class, providing some default behaviors that all other storage systems can inherit or override, as necessary. """ # The following methods represent a public interface to private methods. # These shouldn't be overridden by subclasses unless absolutely necessary. def open(self, name, mode='rb'): """ Retrieves the specified file from storage. """ return self._open(name, mode) def save(self, name, content, max_length=None): """ Saves new content to the file specified by name. The content should be a proper File object or any python file-like object, ready to be read from the beginning. """ # Get the proper name for the file, as it will actually be saved. if name is None: name = content.name if not hasattr(content, 'chunks'): content = File(content) if func_supports_parameter(self.get_available_name, 'max_length'): name = self.get_available_name(name, max_length=max_length) else: warnings.warn( 'Backwards compatibility for storage backends without ' 'support for the `max_length` argument in ' 'Storage.get_available_name() will be removed in Django 1.10.', RemovedInDjango110Warning, stacklevel=2 ) name = self.get_available_name(name) name = self._save(name, content) # Store filenames with forward slashes, even on Windows return force_text(name.replace('\\', '/')) # These methods are part of the public API, with default implementations. def get_valid_name(self, name): """ Returns a filename, based on the provided filename, that's suitable for use in the target storage system. """ return get_valid_filename(name) def get_available_name(self, name, max_length=None): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ dir_name, file_name = os.path.split(name) file_root, file_ext = os.path.splitext(file_name) # If the filename already exists, add an underscore and a random 7 # character alphanumeric string (before the file extension, if one # exists) to the filename until the generated filename doesn't exist. # Truncate original name if required, so the new filename does not # exceed the max_length. while self.exists(name) or (max_length and len(name) > max_length): # file_ext includes the dot. name = os.path.join(dir_name, "%s_%s%s" % (file_root, get_random_string(7), file_ext)) if max_length is None: continue # Truncate file_root if max_length exceeded. truncation = len(name) - max_length if truncation > 0: file_root = file_root[:-truncation] # Entire file_root was truncated in attempt to find an available filename. if not file_root: raise SuspiciousFileOperation( 'Storage can not find an available filename for "%s". ' 'Please make sure that the corresponding file field ' 'allows sufficient "max_length".' % name ) name = os.path.join(dir_name, "%s_%s%s" % (file_root, get_random_string(7), file_ext)) return name def path(self, name): """ Returns a local filesystem path where the file can be retrieved using Python's built-in open() function. Storage systems that can't be accessed using open() should *not* implement this method. """ raise NotImplementedError("This backend doesn't support absolute paths.") # The following methods form the public API for storage systems, but with # no default implementations. Subclasses must implement *all* of these. def delete(self, name): """ Deletes the specified file from the storage system. """ raise NotImplementedError('subclasses of Storage must provide a delete() method') def exists(self, name): """ Returns True if a file referenced by the given name already exists in the storage system, or False if the name is available for a new file. """ raise NotImplementedError('subclasses of Storage must provide an exists() method') def listdir(self, path): """ Lists the contents of the specified path, returning a 2-tuple of lists; the first item being directories, the second item being files. """ raise NotImplementedError('subclasses of Storage must provide a listdir() method') def size(self, name): """ Returns the total size, in bytes, of the file specified by name. """ raise NotImplementedError('subclasses of Storage must provide a size() method') def url(self, name): """ Returns an absolute URL where the file's contents can be accessed directly by a Web browser. """ raise NotImplementedError('subclasses of Storage must provide a url() method') def accessed_time(self, name): """ Returns the last accessed time (as datetime object) of the file specified by name. """ raise NotImplementedError('subclasses of Storage must provide an accessed_time() method') def created_time(self, name): """ Returns the creation time (as datetime object) of the file specified by name. """ raise NotImplementedError('subclasses of Storage must provide a created_time() method') def modified_time(self, name): """ Returns the last modified time (as datetime object) of the file specified by name. """ raise NotImplementedError('subclasses of Storage must provide a modified_time() method') @deconstructible class FileSystemStorage(Storage): """ Standard filesystem storage """ def __init__(self, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None): if location is None: location = settings.MEDIA_ROOT self.base_location = location self.location = abspathu(self.base_location) if base_url is None: base_url = settings.MEDIA_URL elif not base_url.endswith('/'): base_url += '/' self.base_url = base_url self.file_permissions_mode = ( file_permissions_mode if file_permissions_mode is not None else settings.FILE_UPLOAD_PERMISSIONS ) self.directory_permissions_mode = ( directory_permissions_mode if directory_permissions_mode is not None else settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS ) def _open(self, name, mode='rb'): return File(open(self.path(name), mode)) def _save(self, name, content): full_path = self.path(name) # Create any intermediate directories that do not exist. # Note that there is a race between os.path.exists and os.makedirs: # if os.makedirs fails with EEXIST, the directory was created # concurrently, and we can continue normally. Refs #16082. directory = os.path.dirname(full_path) if not os.path.exists(directory): try: if self.directory_permissions_mode is not None: # os.makedirs applies the global umask, so we reset it, # for consistency with file_permissions_mode behavior. old_umask = os.umask(0) try: os.makedirs(directory, self.directory_permissions_mode) finally: os.umask(old_umask) else: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise if not os.path.isdir(directory): raise IOError("%s exists and is not a directory." % directory) # There's a potential race condition between get_available_name and # saving the file; it's possible that two threads might return the # same name, at which point all sorts of fun happens. So we need to # try to create the file, but if it already exists we have to go back # to get_available_name() and try again. while True: try: # This file has a file path that we can move. if hasattr(content, 'temporary_file_path'): file_move_safe(content.temporary_file_path(), full_path) # This is a normal uploadedfile that we can stream. else: # This fun binary flag incantation makes os.open throw an # OSError if the file already exists before we open it. flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_BINARY', 0)) # The current umask value is masked out by os.open! fd = os.open(full_path, flags, 0o666) _file = None try: locks.lock(fd, locks.LOCK_EX) for chunk in content.chunks(): if _file is None: mode = 'wb' if isinstance(chunk, bytes) else 'wt' _file = os.fdopen(fd, mode) _file.write(chunk) finally: locks.unlock(fd) if _file is not None: _file.close() else: os.close(fd) except OSError as e: if e.errno == errno.EEXIST: # Ooops, the file exists. We need a new file name. name = self.get_available_name(name) full_path = self.path(name) else: raise else: # OK, the file save worked. Break out of the loop. break if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) return name def delete(self, name): assert name, "The name argument is not allowed to be empty." name = self.path(name) # If the file exists, delete it from the filesystem. # Note that there is a race between os.path.exists and os.remove: # if os.remove fails with ENOENT, the file was removed # concurrently, and we can continue normally. if os.path.exists(name): try: os.remove(name) except OSError as e: if e.errno != errno.ENOENT: raise def exists(self, name): return os.path.exists(self.path(name)) def listdir(self, path): path = self.path(path) directories, files = [], [] for entry in os.listdir(path): if os.path.isdir(os.path.join(path, entry)): directories.append(entry) else: files.append(entry) return directories, files def path(self, name): return safe_join(self.location, name) def size(self, name): return os.path.getsize(self.path(name)) def url(self, name): if self.base_url is None: raise ValueError("This file is not accessible via a URL.") return urljoin(self.base_url, filepath_to_uri(name)) def accessed_time(self, name): return datetime.fromtimestamp(os.path.getatime(self.path(name))) def created_time(self, name): return datetime.fromtimestamp(os.path.getctime(self.path(name))) def modified_time(self, name): return datetime.fromtimestamp(os.path.getmtime(self.path(name))) def get_storage_class(import_path=None): return import_string(import_path or settings.DEFAULT_FILE_STORAGE) class DefaultStorage(LazyObject): def _setup(self): self._wrapped = get_storage_class()() default_storage = DefaultStorage()
bsd-3-clause
BehavioralInsightsTeam/edx-platform
common/djangoapps/entitlements/api/v1/filters.py
18
1215
from django_filters import rest_framework as filters from entitlements.models import CourseEntitlement class CharListFilter(filters.CharFilter): """ Filters a field via a comma-delimited list of values. """ def filter(self, qs, value): # pylint: disable=method-hidden if value not in (None, ''): value = value.split(',') return super(CharListFilter, self).filter(qs, value) class UUIDListFilter(CharListFilter): """ Filters a field via a comma-delimited list of UUIDs. """ def __init__(self, name='uuid', label=None, widget=None, method=None, lookup_expr='in', required=False, distinct=False, exclude=False, **kwargs): super(UUIDListFilter, self).__init__( name=name, label=label, widget=widget, method=method, lookup_expr=lookup_expr, required=required, distinct=distinct, exclude=exclude, **kwargs ) class CourseEntitlementFilter(filters.FilterSet): uuid = UUIDListFilter() user = filters.CharFilter(name='user__username') class Meta: model = CourseEntitlement fields = ('uuid', 'user')
agpl-3.0
alekz112/statsmodels
statsmodels/formula/tests/test_formula.py
29
4647
from statsmodels.compat.python import iteritems, StringIO import warnings from statsmodels.formula.api import ols from statsmodels.formula.formulatools import make_hypotheses_matrices from statsmodels.tools import add_constant from statsmodels.datasets.longley import load, load_pandas import numpy.testing as npt from statsmodels.tools.testing import assert_equal from numpy.testing.utils import WarningManager longley_formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' class CheckFormulaOLS(object): @classmethod def setupClass(cls): cls.data = load() def test_endog_names(self): assert self.model.endog_names == 'TOTEMP' def test_exog_names(self): assert self.model.exog_names == ['Intercept', 'GNPDEFL', 'GNP', 'UNEMP', 'ARMED', 'POP', 'YEAR'] def test_design(self): npt.assert_equal(self.model.exog, add_constant(self.data.exog, prepend=True)) def test_endog(self): npt.assert_equal(self.model.endog, self.data.endog) def test_summary(self): # smoke test warn_ctx = WarningManager() warn_ctx.__enter__() try: warnings.filterwarnings("ignore", "kurtosistest only valid for n>=20") self.model.fit().summary() finally: warn_ctx.__exit__() class TestFormulaPandas(CheckFormulaOLS): @classmethod def setupClass(cls): data = load_pandas().data cls.model = ols(longley_formula, data) super(TestFormulaPandas, cls).setupClass() class TestFormulaDict(CheckFormulaOLS): @classmethod def setupClass(cls): data = dict((k, v.tolist()) for k, v in iteritems(load_pandas().data)) cls.model = ols(longley_formula, data) super(TestFormulaDict, cls).setupClass() class TestFormulaRecArray(CheckFormulaOLS): @classmethod def setupClass(cls): data = load().data cls.model = ols(longley_formula, data) super(TestFormulaRecArray, cls).setupClass() def test_tests(): formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' dta = load_pandas().data results = ols(formula, dta).fit() test_formula = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' LC = make_hypotheses_matrices(results, test_formula) R = LC.coefs Q = LC.constants npt.assert_almost_equal(R, [[0, 1, -1, 0, 0, 0, 0], [0, 0 , 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1./1829]], 8) npt.assert_array_equal(Q, [[0],[2],[1]]) def test_formula_labels(): # make sure labels pass through patsy as expected # data(Duncan) from car in R dta = StringIO(""""type" "income" "education" "prestige"\n"accountant" "prof" 62 86 82\n"pilot" "prof" 72 76 83\n"architect" "prof" 75 92 90\n"author" "prof" 55 90 76\n"chemist" "prof" 64 86 90\n"minister" "prof" 21 84 87\n"professor" "prof" 64 93 93\n"dentist" "prof" 80 100 90\n"reporter" "wc" 67 87 52\n"engineer" "prof" 72 86 88\n"undertaker" "prof" 42 74 57\n"lawyer" "prof" 76 98 89\n"physician" "prof" 76 97 97\n"welfare.worker" "prof" 41 84 59\n"teacher" "prof" 48 91 73\n"conductor" "wc" 76 34 38\n"contractor" "prof" 53 45 76\n"factory.owner" "prof" 60 56 81\n"store.manager" "prof" 42 44 45\n"banker" "prof" 78 82 92\n"bookkeeper" "wc" 29 72 39\n"mail.carrier" "wc" 48 55 34\n"insurance.agent" "wc" 55 71 41\n"store.clerk" "wc" 29 50 16\n"carpenter" "bc" 21 23 33\n"electrician" "bc" 47 39 53\n"RR.engineer" "bc" 81 28 67\n"machinist" "bc" 36 32 57\n"auto.repairman" "bc" 22 22 26\n"plumber" "bc" 44 25 29\n"gas.stn.attendant" "bc" 15 29 10\n"coal.miner" "bc" 7 7 15\n"streetcar.motorman" "bc" 42 26 19\n"taxi.driver" "bc" 9 19 10\n"truck.driver" "bc" 21 15 13\n"machine.operator" "bc" 21 20 24\n"barber" "bc" 16 26 20\n"bartender" "bc" 16 28 7\n"shoe.shiner" "bc" 9 17 3\n"cook" "bc" 14 22 16\n"soda.clerk" "bc" 12 30 6\n"watchman" "bc" 17 25 11\n"janitor" "bc" 7 20 8\n"policeman" "bc" 34 47 41\n"waiter" "bc" 8 32 10""") from pandas import read_table dta = read_table(dta, sep=" ") model = ols("prestige ~ income + education", dta).fit() assert_equal(model.fittedvalues.index, dta.index) def test_formula_predict(): from numpy import log formula = """TOTEMP ~ log(GNPDEFL) + log(GNP) + UNEMP + ARMED + POP + YEAR""" data = load_pandas() dta = load_pandas().data results = ols(formula, dta).fit() npt.assert_almost_equal(results.fittedvalues.values, results.predict(data.exog), 8)
bsd-3-clause
jclc/discus-inferno
flaskenv/lib/python2.7/site-packages/pip/_vendor/requests/models.py
217
25372
# -*- coding: utf-8 -*- """ requests.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power Requests. """ import collections import logging import datetime from io import BytesIO, UnsupportedOperation from .hooks import default_hooks from .structures import CaseInsensitiveDict from .auth import HTTPBasicAuth from .cookies import cookiejar_from_dict, get_cookie_header from .packages.urllib3.fields import RequestField from .packages.urllib3.filepost import encode_multipart_formdata from .packages.urllib3.util import parse_url from .packages.urllib3.exceptions import DecodeError from .exceptions import ( HTTPError, RequestException, MissingSchema, InvalidURL, ChunkedEncodingError, ContentDecodingError) from .utils import ( guess_filename, get_auth_from_url, requote_uri, stream_decode_response_unicode, to_key_val_list, parse_header_links, iter_slices, guess_json_utf, super_len, to_native_string) from .compat import ( cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO, is_py2, chardet, json, builtin_str, basestring, IncompleteRead) CONTENT_CHUNK_SIZE = 10 * 1024 ITER_CHUNK_SIZE = 512 log = logging.getLogger(__name__) class RequestEncodingMixin(object): @property def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url) @staticmethod def _encode_params(data): """Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if isinstance(data, (str, bytes)): return data elif hasattr(data, 'read'): return data elif hasattr(data, '__iter__'): result = [] for k, vs in to_key_val_list(data): if isinstance(vs, basestring) or not hasattr(vs, '__iter__'): vs = [vs] for v in vs: if v is not None: result.append( (k.encode('utf-8') if isinstance(k, str) else k, v.encode('utf-8') if isinstance(v, str) else v)) return urlencode(result, doseq=True) else: return data @staticmethod def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if (not files): raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, '__iter__'): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( (field.decode('utf-8') if isinstance(field, bytes) else field, v.encode('utf-8') if isinstance(v, str) else v)) for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, str): fp = StringIO(fp) if isinstance(fp, bytes): fp = BytesIO(fp) rf = RequestField(name=k, data=fp.read(), filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type class RequestHooksMixin(object): def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks: raise ValueError('Unsupported event specified, with event name "%s"' % (event)) if isinstance(hook, collections.Callable): self.hooks[event].append(hook) elif hasattr(hook, '__iter__'): self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False class Request(RequestHooksMixin): """A user-created :class:`Request <Request>` object. Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server. :param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach the request. If a dictionary is provided, form-encoding will take place. :param params: dictionary of URL parameters to append to the URL. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage. Usage:: >>> import requests >>> req = requests.Request('GET', 'http://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]> """ def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None): # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.params = params self.auth = auth self.cookies = cookies def __repr__(self): return '<Request [%s]>' % (self.method) def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): """The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server. Generated from either a :class:`Request <Request>` object or manually. Usage:: >>> import requests >>> req = requests.Request('GET', 'http://httpbin.org/get') >>> r = req.prepare() <PreparedRequest [GET]> >>> s = requests.Session() >>> s.send(r) <Response [200]> """ def __init__(self): #: HTTP verb to send to the server. self.method = None #: HTTP URL to send the request to. self.url = None #: dictionary of HTTP headers. self.headers = None # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called self._cookies = None #: request body to send to the server. self.body = None #: dictionary of callback hooks, for internal usage. self.hooks = default_hooks() def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None): """Prepares the entire request with the given parameters.""" self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks) def __repr__(self): return '<PreparedRequest [%s]>' % (self.method) def copy(self): p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() p._cookies = self._cookies.copy() p.body = self.body p.hooks = self.hooks return p def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = self.method.upper() def prepare_url(self, url, params): """Prepares the given HTTP URL.""" #: Accept objects that have string representations. try: url = unicode(url) except NameError: # We're on Python 3. url = str(url) except UnicodeDecodeError: pass # Don't do any URL preparation for oddball schemes if ':' in url and not url.lower().startswith('http'): self.url = url return # Support for unicode domain names and paths. scheme, auth, host, port, path, query, fragment = parse_url(url) if not scheme: raise MissingSchema("Invalid URL {0!r}: No schema supplied. " "Perhaps you meant http://{0}?".format(url)) if not host: raise InvalidURL("Invalid URL %r: No host supplied" % url) # Only want to apply IDNA to the hostname try: host = host.encode('idna').decode('utf-8') except UnicodeError: raise InvalidURL('URL has an invalid label.') # Carefully reconstruct the network location netloc = auth or '' if netloc: netloc += '@' netloc += host if port: netloc += ':' + str(port) # Bare domains aren't valid URLs. if not path: path = '/' if is_py2: if isinstance(scheme, str): scheme = scheme.encode('utf-8') if isinstance(netloc, str): netloc = netloc.encode('utf-8') if isinstance(path, str): path = path.encode('utf-8') if isinstance(query, str): query = query.encode('utf-8') if isinstance(fragment, str): fragment = fragment.encode('utf-8') enc_params = self._encode_params(params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url def prepare_headers(self, headers): """Prepares the given HTTP headers.""" if headers: self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items()) else: self.headers = CaseInsensitiveDict() def prepare_body(self, data, files): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None length = None is_stream = all([ hasattr(data, '__iter__'), not isinstance(data, basestring), not isinstance(data, list), not isinstance(data, dict) ]) try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None if is_stream: body = data if files: raise NotImplementedError('Streamed bodies and files are mutually exclusive.') if length is not None: self.headers['Content-Length'] = builtin_str(length) else: self.headers['Transfer-Encoding'] = 'chunked' else: # Multi-part file uploads. if files: (body, content_type) = self._encode_files(files, data) else: if data: body = self._encode_params(data) if isinstance(data, str) or isinstance(data, builtin_str) or hasattr(data, 'read'): content_type = None else: content_type = 'application/x-www-form-urlencoded' self.prepare_content_length(body) # Add content-type if it wasn't explicitly provided. if (content_type) and (not 'content-type' in self.headers): self.headers['Content-Type'] = content_type self.body = body def prepare_content_length(self, body): if hasattr(body, 'seek') and hasattr(body, 'tell'): body.seek(0, 2) self.headers['Content-Length'] = builtin_str(body.tell()) body.seek(0, 0) elif body is not None: l = super_len(body) if l: self.headers['Content-Length'] = builtin_str(l) elif self.method not in ('GET', 'HEAD'): self.headers['Content-Length'] = '0' def prepare_auth(self, auth, url=''): """Prepares the given HTTP auth data.""" # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = HTTPBasicAuth(*auth) # Allow auth to make its changes. r = auth(self) # Update self to reflect the auth changes. self.__dict__.update(r.__dict__) # Recompute Content-Length self.prepare_content_length(self.body) def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data.""" if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers['Cookie'] = cookie_header def prepare_hooks(self, hooks): """Prepares the given hooks.""" for event in hooks: self.register_hook(event, hooks[event]) class Response(object): """The :class:`Response <Response>` object, which contains a server's response to an HTTP request. """ __attrs__ = [ '_content', 'status_code', 'headers', 'url', 'history', 'encoding', 'reason', 'cookies', 'elapsed', 'request', ] def __init__(self): super(Response, self).__init__() self._content = False self._content_consumed = False #: Integer Code of responded HTTP Status. self.status_code = None #: Case-insensitive Dictionary of Response Headers. #: For example, ``headers['content-encoding']`` will return the #: value of a ``'Content-Encoding'`` response header. self.headers = CaseInsensitiveDict() #: File-like object representation of response (for advanced usage). #: Use of ``raw`` requires that ``stream=True`` be set on the request. # This requirement does not apply for use internally to Requests. self.raw = None #: Final URL location of Response. self.url = None #: Encoding to decode with when accessing r.text. self.encoding = None #: A list of :class:`Response <Response>` objects from #: the history of the Request. Any redirect responses will end #: up here. The list is sorted from the oldest to the most recent request. self.history = [] self.reason = None #: A CookieJar of Cookies the server sent back. self.cookies = cookiejar_from_dict({}) #: The amount of time elapsed between sending the request #: and the arrival of the response (as a timedelta) self.elapsed = datetime.timedelta(0) def __getstate__(self): # Consume everything; accessing the content attribute makes # sure the content has been fully read. if not self._content_consumed: self.content return dict( (attr, getattr(self, attr, None)) for attr in self.__attrs__ ) def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) # pickled objects do not have .raw setattr(self, '_content_consumed', True) def __repr__(self): return '<Response [%s]>' % (self.status_code) def __bool__(self): """Returns true if :attr:`status_code` is 'OK'.""" return self.ok def __nonzero__(self): """Returns true if :attr:`status_code` is 'OK'.""" return self.ok def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128) @property def ok(self): try: self.raise_for_status() except RequestException: return False return True @property def apparent_encoding(self): """The apparent encoding, provided by the lovely Charade library (Thanks, Ian!).""" return chardet.detect(self.content)['encoding'] def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. """ if self._content_consumed: # simulate reading small chunks of the content return iter_slices(self._content, chunk_size) def generate(): try: # Special case for urllib3. try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except IncompleteRead as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except AttributeError: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True gen = generate() if decode_unicode: gen = stream_decode_response_unicode(gen, self) return gen def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. """ pending = None for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending @property def content(self): """Content of the response, in bytes.""" if self._content is False: # Read the contents. try: if self._content_consumed: raise RuntimeError( 'The content for this response was already consumed') if self.status_code == 0: self._content = None else: self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes() except AttributeError: self._content = None self._content_consumed = True # don't need to release the connection; that's been handled by urllib3 # since we exhausted the data. return self._content @property def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based soley on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. """ # Try charset from content-type content = None encoding = self.encoding if not self.content: return str('') # Fallback to auto-detected encoding. if self.encoding is None: encoding = self.apparent_encoding # Decode unicode from given encoding. try: content = str(self.content, encoding, errors='replace') except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors='replace') return content def json(self, **kwargs): """Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: return json.loads(self.content.decode(encoding), **kwargs) return json.loads(self.text, **kwargs) @property def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get('link') # l = MultiDict() l = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.get('url') l[key] = link return l def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if 400 <= self.status_code < 500: http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason) elif 500 <= self.status_code < 600: http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason) if http_error_msg: raise HTTPError(http_error_msg, response=self) def close(self): """Closes the underlying file descriptor and releases the connection back to the pool. *Note: Should not normally need to be called explicitly.* """ return self.raw.release_conn()
mit
alexteodor/odoo
addons/sale/sale.py
8
69136
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from datetime import datetime, timedelta import time from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT import openerp.addons.decimal_precision as dp from openerp import workflow class res_company(osv.Model): _inherit = "res.company" _columns = { 'sale_note': fields.text('Default Terms and Conditions', translate=True, help="Default terms and conditions for quotations."), } class sale_order(osv.osv): _name = "sale.order" _inherit = ['mail.thread', 'ir.needaction_mixin'] _description = "Sales Order" _track = { 'state': { 'sale.mt_order_confirmed': lambda self, cr, uid, obj, ctx=None: obj.state in ['manual'], 'sale.mt_order_sent': lambda self, cr, uid, obj, ctx=None: obj.state in ['sent'] }, } def _amount_line_tax(self, cr, uid, line, context=None): val = 0.0 for c in self.pool.get('account.tax').compute_all(cr, uid, line.tax_id, line.price_unit * (1-(line.discount or 0.0)/100.0), line.product_uom_qty, line.product_id, line.order_id.partner_id)['taxes']: val += c.get('amount', 0.0) return val def _amount_all_wrapper(self, cr, uid, ids, field_name, arg, context=None): """ Wrapper because of direct method passing as parameter for function fields """ return self._amount_all(cr, uid, ids, field_name, arg, context=context) def _amount_all(self, cr, uid, ids, field_name, arg, context=None): cur_obj = self.pool.get('res.currency') res = {} for order in self.browse(cr, uid, ids, context=context): res[order.id] = { 'amount_untaxed': 0.0, 'amount_tax': 0.0, 'amount_total': 0.0, } val = val1 = 0.0 cur = order.pricelist_id.currency_id for line in order.order_line: val1 += line.price_subtotal val += self._amount_line_tax(cr, uid, line, context=context) res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val) res[order.id]['amount_untaxed'] = cur_obj.round(cr, uid, cur, val1) res[order.id]['amount_total'] = res[order.id]['amount_untaxed'] + res[order.id]['amount_tax'] return res def _invoiced_rate(self, cursor, user, ids, name, arg, context=None): res = {} for sale in self.browse(cursor, user, ids, context=context): if sale.invoiced: res[sale.id] = 100.0 continue tot = 0.0 for invoice in sale.invoice_ids: if invoice.state not in ('draft', 'cancel'): tot += invoice.amount_untaxed if tot: res[sale.id] = min(100.0, tot * 100.0 / (sale.amount_untaxed or 1.00)) else: res[sale.id] = 0.0 return res def _invoice_exists(self, cursor, user, ids, name, arg, context=None): res = {} for sale in self.browse(cursor, user, ids, context=context): res[sale.id] = False if sale.invoice_ids: res[sale.id] = True return res def _invoiced(self, cursor, user, ids, name, arg, context=None): res = {} for sale in self.browse(cursor, user, ids, context=context): res[sale.id] = True invoice_existence = False for invoice in sale.invoice_ids: if invoice.state!='cancel': invoice_existence = True if invoice.state != 'paid': res[sale.id] = False break if not invoice_existence or sale.state == 'manual': res[sale.id] = False return res def _invoiced_search(self, cursor, user, obj, name, args, context=None): if not len(args): return [] clause = '' sale_clause = '' no_invoiced = False for arg in args: if (arg[1] == '=' and arg[2]) or (arg[1] == '!=' and not arg[2]): clause += 'AND inv.state = \'paid\'' else: clause += 'AND inv.state != \'cancel\' AND sale.state != \'cancel\' AND inv.state <> \'paid\' AND rel.order_id = sale.id ' sale_clause = ', sale_order AS sale ' no_invoiced = True cursor.execute('SELECT rel.order_id ' \ 'FROM sale_order_invoice_rel AS rel, account_invoice AS inv '+ sale_clause + \ 'WHERE rel.invoice_id = inv.id ' + clause) res = cursor.fetchall() if no_invoiced: cursor.execute('SELECT sale.id ' \ 'FROM sale_order AS sale ' \ 'WHERE sale.id NOT IN ' \ '(SELECT rel.order_id ' \ 'FROM sale_order_invoice_rel AS rel) and sale.state != \'cancel\'') res.extend(cursor.fetchall()) if not res: return [('id', '=', 0)] return [('id', 'in', [x[0] for x in res])] def _get_order(self, cr, uid, ids, context=None): result = {} for line in self.pool.get('sale.order.line').browse(cr, uid, ids, context=context): result[line.order_id.id] = True return result.keys() def _get_default_company(self, cr, uid, context=None): company_id = self.pool.get('res.users')._get_company(cr, uid, context=context) if not company_id: raise osv.except_osv(_('Error!'), _('There is no default company for the current user!')) return company_id def _get_default_section_id(self, cr, uid, context=None): """ Gives default section by checking if present in the context """ section_id = self._resolve_section_id_from_context(cr, uid, context=context) or False if not section_id: section_id = self.pool.get('res.users').browse(cr, uid, uid, context).default_section_id.id or False return section_id def _resolve_section_id_from_context(self, cr, uid, context=None): """ Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team. """ if context is None: context = {} if type(context.get('default_section_id')) in (int, long): return context.get('default_section_id') if isinstance(context.get('default_section_id'), basestring): section_ids = self.pool.get('crm.case.section').name_search(cr, uid, name=context['default_section_id'], context=context) if len(section_ids) == 1: return int(section_ids[0][0]) return None _columns = { 'name': fields.char('Order Reference', required=True, copy=False, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, select=True), 'origin': fields.char('Source Document', help="Reference of the document that generated this sales order request."), 'client_order_ref': fields.char('Reference/Description', copy=False), 'state': fields.selection([ ('draft', 'Draft Quotation'), ('sent', 'Quotation Sent'), ('cancel', 'Cancelled'), ('waiting_date', 'Waiting Schedule'), ('progress', 'Sales Order'), ('manual', 'Sale to Invoice'), ('shipping_except', 'Shipping Exception'), ('invoice_except', 'Invoice Exception'), ('done', 'Done'), ], 'Status', readonly=True, copy=False, help="Gives the status of the quotation or sales order.\ \nThe exception status is automatically set when a cancel operation occurs \ in the invoice validation (Invoice Exception) or in the picking list process (Shipping Exception).\nThe 'Waiting Schedule' status is set when the invoice is confirmed\ but waiting for the scheduler to run on the order date.", select=True), 'date_order': fields.datetime('Date', required=True, readonly=True, select=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=False), 'create_date': fields.datetime('Creation Date', readonly=True, select=True, help="Date on which sales order is created."), 'date_confirm': fields.date('Confirmation Date', readonly=True, select=True, help="Date on which sales order is confirmed.", copy=False), 'user_id': fields.many2one('res.users', 'Salesperson', states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, select=True, track_visibility='onchange'), 'partner_id': fields.many2one('res.partner', 'Customer', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, required=True, change_default=True, select=True, track_visibility='always'), 'partner_invoice_id': fields.many2one('res.partner', 'Invoice Address', readonly=True, required=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="Invoice address for current sales order."), 'partner_shipping_id': fields.many2one('res.partner', 'Delivery Address', readonly=True, required=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="Delivery address for current sales order."), 'order_policy': fields.selection([ ('manual', 'On Demand'), ], 'Create Invoice', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="""This field controls how invoice and delivery operations are synchronized."""), 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="Pricelist for current sales order."), 'currency_id': fields.related('pricelist_id', 'currency_id', type="many2one", relation="res.currency", string="Currency", readonly=True, required=True), 'project_id': fields.many2one('account.analytic.account', 'Contract / Analytic', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="The analytic account related to a sales order."), 'order_line': fields.one2many('sale.order.line', 'order_id', 'Order Lines', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=True), 'invoice_ids': fields.many2many('account.invoice', 'sale_order_invoice_rel', 'order_id', 'invoice_id', 'Invoices', readonly=True, copy=False, help="This is the list of invoices that have been generated for this sales order. The same sales order may have been invoiced in several times (by line for example)."), 'invoiced_rate': fields.function(_invoiced_rate, string='Invoiced Ratio', type='float'), 'invoiced': fields.function(_invoiced, string='Paid', fnct_search=_invoiced_search, type='boolean', help="It indicates that an invoice has been paid."), 'invoice_exists': fields.function(_invoice_exists, string='Invoiced', fnct_search=_invoiced_search, type='boolean', help="It indicates that sales order has at least one invoice."), 'note': fields.text('Terms and conditions'), 'amount_untaxed': fields.function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Untaxed Amount', store={ 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), }, multi='sums', help="The amount without tax.", track_visibility='always'), 'amount_tax': fields.function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Taxes', store={ 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), }, multi='sums', help="The tax amount."), 'amount_total': fields.function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Total', store={ 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), }, multi='sums', help="The total amount."), 'payment_term': fields.many2one('account.payment.term', 'Payment Term'), 'fiscal_position': fields.many2one('account.fiscal.position', 'Fiscal Position'), 'company_id': fields.many2one('res.company', 'Company'), 'section_id': fields.many2one('crm.case.section', 'Sales Team'), 'procurement_group_id': fields.many2one('procurement.group', 'Procurement group', copy=False), 'product_id': fields.related('order_line', 'product_id', type='many2one', relation='product.product', string='Product'), } _defaults = { 'date_order': fields.datetime.now, 'order_policy': 'manual', 'company_id': _get_default_company, 'state': 'draft', 'user_id': lambda obj, cr, uid, context: uid, 'name': lambda obj, cr, uid, context: '/', 'partner_invoice_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['invoice'])['invoice'], 'partner_shipping_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['delivery'])['delivery'], 'note': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.sale_note, 'section_id': lambda s, cr, uid, c: s._get_default_section_id(cr, uid, c), } _sql_constraints = [ ('name_uniq', 'unique(name, company_id)', 'Order Reference must be unique per Company!'), ] _order = 'date_order desc, id desc' # Form filling def unlink(self, cr, uid, ids, context=None): sale_orders = self.read(cr, uid, ids, ['state'], context=context) unlink_ids = [] for s in sale_orders: if s['state'] in ['draft', 'cancel']: unlink_ids.append(s['id']) else: raise osv.except_osv(_('Invalid Action!'), _('In order to delete a confirmed sales order, you must cancel it before!')) return osv.osv.unlink(self, cr, uid, unlink_ids, context=context) def copy_quotation(self, cr, uid, ids, context=None): id = self.copy(cr, uid, ids[0], context=context) view_ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'sale', 'view_order_form') view_id = view_ref and view_ref[1] or False, return { 'type': 'ir.actions.act_window', 'name': _('Sales Order'), 'res_model': 'sale.order', 'res_id': id, 'view_type': 'form', 'view_mode': 'form', 'view_id': view_id, 'target': 'current', 'nodestroy': True, } def onchange_pricelist_id(self, cr, uid, ids, pricelist_id, order_lines, context=None): context = context or {} if not pricelist_id: return {} value = { 'currency_id': self.pool.get('product.pricelist').browse(cr, uid, pricelist_id, context=context).currency_id.id } if not order_lines or order_lines == [(6, 0, [])]: return {'value': value} warning = { 'title': _('Pricelist Warning!'), 'message' : _('If you change the pricelist of this order (and eventually the currency), prices of existing order lines will not be updated.') } return {'warning': warning, 'value': value} def get_salenote(self, cr, uid, ids, partner_id, context=None): context_lang = context.copy() if partner_id: partner_lang = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context).lang context_lang.update({'lang': partner_lang}) return self.pool.get('res.users').browse(cr, uid, uid, context=context_lang).company_id.sale_note def onchange_delivery_id(self, cr, uid, ids, company_id, partner_id, delivery_id, fiscal_position, context=None): r = {'value': {}} if not fiscal_position: if not company_id: company_id = self._get_default_company(cr, uid, context=context) fiscal_position = self.pool['account.fiscal.position'].get_fiscal_position(cr, uid, company_id, partner_id, delivery_id, context=context) if fiscal_position: r['value']['fiscal_position'] = fiscal_position return r def onchange_partner_id(self, cr, uid, ids, part, context=None): if not part: return {'value': {'partner_invoice_id': False, 'partner_shipping_id': False, 'payment_term': False, 'fiscal_position': False}} part = self.pool.get('res.partner').browse(cr, uid, part, context=context) addr = self.pool.get('res.partner').address_get(cr, uid, [part.id], ['delivery', 'invoice', 'contact']) pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False payment_term = part.property_payment_term and part.property_payment_term.id or False dedicated_salesman = part.user_id and part.user_id.id or uid val = { 'partner_invoice_id': addr['invoice'], 'partner_shipping_id': addr['delivery'], 'payment_term': payment_term, 'user_id': dedicated_salesman, } delivery_onchange = self.onchange_delivery_id(cr, uid, ids, False, part.id, addr['delivery'], False, context=context) val.update(delivery_onchange['value']) if pricelist: val['pricelist_id'] = pricelist sale_note = self.get_salenote(cr, uid, ids, part.id, context=context) if sale_note: val.update({'note': sale_note}) return {'value': val} def create(self, cr, uid, vals, context=None): if context is None: context = {} if vals.get('name', '/') == '/': vals['name'] = self.pool.get('ir.sequence').get(cr, uid, 'sale.order') or '/' if vals.get('partner_id') and any(f not in vals for f in ['partner_invoice_id', 'partner_shipping_id', 'pricelist_id', 'fiscal_position']): defaults = self.onchange_partner_id(cr, uid, [], vals['partner_id'], context=context)['value'] if not vals.get('fiscal_position') and vals.get('partner_shipping_id'): delivery_onchange = self.onchange_delivery_id(cr, uid, [], vals.get('company_id'), None, vals['partner_id'], vals.get('partner_shipping_id'), context=context) defaults.update(delivery_onchange['value']) vals = dict(defaults, **vals) ctx = dict(context or {}, mail_create_nolog=True) new_id = super(sale_order, self).create(cr, uid, vals, context=ctx) self.message_post(cr, uid, [new_id], body=_("Quotation created"), context=ctx) return new_id def button_dummy(self, cr, uid, ids, context=None): return True # FIXME: deprecated method, overriders should be using _prepare_invoice() instead. # can be removed after 6.1. def _inv_get(self, cr, uid, order, context=None): return {} def _prepare_invoice(self, cr, uid, order, lines, context=None): """Prepare the dict of values to create the new invoice for a sales order. This method may be overridden to implement custom invoice generation (making sure to call super() to establish a clean extension chain). :param browse_record order: sale.order record to invoice :param list(int) line: list of invoice line IDs that must be attached to the invoice :return: dict of value to create() the invoice """ if context is None: context = {} journal_ids = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'sale'), ('company_id', '=', order.company_id.id)], limit=1) if not journal_ids: raise osv.except_osv(_('Error!'), _('Please define sales journal for this company: "%s" (id:%d).') % (order.company_id.name, order.company_id.id)) invoice_vals = { 'name': order.client_order_ref or '', 'origin': order.name, 'type': 'out_invoice', 'reference': order.client_order_ref or order.name, 'account_id': order.partner_id.property_account_receivable.id, 'partner_id': order.partner_invoice_id.id, 'journal_id': journal_ids[0], 'invoice_line': [(6, 0, lines)], 'currency_id': order.pricelist_id.currency_id.id, 'comment': order.note, 'payment_term': order.payment_term and order.payment_term.id or False, 'fiscal_position': order.fiscal_position.id or order.partner_id.property_account_position.id, 'date_invoice': context.get('date_invoice', False), 'company_id': order.company_id.id, 'user_id': order.user_id and order.user_id.id or False, 'section_id' : order.section_id.id } # Care for deprecated _inv_get() hook - FIXME: to be removed after 6.1 invoice_vals.update(self._inv_get(cr, uid, order, context=context)) return invoice_vals def _make_invoice(self, cr, uid, order, lines, context=None): inv_obj = self.pool.get('account.invoice') obj_invoice_line = self.pool.get('account.invoice.line') if context is None: context = {} invoiced_sale_line_ids = self.pool.get('sale.order.line').search(cr, uid, [('order_id', '=', order.id), ('invoiced', '=', True)], context=context) from_line_invoice_ids = [] for invoiced_sale_line_id in self.pool.get('sale.order.line').browse(cr, uid, invoiced_sale_line_ids, context=context): for invoice_line_id in invoiced_sale_line_id.invoice_lines: if invoice_line_id.invoice_id.id not in from_line_invoice_ids: from_line_invoice_ids.append(invoice_line_id.invoice_id.id) for preinv in order.invoice_ids: if preinv.state not in ('cancel',) and preinv.id not in from_line_invoice_ids: for preline in preinv.invoice_line: inv_line_id = obj_invoice_line.copy(cr, uid, preline.id, {'invoice_id': False, 'price_unit': -preline.price_unit}) lines.append(inv_line_id) inv = self._prepare_invoice(cr, uid, order, lines, context=context) inv_id = inv_obj.create(cr, uid, inv, context=context) data = inv_obj.onchange_payment_term_date_invoice(cr, uid, [inv_id], inv['payment_term'], time.strftime(DEFAULT_SERVER_DATE_FORMAT)) if data.get('value', False): inv_obj.write(cr, uid, [inv_id], data['value'], context=context) inv_obj.button_compute(cr, uid, [inv_id]) return inv_id def print_quotation(self, cr, uid, ids, context=None): ''' This function prints the sales order and mark it as sent, so that we can see more easily the next step of the workflow ''' assert len(ids) == 1, 'This option should only be used for a single id at a time' self.signal_workflow(cr, uid, ids, 'quotation_sent') return self.pool['report'].get_action(cr, uid, ids, 'sale.report_saleorder', context=context) def manual_invoice(self, cr, uid, ids, context=None): """ create invoices for the given sales orders (ids), and open the form view of one of the newly created invoices """ mod_obj = self.pool.get('ir.model.data') # create invoices through the sales orders' workflow inv_ids0 = set(inv.id for sale in self.browse(cr, uid, ids, context) for inv in sale.invoice_ids) self.signal_workflow(cr, uid, ids, 'manual_invoice') inv_ids1 = set(inv.id for sale in self.browse(cr, uid, ids, context) for inv in sale.invoice_ids) # determine newly created invoices new_inv_ids = list(inv_ids1 - inv_ids0) res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form') res_id = res and res[1] or False, return { 'name': _('Customer Invoices'), 'view_type': 'form', 'view_mode': 'form', 'view_id': [res_id], 'res_model': 'account.invoice', 'context': "{'type':'out_invoice'}", 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'current', 'res_id': new_inv_ids and new_inv_ids[0] or False, } def action_view_invoice(self, cr, uid, ids, context=None): ''' This function returns an action that display existing invoices of given sales order ids. It can either be a in a list or in a form view, if there is only one invoice to show. ''' mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') result = mod_obj.get_object_reference(cr, uid, 'account', 'action_invoice_tree1') id = result and result[1] or False result = act_obj.read(cr, uid, [id], context=context)[0] #compute the number of invoices to display inv_ids = [] for so in self.browse(cr, uid, ids, context=context): inv_ids += [invoice.id for invoice in so.invoice_ids] #choose the view_mode accordingly if len(inv_ids)>1: result['domain'] = "[('id','in',["+','.join(map(str, inv_ids))+"])]" else: res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form') result['views'] = [(res and res[1] or False, 'form')] result['res_id'] = inv_ids and inv_ids[0] or False return result def test_no_product(self, cr, uid, order, context): for line in order.order_line: if line.product_id and (line.product_id.type<>'service'): return False return True def action_invoice_create(self, cr, uid, ids, grouped=False, states=None, date_invoice = False, context=None): if states is None: states = ['confirmed', 'done', 'exception'] res = False invoices = {} invoice_ids = [] invoice = self.pool.get('account.invoice') obj_sale_order_line = self.pool.get('sale.order.line') partner_currency = {} # If date was specified, use it as date invoiced, usefull when invoices are generated this month and put the # last day of the last month as invoice date if date_invoice: context = dict(context or {}, date_invoice=date_invoice) for o in self.browse(cr, uid, ids, context=context): currency_id = o.pricelist_id.currency_id.id if (o.partner_id.id in partner_currency) and (partner_currency[o.partner_id.id] <> currency_id): raise osv.except_osv( _('Error!'), _('You cannot group sales having different currencies for the same partner.')) partner_currency[o.partner_id.id] = currency_id lines = [] for line in o.order_line: if line.invoiced: continue elif (line.state in states): lines.append(line.id) created_lines = obj_sale_order_line.invoice_line_create(cr, uid, lines) if created_lines: invoices.setdefault(o.partner_invoice_id.id or o.partner_id.id, []).append((o, created_lines)) if not invoices: for o in self.browse(cr, uid, ids, context=context): for i in o.invoice_ids: if i.state == 'draft': return i.id for val in invoices.values(): if grouped: res = self._make_invoice(cr, uid, val[0][0], reduce(lambda x, y: x + y, [l for o, l in val], []), context=context) invoice_ref = '' origin_ref = '' for o, l in val: invoice_ref += (o.client_order_ref or o.name) + '|' origin_ref += (o.origin or o.name) + '|' self.write(cr, uid, [o.id], {'state': 'progress'}) cr.execute('insert into sale_order_invoice_rel (order_id,invoice_id) values (%s,%s)', (o.id, res)) self.invalidate_cache(cr, uid, ['invoice_ids'], [o.id], context=context) #remove last '|' in invoice_ref if len(invoice_ref) >= 1: invoice_ref = invoice_ref[:-1] if len(origin_ref) >= 1: origin_ref = origin_ref[:-1] invoice.write(cr, uid, [res], {'origin': origin_ref, 'name': invoice_ref}) else: for order, il in val: res = self._make_invoice(cr, uid, order, il, context=context) invoice_ids.append(res) self.write(cr, uid, [order.id], {'state': 'progress'}) cr.execute('insert into sale_order_invoice_rel (order_id,invoice_id) values (%s,%s)', (order.id, res)) self.invalidate_cache(cr, uid, ['invoice_ids'], [order.id], context=context) return res def action_invoice_cancel(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'invoice_except'}, context=context) return True def action_invoice_end(self, cr, uid, ids, context=None): for this in self.browse(cr, uid, ids, context=context): for line in this.order_line: if line.state == 'exception': line.write({'state': 'confirmed'}) if this.state == 'invoice_except': this.write({'state': 'progress'}) return True def action_cancel(self, cr, uid, ids, context=None): if context is None: context = {} sale_order_line_obj = self.pool.get('sale.order.line') account_invoice_obj = self.pool.get('account.invoice') for sale in self.browse(cr, uid, ids, context=context): for inv in sale.invoice_ids: if inv.state not in ('draft', 'cancel'): raise osv.except_osv( _('Cannot cancel this sales order!'), _('First cancel all invoices attached to this sales order.')) inv.signal_workflow('invoice_cancel') sale_order_line_obj.write(cr, uid, [l.id for l in sale.order_line], {'state': 'cancel'}) self.write(cr, uid, ids, {'state': 'cancel'}) return True def action_button_confirm(self, cr, uid, ids, context=None): assert len(ids) == 1, 'This option should only be used for a single id at a time.' self.signal_workflow(cr, uid, ids, 'order_confirm') return True def action_wait(self, cr, uid, ids, context=None): context = context or {} for o in self.browse(cr, uid, ids): if not o.order_line: raise osv.except_osv(_('Error!'),_('You cannot confirm a sales order which has no line.')) noprod = self.test_no_product(cr, uid, o, context) if (o.order_policy == 'manual') or noprod: self.write(cr, uid, [o.id], {'state': 'manual', 'date_confirm': fields.date.context_today(self, cr, uid, context=context)}) else: self.write(cr, uid, [o.id], {'state': 'progress', 'date_confirm': fields.date.context_today(self, cr, uid, context=context)}) self.pool.get('sale.order.line').button_confirm(cr, uid, [x.id for x in o.order_line]) return True def action_quotation_send(self, cr, uid, ids, context=None): ''' This function opens a window to compose an email, with the edi sale template message loaded by default ''' assert len(ids) == 1, 'This option should only be used for a single id at a time.' ir_model_data = self.pool.get('ir.model.data') try: template_id = ir_model_data.get_object_reference(cr, uid, 'sale', 'email_template_edi_sale')[1] except ValueError: template_id = False try: compose_form_id = ir_model_data.get_object_reference(cr, uid, 'mail', 'email_compose_message_wizard_form')[1] except ValueError: compose_form_id = False ctx = dict() ctx.update({ 'default_model': 'sale.order', 'default_res_id': ids[0], 'default_use_template': bool(template_id), 'default_template_id': template_id, 'default_composition_mode': 'comment', 'mark_so_as_sent': True }) return { 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'mail.compose.message', 'views': [(compose_form_id, 'form')], 'view_id': compose_form_id, 'target': 'new', 'context': ctx, } def action_done(self, cr, uid, ids, context=None): for order in self.browse(cr, uid, ids, context=context): self.pool.get('sale.order.line').write(cr, uid, [line.id for line in order.order_line], {'state': 'done'}, context=context) return self.write(cr, uid, ids, {'state': 'done'}, context=context) def _prepare_order_line_procurement(self, cr, uid, order, line, group_id=False, context=None): date_planned = self._get_date_planned(cr, uid, order, line, order.date_order, context=context) return { 'name': line.name, 'origin': order.name, 'date_planned': date_planned, 'product_id': line.product_id.id, 'product_qty': line.product_uom_qty, 'product_uom': line.product_uom.id, 'product_uos_qty': (line.product_uos and line.product_uos_qty) or line.product_uom_qty, 'product_uos': (line.product_uos and line.product_uos.id) or line.product_uom.id, 'company_id': order.company_id.id, 'group_id': group_id, 'invoice_state': (order.order_policy == 'picking') and '2binvoiced' or 'none', 'sale_line_id': line.id } def _get_date_planned(self, cr, uid, order, line, start_date, context=None): date_planned = datetime.strptime(start_date, DEFAULT_SERVER_DATETIME_FORMAT) + timedelta(days=line.delay or 0.0) return date_planned def _prepare_procurement_group(self, cr, uid, order, context=None): return {'name': order.name, 'partner_id': order.partner_shipping_id.id} def procurement_needed(self, cr, uid, ids, context=None): #when sale is installed only, there is no need to create procurements, that's only #further installed modules (sale_service, sale_stock) that will change this. sale_line_obj = self.pool.get('sale.order.line') res = [] for order in self.browse(cr, uid, ids, context=context): res.append(sale_line_obj.need_procurement(cr, uid, [line.id for line in order.order_line], context=context)) return any(res) def action_ignore_delivery_exception(self, cr, uid, ids, context=None): for sale_order in self.browse(cr, uid, ids, context=context): self.write(cr, uid, ids, {'state': 'progress' if sale_order.invoice_exists else 'manual'}, context=context) return True def action_ship_create(self, cr, uid, ids, context=None): """Create the required procurements to supply sales order lines, also connecting the procurements to appropriate stock moves in order to bring the goods to the sales order's requested location. :return: True """ procurement_obj = self.pool.get('procurement.order') sale_line_obj = self.pool.get('sale.order.line') for order in self.browse(cr, uid, ids, context=context): proc_ids = [] vals = self._prepare_procurement_group(cr, uid, order, context=context) if not order.procurement_group_id: group_id = self.pool.get("procurement.group").create(cr, uid, vals, context=context) order.write({'procurement_group_id': group_id}, context=context) for line in order.order_line: #Try to fix exception procurement (possible when after a shipping exception the user choose to recreate) if line.procurement_ids: #first check them to see if they are in exception or not (one of the related moves is cancelled) procurement_obj.check(cr, uid, [x.id for x in line.procurement_ids if x.state not in ['cancel', 'done']]) line.refresh() #run again procurement that are in exception in order to trigger another move proc_ids += [x.id for x in line.procurement_ids if x.state in ('exception', 'cancel')] elif sale_line_obj.need_procurement(cr, uid, [line.id], context=context): if (line.state == 'done') or not line.product_id: continue vals = self._prepare_order_line_procurement(cr, uid, order, line, group_id=group_id, context=context) proc_id = procurement_obj.create(cr, uid, vals, context=context) proc_ids.append(proc_id) #Confirm procurement order such that rules will be applied on it #note that the workflow normally ensure proc_ids isn't an empty list procurement_obj.run(cr, uid, proc_ids, context=context) #if shipping was in exception and the user choose to recreate the delivery order, write the new status of SO if order.state == 'shipping_except': val = {'state': 'progress', 'shipped': False} if (order.order_policy == 'manual'): for line in order.order_line: if (not line.invoiced) and (line.state not in ('cancel', 'draft')): val['state'] = 'manual' break order.write(val) return True def onchange_fiscal_position(self, cr, uid, ids, fiscal_position, order_lines, context=None): '''Update taxes of order lines for each line where a product is defined :param list ids: not used :param int fiscal_position: sale order fiscal position :param list order_lines: command list for one2many write method ''' order_line = [] fiscal_obj = self.pool.get('account.fiscal.position') product_obj = self.pool.get('product.product') line_obj = self.pool.get('sale.order.line') fpos = False if fiscal_position: fpos = fiscal_obj.browse(cr, uid, fiscal_position, context=context) for line in order_lines: # create (0, 0, { fields }) # update (1, ID, { fields }) if line[0] in [0, 1]: prod = None if line[2].get('product_id'): prod = product_obj.browse(cr, uid, line[2]['product_id'], context=context) elif line[1]: prod = line_obj.browse(cr, uid, line[1], context=context).product_id if prod and prod.taxes_id: line[2]['tax_id'] = [[6, 0, fiscal_obj.map_tax(cr, uid, fpos, prod.taxes_id)]] order_line.append(line) # link (4, ID) # link all (6, 0, IDS) elif line[0] in [4, 6]: line_ids = line[0] == 4 and [line[1]] or line[2] for line_id in line_ids: prod = line_obj.browse(cr, uid, line_id, context=context).product_id if prod and prod.taxes_id: order_line.append([1, line_id, {'tax_id': [[6, 0, fiscal_obj.map_tax(cr, uid, fpos, prod.taxes_id)]]}]) else: order_line.append([4, line_id]) else: order_line.append(line) return {'value': {'order_line': order_line}} def test_procurements_done(self, cr, uid, ids, context=None): for sale in self.browse(cr, uid, ids, context=context): for line in sale.order_line: if not all([x.state == 'done' for x in line.procurement_ids]): return False return True def test_procurements_except(self, cr, uid, ids, context=None): for sale in self.browse(cr, uid, ids, context=context): for line in sale.order_line: if any([x.state == 'cancel' for x in line.procurement_ids]): return True return False # TODO add a field price_unit_uos # - update it on change product and unit price # - use it in report if there is a uos class sale_order_line(osv.osv): def need_procurement(self, cr, uid, ids, context=None): #when sale is installed only, there is no need to create procurements, that's only #further installed modules (sale_service, sale_stock) that will change this. prod_obj = self.pool.get('product.product') for line in self.browse(cr, uid, ids, context=context): if prod_obj.need_procurement(cr, uid, [line.product_id.id], context=context): return True return False def _amount_line(self, cr, uid, ids, field_name, arg, context=None): tax_obj = self.pool.get('account.tax') cur_obj = self.pool.get('res.currency') res = {} if context is None: context = {} for line in self.browse(cr, uid, ids, context=context): price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) taxes = tax_obj.compute_all(cr, uid, line.tax_id, price, line.product_uom_qty, line.product_id, line.order_id.partner_id) cur = line.order_id.pricelist_id.currency_id res[line.id] = cur_obj.round(cr, uid, cur, taxes['total']) return res def _get_uom_id(self, cr, uid, *args): try: proxy = self.pool.get('ir.model.data') result = proxy.get_object_reference(cr, uid, 'product', 'product_uom_unit') return result[1] except Exception, ex: return False def _fnct_line_invoiced(self, cr, uid, ids, field_name, args, context=None): res = dict.fromkeys(ids, False) for this in self.browse(cr, uid, ids, context=context): res[this.id] = this.invoice_lines and \ all(iline.invoice_id.state != 'cancel' for iline in this.invoice_lines) return res def _order_lines_from_invoice(self, cr, uid, ids, context=None): # direct access to the m2m table is the less convoluted way to achieve this (and is ok ACL-wise) cr.execute("""SELECT DISTINCT sol.id FROM sale_order_invoice_rel rel JOIN sale_order_line sol ON (sol.order_id = rel.order_id) WHERE rel.invoice_id = ANY(%s)""", (list(ids),)) return [i[0] for i in cr.fetchall()] def _get_price_reduce(self, cr, uid, ids, field_name, arg, context=None): res = dict.fromkeys(ids, 0.0) for line in self.browse(cr, uid, ids, context=context): res[line.id] = line.price_subtotal / line.product_uom_qty return res _name = 'sale.order.line' _description = 'Sales Order Line' _columns = { 'order_id': fields.many2one('sale.order', 'Order Reference', required=True, ondelete='cascade', select=True, readonly=True, states={'draft':[('readonly',False)]}), 'name': fields.text('Description', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of sales order lines."), 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], change_default=True, readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict'), 'invoice_lines': fields.many2many('account.invoice.line', 'sale_order_line_invoice_rel', 'order_line_id', 'invoice_id', 'Invoice Lines', readonly=True, copy=False), 'invoiced': fields.function(_fnct_line_invoiced, string='Invoiced', type='boolean', store={ 'account.invoice': (_order_lines_from_invoice, ['state'], 10), 'sale.order.line': (lambda self,cr,uid,ids,ctx=None: ids, ['invoice_lines'], 10) }), 'price_unit': fields.float('Unit Price', required=True, digits_compute= dp.get_precision('Product Price'), readonly=True, states={'draft': [('readonly', False)]}), 'price_subtotal': fields.function(_amount_line, string='Subtotal', digits_compute= dp.get_precision('Account')), 'price_reduce': fields.function(_get_price_reduce, type='float', string='Price Reduce', digits_compute=dp.get_precision('Product Price')), 'tax_id': fields.many2many('account.tax', 'sale_order_tax', 'order_line_id', 'tax_id', 'Taxes', readonly=True, states={'draft': [('readonly', False)]}), 'address_allotment_id': fields.many2one('res.partner', 'Allotment Partner',help="A partner to whom the particular product needs to be allotted."), 'product_uom_qty': fields.float('Quantity', digits_compute= dp.get_precision('Product UoS'), required=True, readonly=True, states={'draft': [('readonly', False)]}), 'product_uom': fields.many2one('product.uom', 'Unit of Measure ', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'product_uos_qty': fields.float('Quantity (UoS)' ,digits_compute= dp.get_precision('Product UoS'), readonly=True, states={'draft': [('readonly', False)]}), 'product_uos': fields.many2one('product.uom', 'Product UoS'), 'discount': fields.float('Discount (%)', digits_compute= dp.get_precision('Discount'), readonly=True, states={'draft': [('readonly', False)]}), 'th_weight': fields.float('Weight', readonly=True, states={'draft': [('readonly', False)]}), 'state': fields.selection( [('cancel', 'Cancelled'),('draft', 'Draft'),('confirmed', 'Confirmed'),('exception', 'Exception'),('done', 'Done')], 'Status', required=True, readonly=True, copy=False, help='* The \'Draft\' status is set when the related sales order in draft status. \ \n* The \'Confirmed\' status is set when the related sales order is confirmed. \ \n* The \'Exception\' status is set when the related sales order is set as exception. \ \n* The \'Done\' status is set when the sales order line has been picked. \ \n* The \'Cancelled\' status is set when a user cancel the sales order related.'), 'order_partner_id': fields.related('order_id', 'partner_id', type='many2one', relation='res.partner', store=True, string='Customer'), 'salesman_id':fields.related('order_id', 'user_id', type='many2one', relation='res.users', store=True, string='Salesperson'), 'company_id': fields.related('order_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True), 'delay': fields.float('Delivery Lead Time', required=True, help="Number of days between the order confirmation and the shipping of the products to the customer", readonly=True, states={'draft': [('readonly', False)]}), 'procurement_ids': fields.one2many('procurement.order', 'sale_line_id', 'Procurements'), } _order = 'order_id desc, sequence, id' _defaults = { 'product_uom' : _get_uom_id, 'discount': 0.0, 'product_uom_qty': 1, 'product_uos_qty': 1, 'sequence': 10, 'state': 'draft', 'price_unit': 0.0, 'delay': 0.0, } def _get_line_qty(self, cr, uid, line, context=None): if line.product_uos: return line.product_uos_qty or 0.0 return line.product_uom_qty def _get_line_uom(self, cr, uid, line, context=None): if line.product_uos: return line.product_uos.id return line.product_uom.id def _prepare_order_line_invoice_line(self, cr, uid, line, account_id=False, context=None): """Prepare the dict of values to create the new invoice line for a sales order line. This method may be overridden to implement custom invoice generation (making sure to call super() to establish a clean extension chain). :param browse_record line: sale.order.line record to invoice :param int account_id: optional ID of a G/L account to force (this is used for returning products including service) :return: dict of values to create() the invoice line """ res = {} if not line.invoiced: if not account_id: if line.product_id: account_id = line.product_id.property_account_income.id if not account_id: account_id = line.product_id.categ_id.property_account_income_categ.id if not account_id: raise osv.except_osv(_('Error!'), _('Please define income account for this product: "%s" (id:%d).') % \ (line.product_id.name, line.product_id.id,)) else: prop = self.pool.get('ir.property').get(cr, uid, 'property_account_income_categ', 'product.category', context=context) account_id = prop and prop.id or False uosqty = self._get_line_qty(cr, uid, line, context=context) uos_id = self._get_line_uom(cr, uid, line, context=context) pu = 0.0 if uosqty: pu = round(line.price_unit * line.product_uom_qty / uosqty, self.pool.get('decimal.precision').precision_get(cr, uid, 'Product Price')) fpos = line.order_id.fiscal_position or False account_id = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, account_id) if not account_id: raise osv.except_osv(_('Error!'), _('There is no Fiscal Position defined or Income category account defined for default properties of Product categories.')) res = { 'name': line.name, 'sequence': line.sequence, 'origin': line.order_id.name, 'account_id': account_id, 'price_unit': pu, 'quantity': uosqty, 'discount': line.discount, 'uos_id': uos_id, 'product_id': line.product_id.id or False, 'invoice_line_tax_id': [(6, 0, [x.id for x in line.tax_id])], 'account_analytic_id': line.order_id.project_id and line.order_id.project_id.id or False, } return res def invoice_line_create(self, cr, uid, ids, context=None): if context is None: context = {} create_ids = [] sales = set() for line in self.browse(cr, uid, ids, context=context): vals = self._prepare_order_line_invoice_line(cr, uid, line, False, context) if vals: inv_id = self.pool.get('account.invoice.line').create(cr, uid, vals, context=context) self.write(cr, uid, [line.id], {'invoice_lines': [(4, inv_id)]}, context=context) sales.add(line.order_id.id) create_ids.append(inv_id) # Trigger workflow events for sale_id in sales: workflow.trg_write(uid, 'sale.order', sale_id, cr) return create_ids def button_cancel(self, cr, uid, ids, context=None): for line in self.browse(cr, uid, ids, context=context): if line.invoiced: raise osv.except_osv(_('Invalid Action!'), _('You cannot cancel a sales order line that has already been invoiced.')) return self.write(cr, uid, ids, {'state': 'cancel'}) def button_confirm(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'confirmed'}) def button_done(self, cr, uid, ids, context=None): res = self.write(cr, uid, ids, {'state': 'done'}) for line in self.browse(cr, uid, ids, context=context): workflow.trg_write(uid, 'sale.order', line.order_id.id, cr) return res def uos_change(self, cr, uid, ids, product_uos, product_uos_qty=0, product_id=None): product_obj = self.pool.get('product.product') if not product_id: return {'value': {'product_uom': product_uos, 'product_uom_qty': product_uos_qty}, 'domain': {}} product = product_obj.browse(cr, uid, product_id) value = { 'product_uom': product.uom_id.id, } # FIXME must depend on uos/uom of the product and not only of the coeff. try: value.update({ 'product_uom_qty': product_uos_qty / product.uos_coeff, 'th_weight': product_uos_qty / product.uos_coeff * product.weight }) except ZeroDivisionError: pass return {'value': value} def create(self, cr, uid, values, context=None): if values.get('order_id') and values.get('product_id') and any(f not in values for f in ['name', 'price_unit', 'type', 'product_uom_qty', 'product_uom']): order = self.pool['sale.order'].read(cr, uid, values['order_id'], ['pricelist_id', 'partner_id', 'date_order', 'fiscal_position'], context=context) defaults = self.product_id_change(cr, uid, [], order['pricelist_id'][0], values['product_id'], qty=float(values.get('product_uom_qty', False)), uom=values.get('product_uom', False), qty_uos=float(values.get('product_uos_qty', False)), uos=values.get('product_uos', False), name=values.get('name', False), partner_id=order['partner_id'][0], date_order=order['date_order'], fiscal_position=order['fiscal_position'][0] if order['fiscal_position'] else False, flag=False, # Force name update context=context )['value'] if defaults.get('tax_id'): defaults['tax_id'] = [[6, 0, defaults['tax_id']]] values = dict(defaults, **values) return super(sale_order_line, self).create(cr, uid, values, context=context) def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, context=None): context = context or {} lang = lang or context.get('lang', False) if not partner_id: raise osv.except_osv(_('No Customer Defined!'), _('Before choosing a product,\n select a customer in the sales form.')) warning = False product_uom_obj = self.pool.get('product.uom') partner_obj = self.pool.get('res.partner') product_obj = self.pool.get('product.product') context = {'lang': lang, 'partner_id': partner_id} partner = partner_obj.browse(cr, uid, partner_id) lang = partner.lang context_partner = {'lang': lang, 'partner_id': partner_id} if not product: return {'value': {'th_weight': 0, 'product_uos_qty': qty}, 'domain': {'product_uom': [], 'product_uos': []}} if not date_order: date_order = time.strftime(DEFAULT_SERVER_DATE_FORMAT) result = {} warning_msgs = '' product_obj = product_obj.browse(cr, uid, product, context=context_partner) uom2 = False if uom: uom2 = product_uom_obj.browse(cr, uid, uom) if product_obj.uom_id.category_id.id != uom2.category_id.id: uom = False if uos: if product_obj.uos_id: uos2 = product_uom_obj.browse(cr, uid, uos) if product_obj.uos_id.category_id.id != uos2.category_id.id: uos = False else: uos = False fpos = False if not fiscal_position: fpos = partner.property_account_position or False else: fpos = self.pool.get('account.fiscal.position').browse(cr, uid, fiscal_position) if update_tax: #The quantity only have changed result['tax_id'] = self.pool.get('account.fiscal.position').map_tax(cr, uid, fpos, product_obj.taxes_id) if not flag: result['name'] = self.pool.get('product.product').name_get(cr, uid, [product_obj.id], context=context_partner)[0][1] if product_obj.description_sale: result['name'] += '\n'+product_obj.description_sale domain = {} if (not uom) and (not uos): result['product_uom'] = product_obj.uom_id.id if product_obj.uos_id: result['product_uos'] = product_obj.uos_id.id result['product_uos_qty'] = qty * product_obj.uos_coeff uos_category_id = product_obj.uos_id.category_id.id else: result['product_uos'] = False result['product_uos_qty'] = qty uos_category_id = False result['th_weight'] = qty * product_obj.weight domain = {'product_uom': [('category_id', '=', product_obj.uom_id.category_id.id)], 'product_uos': [('category_id', '=', uos_category_id)]} elif uos and not uom: # only happens if uom is False result['product_uom'] = product_obj.uom_id and product_obj.uom_id.id result['product_uom_qty'] = qty_uos / product_obj.uos_coeff result['th_weight'] = result['product_uom_qty'] * product_obj.weight elif uom: # whether uos is set or not default_uom = product_obj.uom_id and product_obj.uom_id.id q = product_uom_obj._compute_qty(cr, uid, uom, qty, default_uom) if product_obj.uos_id: result['product_uos'] = product_obj.uos_id.id result['product_uos_qty'] = qty * product_obj.uos_coeff else: result['product_uos'] = False result['product_uos_qty'] = qty result['th_weight'] = q * product_obj.weight # Round the quantity up if not uom2: uom2 = product_obj.uom_id # get unit price if not pricelist: warn_msg = _('You have to select a pricelist or a customer in the sales form !\n' 'Please set one before choosing a product.') warning_msgs += _("No Pricelist ! : ") + warn_msg +"\n\n" else: price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist], product, qty or 1.0, partner_id, { 'uom': uom or result.get('product_uom'), 'date': date_order, })[pricelist] if price is False: warn_msg = _("Cannot find a pricelist line matching this product and quantity.\n" "You have to change either the product, the quantity or the pricelist.") warning_msgs += _("No valid pricelist line found ! :") + warn_msg +"\n\n" else: result.update({'price_unit': price}) if warning_msgs: warning = { 'title': _('Configuration Error!'), 'message' : warning_msgs } return {'value': result, 'domain': domain, 'warning': warning} def product_uom_change(self, cursor, user, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, context=None): context = context or {} lang = lang or ('lang' in context and context['lang']) if not uom: return {'value': {'price_unit': 0.0, 'product_uom' : uom or False}} return self.product_id_change(cursor, user, ids, pricelist, product, qty=qty, uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, context=context) def unlink(self, cr, uid, ids, context=None): if context is None: context = {} """Allows to delete sales order lines in draft,cancel states""" for rec in self.browse(cr, uid, ids, context=context): if rec.state not in ['draft', 'cancel']: raise osv.except_osv(_('Invalid Action!'), _('Cannot delete a sales order line which is in state \'%s\'.') %(rec.state,)) return super(sale_order_line, self).unlink(cr, uid, ids, context=context) class mail_compose_message(osv.Model): _inherit = 'mail.compose.message' def send_mail(self, cr, uid, ids, context=None): context = context or {} if context.get('default_model') == 'sale.order' and context.get('default_res_id') and context.get('mark_so_as_sent'): context = dict(context, mail_post_autofollow=True) self.pool.get('sale.order').signal_workflow(cr, uid, [context['default_res_id']], 'quotation_sent') return super(mail_compose_message, self).send_mail(cr, uid, ids, context=context) class account_invoice(osv.Model): _inherit = 'account.invoice' def _get_default_section_id(self, cr, uid, context=None): """ Gives default section by checking if present in the context """ section_id = self._resolve_section_id_from_context(cr, uid, context=context) or False if not section_id: section_id = self.pool.get('res.users').browse(cr, uid, uid, context).default_section_id.id or False return section_id def _resolve_section_id_from_context(self, cr, uid, context=None): """ Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team. """ if context is None: context = {} if type(context.get('default_section_id')) in (int, long): return context.get('default_section_id') if isinstance(context.get('default_section_id'), basestring): section_ids = self.pool.get('crm.case.section').name_search(cr, uid, name=context['default_section_id'], context=context) if len(section_ids) == 1: return int(section_ids[0][0]) return None _columns = { 'section_id': fields.many2one('crm.case.section', 'Sales Team'), } _defaults = { 'section_id': lambda self, cr, uid, c=None: self._get_default_section_id(cr, uid, context=c) } def confirm_paid(self, cr, uid, ids, context=None): sale_order_obj = self.pool.get('sale.order') res = super(account_invoice, self).confirm_paid(cr, uid, ids, context=context) so_ids = sale_order_obj.search(cr, uid, [('invoice_ids', 'in', ids)], context=context) for so_id in so_ids: sale_order_obj.message_post(cr, uid, so_id, body=_("Invoice paid"), context=context) return res def unlink(self, cr, uid, ids, context=None): """ Overwrite unlink method of account invoice to send a trigger to the sale workflow upon invoice deletion """ invoice_ids = self.search(cr, uid, [('id', 'in', ids), ('state', 'in', ['draft', 'cancel'])], context=context) #if we can't cancel all invoices, do nothing if len(invoice_ids) == len(ids): #Cancel invoice(s) first before deleting them so that if any sale order is associated with them #it will trigger the workflow to put the sale order in an 'invoice exception' state for id in ids: workflow.trg_validate(uid, 'account.invoice', id, 'invoice_cancel', cr) return super(account_invoice, self).unlink(cr, uid, ids, context=context) class procurement_order(osv.osv): _inherit = 'procurement.order' _columns = { 'sale_line_id': fields.many2one('sale.order.line', string='Sale Order Line'), } def write(self, cr, uid, ids, vals, context=None): if isinstance(ids, (int, long)): ids = [ids] res = super(procurement_order, self).write(cr, uid, ids, vals, context=context) from openerp import workflow if vals.get('state') in ['done', 'cancel', 'exception']: for proc in self.browse(cr, uid, ids, context=context): if proc.sale_line_id and proc.sale_line_id.order_id: order_id = proc.sale_line_id.order_id.id if self.pool.get('sale.order').test_procurements_done(cr, uid, [order_id], context=context): workflow.trg_validate(uid, 'sale.order', order_id, 'ship_end', cr) if self.pool.get('sale.order').test_procurements_except(cr, uid, [order_id], context=context): workflow.trg_validate(uid, 'sale.order', order_id, 'ship_except', cr) return res class product_product(osv.Model): _inherit = 'product.product' def _sales_count(self, cr, uid, ids, field_name, arg, context=None): SaleOrderLine = self.pool['sale.order.line'] return { product_id: SaleOrderLine.search_count(cr,uid, [('product_id', '=', product_id)], context=context) for product_id in ids } _columns = { 'sales_count': fields.function(_sales_count, string='# Sales', type='integer'), } class product_template(osv.Model): _inherit = 'product.template' def _sales_count(self, cr, uid, ids, field_name, arg, context=None): res = dict.fromkeys(ids, 0) for template in self.browse(cr, uid, ids, context=context): res[template.id] = sum([p.sales_count for p in template.product_variant_ids]) return res def action_view_sales(self, cr, uid, ids, context=None): act_obj = self.pool.get('ir.actions.act_window') mod_obj = self.pool.get('ir.model.data') product_ids = [] for template in self.browse(cr, uid, ids, context=context): product_ids += [x.id for x in template.product_variant_ids] result = mod_obj.xmlid_to_res_id(cr, uid, 'sale.action_order_line_product_tree',raise_if_not_found=True) result = act_obj.read(cr, uid, [result], context=context)[0] result['domain'] = "[('product_id','in',[" + ','.join(map(str, product_ids)) + "])]" return result _columns = { 'sales_count': fields.function(_sales_count, string='# Sales', type='integer'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
neilLasrado/erpnext
erpnext/patches/v11_0/refactor_autoname_naming.py
14
4592
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import print_function, unicode_literals import frappe from frappe.custom.doctype.property_setter.property_setter import make_property_setter doctype_series_map = { 'Activity Cost': 'PROJ-ACC-.#####', 'Agriculture Task': 'AG-TASK-.#####', 'Assessment Plan': 'EDU-ASP-.YYYY.-.#####', 'Assessment Result': 'EDU-RES-.YYYY.-.#####', 'Asset Movement': 'ACC-ASM-.YYYY.-.#####', 'Attendance Request': 'HR-ARQ-.YY.-.MM.-.#####', 'Authorization Rule': 'HR-ARU-.#####', 'Bank Guarantee': 'ACC-BG-.YYYY.-.#####', 'Bin': 'MAT-BIN-.YYYY.-.#####', 'Certification Application': 'NPO-CAPP-.YYYY.-.#####', 'Certified Consultant': 'NPO-CONS-.YYYY.-.#####', 'Chat Room': 'CHAT-ROOM-.#####', 'Compensatory Leave Request': 'HR-CMP-.YY.-.MM.-.#####', 'Custom Script': 'SYS-SCR-.#####', 'Employee Benefit Application': 'HR-BEN-APP-.YY.-.MM.-.#####', 'Employee Benefit Application Detail': '', 'Employee Benefit Claim': 'HR-BEN-CLM-.YY.-.MM.-.#####', 'Employee Incentive': 'HR-EINV-.YY.-.MM.-.#####', 'Employee Onboarding': 'HR-EMP-ONB-.YYYY.-.#####', 'Employee Onboarding Template': 'HR-EMP-ONT-.#####', 'Employee Promotion': 'HR-EMP-PRO-.YYYY.-.#####', 'Employee Separation': 'HR-EMP-SEP-.YYYY.-.#####', 'Employee Separation Template': 'HR-EMP-STP-.#####', 'Employee Tax Exemption Declaration': 'HR-TAX-DEC-.YYYY.-.#####', 'Employee Tax Exemption Proof Submission': 'HR-TAX-PRF-.YYYY.-.#####', 'Employee Transfer': 'HR-EMP-TRN-.YYYY.-.#####', 'Event': 'EVENT-.YYYY.-.#####', 'Exchange Rate Revaluation': 'ACC-ERR-.YYYY.-.#####', 'GL Entry': 'ACC-GLE-.YYYY.-.#####', 'Guardian': 'EDU-GRD-.YYYY.-.#####', 'Hotel Room Reservation': 'HTL-RES-.YYYY.-.#####', 'Item Price': '', 'Job Applicant': 'HR-APP-.YYYY.-.#####', 'Job Offer': 'HR-OFF-.YYYY.-.#####', 'Leave Encashment': 'HR-ENC-.YYYY.-.#####', 'Leave Period': 'HR-LPR-.YYYY.-.#####', 'Leave Policy': 'HR-LPOL-.YYYY.-.#####', 'Loan': 'ACC-LOAN-.YYYY.-.#####', 'Loan Application': 'ACC-LOAP-.YYYY.-.#####', 'Loyalty Point Entry': '', 'Membership': 'NPO-MSH-.YYYY.-.#####', 'Packing Slip': 'MAT-PAC-.YYYY.-.#####', 'Patient Appointment': 'HLC-APP-.YYYY.-.#####', 'Payment Terms Template Detail': '', 'Payroll Entry': 'HR-PRUN-.YYYY.-.#####', 'Period Closing Voucher': 'ACC-PCV-.YYYY.-.#####', 'Plant Analysis': 'AG-PLA-.YYYY.-.#####', 'POS Closing Voucher': 'POS-CLO-.YYYY.-.#####', 'Prepared Report': 'SYS-PREP-.YYYY.-.#####', 'Program Enrollment': 'EDU-ENR-.YYYY.-.#####', 'Quotation Item': '', 'Restaurant Reservation': 'RES-RES-.YYYY.-.#####', 'Retention Bonus': 'HR-RTB-.YYYY.-.#####', 'Room': 'HTL-ROOM-.YYYY.-.#####', 'Salary Structure Assignment': 'HR-SSA-.YY.-.MM.-.#####', 'Sales Taxes and Charges': '', 'Share Transfer': 'ACC-SHT-.YYYY.-.#####', 'Shift Assignment': 'HR-SHA-.YY.-.MM.-.#####', 'Shift Request': 'HR-SHR-.YY.-.MM.-.#####', 'SMS Log': 'SYS-SMS-.#####', 'Soil Analysis': 'AG-ANA-.YY.-.MM.-.#####', 'Soil Texture': 'AG-TEX-.YYYY.-.#####', 'Stock Ledger Entry': 'MAT-SLE-.YYYY.-.#####', 'Student Leave Application': 'EDU-SLA-.YYYY.-.#####', 'Student Log': 'EDU-SLOG-.YYYY.-.#####', 'Subscription': 'ACC-SUB-.YYYY.-.#####', 'Task': 'TASK-.YYYY.-.#####', 'Tax Rule': 'ACC-TAX-RULE-.YYYY.-.#####', 'Training Feedback': 'HR-TRF-.YYYY.-.#####', 'Training Result': 'HR-TRR-.YYYY.-.#####', 'Travel Request': 'HR-TRQ-.YYYY.-.#####', 'UOM Conversion Factor': 'MAT-UOM-CNV-.#####', 'Water Analysis': 'HR-WAT-.YYYY.-.#####', 'Workflow Action': 'SYS-WACT-.#####', } def execute(): series_to_set = get_series() for doctype, opts in series_to_set.items(): set_series(doctype, opts['value']) def set_series(doctype, value): doc = frappe.db.exists('Property Setter', {'doc_type': doctype, 'property': 'autoname'}) if doc: frappe.db.set_value('Property Setter', doc, 'value', value) else: make_property_setter(doctype, '', 'autoname', value, '', for_doctype = True) def get_series(): series_to_set = {} for doctype in doctype_series_map: if not frappe.db.exists('DocType', doctype): continue if not frappe.db.a_row_exists(doctype): continue series_to_preserve = get_series_to_preserve(doctype) if not series_to_preserve: continue # set autoname property setter if series_to_preserve: series_to_set[doctype] = {'value': series_to_preserve} return series_to_set def get_series_to_preserve(doctype): series_to_preserve = frappe.db.get_value('DocType', doctype, 'autoname') return series_to_preserve
gpl-3.0
kch8qx/osf.io
website/project/views/log.py
38
2291
# -*- coding: utf-8 -*- import httplib as http import logging import math from flask import request from framework.exceptions import HTTPError from framework.auth.decorators import collect_auth from framework.transactions.handlers import no_auto_transaction from website.views import serialize_log, validate_page_num from website.project.model import NodeLog from website.project.model import has_anonymous_link from website.project.decorators import must_be_valid_project logger = logging.getLogger(__name__) @collect_auth @no_auto_transaction def get_log(auth, log_id): log = NodeLog.load(log_id) node_to_use = log.node if not node_to_use.can_view(auth): raise HTTPError(http.FORBIDDEN) return {'log': serialize_log(log, auth=auth)} def _get_logs(node, count, auth, page=0): """ :param Node node: :param int count: :param auth: :return list: List of serialized logs, boolean: if there are more logs """ logs_set = node.get_aggregate_logs_queryset(auth) total = logs_set.count() pages = math.ceil(total / float(count)) validate_page_num(page, pages) start = page * count stop = start + count logs = [ serialize_log(log, auth=auth, anonymous=has_anonymous_link(node, auth)) for log in logs_set[start:stop] ] return logs, total, pages @no_auto_transaction @collect_auth @must_be_valid_project(retractions_valid=True) def get_logs(auth, node, **kwargs): """ """ try: page = int(request.args.get('page', 0)) except ValueError: raise HTTPError(http.BAD_REQUEST, data=dict( message_long='Invalid value for "page".' )) if not node.can_view(auth): raise HTTPError(http.FORBIDDEN) if 'count' in request.args: count = int(request.args['count']) elif 'count' in kwargs: count = kwargs['count'] elif request.json and 'count' in request.json.keys(): count = request.json['count'] else: count = 10 # Serialize up to `count` logs in reverse chronological order; skip # logs that the current user / API key cannot access logs, total, pages = _get_logs(node, count, auth, page) return {'logs': logs, 'total': total, 'pages': pages, 'page': page}
apache-2.0
zaqwes8811/matlab_ext
identification/tests/test-dfilters.py
1
1166
# coding: utf-8 """ Характеристики для цифрового фильтра """ # Other from pylab import * from numpy import arange from numpy import ones # App from visualisers import mfreqz from visualisers import impz from iir_models.iir_digital import calc_digital_characteristics if __name__=='__main__': mean_params = (5.32255626, 3.07633474, 0.88892465, 2.14692147, 69.83541651) (T1, T2, t0, K, dy) = mean_params #K = 1 freq = arange(10000)*0.01 # Hz freq_sampling = 1 # Hz """ Model """ b, a, fs = calc_digital_characteristics((T1, T2, t0, K), freq_sampling) print b, a #b = ones(1) from numpy.polynomial import Polynomial as P a1 = P(b) a2 = P([0,0,0,1]) b = (a1*a2).coef """ View """ #plot_normalize_analog(tau, freq, freq_sampling, plot_AFC, plot_PFC) #impz(b, a) mfreqz(b, a) b, a, fs = calc_digital_characteristics((T1, T2, t0, K), freq_sampling) print b, a """ View """ #plot_normalize_analog(tau, freq, freq_sampling, plot_AFC, plot_PFC) #impz(b, a) mfreqz(b, a) show() print 'Done'
apache-2.0
lanfker/tdma_imac
src/lte/bindings/modulegen__gcc_ILP32.py
27
474175
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() ## log.h (module 'core'): ns3::LogLevel [enumeration] module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_INFO', 'LOG_FUNCTION', 'LOG_LEVEL_FUNCTION', 'LOG_LOGIC', 'LOG_LEVEL_LOGIC', 'LOG_ALL', 'LOG_LEVEL_ALL', 'LOG_PREFIX_FUNC', 'LOG_PREFIX_TIME', 'LOG_PREFIX_NODE'], import_from_module='ns.core') ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## 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']) ## 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-rate.h (module 'network'): ns3::DataRate [class] module.add_class('DataRate', import_from_module='ns.network') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord [class] module.add_class('IpcsClassifierRecord', import_from_module='ns.wimax') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## log.h (module 'core'): ns3::LogComponent [class] module.add_class('LogComponent', import_from_module='ns.core') ## lte-helper.h (module 'lte'): ns3::LteHelper [class] module.add_class('LteHelper') ## lte-helper.h (module 'lte'): ns3::LteHelper::NetDeviceType [enumeration] module.add_enum('NetDeviceType', ['DEVICE_TYPE_USER_EQUIPMENT', 'DEVICE_TYPE_ENODEB'], outer_class=root_module['ns3::LteHelper']) ## lte-spectrum-value-helper.h (module 'lte'): ns3::LteSpectrumValueHelper [class] module.add_class('LteSpectrumValueHelper') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## random-variable.h (module 'core'): ns3::RandomVariable [class] module.add_class('RandomVariable', import_from_module='ns.core') ## random-variable.h (module 'core'): ns3::SeedManager [class] module.add_class('SeedManager', import_from_module='ns.core') ## random-variable.h (module 'core'): ns3::SequentialVariable [class] module.add_class('SequentialVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## 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') ## wimax-tlv.h (module 'wimax'): ns3::TlvValue [class] module.add_class('TlvValue', allow_subclassing=True, import_from_module='ns.wimax') ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue [class] module.add_class('TosTlvValue', import_from_module='ns.wimax', parent=root_module['ns3::TlvValue']) ## 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']) ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue [class] module.add_class('U16TlvValue', import_from_module='ns.wimax', parent=root_module['ns3::TlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue [class] module.add_class('U32TlvValue', import_from_module='ns.wimax', parent=root_module['ns3::TlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue [class] module.add_class('U8TlvValue', import_from_module='ns.wimax', parent=root_module['ns3::TlvValue']) ## 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') ## wimax-tlv.h (module 'wimax'): ns3::VectorTlvValue [class] module.add_class('VectorTlvValue', import_from_module='ns.wimax', parent=root_module['ns3::TlvValue']) ## 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') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue [class] module.add_class('ClassificationRuleVectorTlvValue', import_from_module='ns.wimax', parent=root_module['ns3::VectorTlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue::ClassificationRuleTlvType [enumeration] module.add_enum('ClassificationRuleTlvType', ['Priority', 'ToS', 'Protocol', 'IP_src', 'IP_dst', 'Port_src', 'Port_dst', 'Index'], outer_class=root_module['ns3::ClassificationRuleVectorTlvValue'], import_from_module='ns.wimax') ## random-variable.h (module 'core'): ns3::ConstantVariable [class] module.add_class('ConstantVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue [class] module.add_class('CsParamVectorTlvValue', import_from_module='ns.wimax', parent=root_module['ns3::VectorTlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue::Type [enumeration] module.add_enum('Type', ['Classifier_DSC_Action', 'Packet_Classification_Rule'], outer_class=root_module['ns3::CsParamVectorTlvValue'], import_from_module='ns.wimax') ## 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']) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue [class] module.add_class('Ipv4AddressTlvValue', import_from_module='ns.wimax', parent=root_module['ns3::TlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr [struct] module.add_class('ipv4Addr', import_from_module='ns.wimax', outer_class=root_module['ns3::Ipv4AddressTlvValue']) ## random-variable.h (module 'core'): ns3::LogNormalVariable [class] module.add_class('LogNormalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## lte-mac-header.h (module 'lte'): ns3::LteMacHeader [class] module.add_class('LteMacHeader', parent=root_module['ns3::Header']) ## random-variable.h (module 'core'): ns3::NormalVariable [class] module.add_class('NormalVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariable']) ## 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']) ## packet-scheduler.h (module 'lte'): ns3::PacketScheduler [class] module.add_class('PacketScheduler', 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']) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue [class] module.add_class('PortRangeTlvValue', import_from_module='ns.wimax', parent=root_module['ns3::TlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange [struct] module.add_class('PortRange', import_from_module='ns.wimax', outer_class=root_module['ns3::PortRangeTlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::ProtocolTlvValue [class] module.add_class('ProtocolTlvValue', import_from_module='ns.wimax', parent=root_module['ns3::TlvValue']) ## radio-bearer-instance.h (module 'lte'): ns3::RadioBearerInstance [class] module.add_class('RadioBearerInstance', parent=root_module['ns3::Object']) ## radio-bearer-instance.h (module 'lte'): ns3::RadioBearerInstance::BearerDirection [enumeration] module.add_enum('BearerDirection', ['DIRECTION_TYPE_UL', 'DIRECTION_TYPE_DL'], outer_class=root_module['ns3::RadioBearerInstance']) ## radio-bearer-instance.h (module 'lte'): ns3::RadioBearerInstance::BearerType [enumeration] module.add_enum('BearerType', ['BEARER_TYPE_SRB1', 'BEARER_TYPE_SRB2', 'BEARER_TYPE_DRB'], outer_class=root_module['ns3::RadioBearerInstance']) ## rlc-entity.h (module 'lte'): ns3::RlcEntity [class] module.add_class('RlcEntity', parent=root_module['ns3::Object']) ## rrc-entity.h (module 'lte'): ns3::RrcEntity [class] module.add_class('RrcEntity', parent=root_module['ns3::Object']) ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue [class] module.add_class('SfVectorTlvValue', import_from_module='ns.wimax', parent=root_module['ns3::VectorTlvValue']) ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue::Type [enumeration] module.add_enum('Type', ['SFID', 'CID', 'Service_Class_Name', 'reserved1', 'QoS_Parameter_Set_Type', 'Traffic_Priority', 'Maximum_Sustained_Traffic_Rate', 'Maximum_Traffic_Burst', 'Minimum_Reserved_Traffic_Rate', 'Minimum_Tolerable_Traffic_Rate', 'Service_Flow_Scheduling_Type', 'Request_Transmission_Policy', 'Tolerated_Jitter', 'Maximum_Latency', 'Fixed_length_versus_Variable_length_SDU_Indicator', 'SDU_Size', 'Target_SAID', 'ARQ_Enable', 'ARQ_WINDOW_SIZE', 'ARQ_RETRY_TIMEOUT_Transmitter_Delay', 'ARQ_RETRY_TIMEOUT_Receiver_Delay', 'ARQ_BLOCK_LIFETIME', 'ARQ_SYNC_LOSS', 'ARQ_DELIVER_IN_ORDER', 'ARQ_PURGE_TIMEOUT', 'ARQ_BLOCK_SIZE', 'reserved2', 'CS_Specification', 'IPV4_CS_Parameters'], outer_class=root_module['ns3::SfVectorTlvValue'], import_from_module='ns.wimax') ## simple-packet-scheduler.h (module 'lte'): ns3::SimplePacketScheduler [class] module.add_class('SimplePacketScheduler', parent=root_module['ns3::PacketScheduler']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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::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')) ## 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']) ## wimax-tlv.h (module 'wimax'): ns3::Tlv [class] module.add_class('Tlv', import_from_module='ns.wimax', parent=root_module['ns3::Header']) ## wimax-tlv.h (module 'wimax'): ns3::Tlv::CommonTypes [enumeration] module.add_enum('CommonTypes', ['HMAC_TUPLE', 'MAC_VERSION_ENCODING', 'CURRENT_TRANSMIT_POWER', 'DOWNLINK_SERVICE_FLOW', 'UPLINK_SERVICE_FLOW', 'VENDOR_ID_EMCODING', 'VENDOR_SPECIFIC_INFORMATION'], outer_class=root_module['ns3::Tlv'], import_from_module='ns.wimax') ## 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']) ## ue-manager.h (module 'lte'): ns3::UeManager [class] module.add_class('UeManager', parent=root_module['ns3::Object']) ## ue-record.h (module 'lte'): ns3::UeRecord [class] module.add_class('UeRecord', parent=root_module['ns3::Object']) ## ue-record.h (module 'lte'): ns3::UeRecord::CqiFeedback [struct] module.add_class('CqiFeedback', outer_class=root_module['ns3::UeRecord']) ## amc-module.h (module 'lte'): ns3::AmcModule [class] module.add_class('AmcModule', 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> >']) ## bearer-qos-parameters.h (module 'lte'): ns3::BearerQosParameters [class] module.add_class('BearerQosParameters', parent=root_module['ns3::Object']) ## bearer-qos-parameters.h (module 'lte'): ns3::BearerQosParameters::BearerQosType [enumeration] module.add_enum('BearerQosType', ['BEARER_TYPE_GBR', 'BEARER_TYPE_NGBR'], outer_class=root_module['ns3::BearerQosParameters']) ## 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']) ## channel-realization.h (module 'lte'): ns3::ChannelRealization [class] module.add_class('ChannelRealization', 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']) ## discrete-time-loss-model.h (module 'lte'): ns3::DiscreteTimeLossModel [class] module.add_class('DiscreteTimeLossModel', parent=root_module['ns3::Object']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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> >']) ## 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'], outer_class=root_module['ns3::IdealControlMessage']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## jakes-fading-loss-model.h (module 'lte'): ns3::JakesFadingLossModel [class] module.add_class('JakesFadingLossModel', parent=root_module['ns3::DiscreteTimeLossModel']) ## lte-mac-queue.h (module 'lte'): ns3::LteMacQueue [class] module.add_class('LteMacQueue', parent=root_module['ns3::Object']) ## lte-phy.h (module 'lte'): ns3::LtePhy [class] module.add_class('LtePhy', parent=root_module['ns3::Object']) ## lte-propagation-loss-model.h (module 'lte'): ns3::LtePropagationLossModel [class] module.add_class('LtePropagationLossModel', parent=root_module['ns3::SpectrumPropagationLossModel']) ## 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']) ## 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-entity.h (module 'lte'): ns3::MacEntity [class] module.add_class('MacEntity', parent=root_module['ns3::Object']) ## 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> >']) ## path-loss-model.h (module 'lte'): ns3::PathLossModel [class] module.add_class('PathLossModel', parent=root_module['ns3::DiscreteTimeLossModel']) ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage [class] module.add_class('PdcchMapIdealControlMessage', parent=root_module['ns3::IdealControlMessage']) ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::Direction [enumeration] module.add_enum('Direction', ['DOWNLINK', 'UPLINK'], outer_class=root_module['ns3::PdcchMapIdealControlMessage']) ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::IdealPdcchRecord [struct] module.add_class('IdealPdcchRecord', outer_class=root_module['ns3::PdcchMapIdealControlMessage']) ## penetration-loss-model.h (module 'lte'): ns3::PenetrationLossModel [class] module.add_class('PenetrationLossModel', parent=root_module['ns3::DiscreteTimeLossModel']) ## 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']) ## shadowing-loss-model.h (module 'lte'): ns3::ShadowingLossModel [class] module.add_class('ShadowingLossModel', parent=root_module['ns3::DiscreteTimeLossModel']) ## spectrum-channel.h (module 'spectrum'): ns3::SpectrumChannel [class] module.add_class('SpectrumChannel', import_from_module='ns.spectrum', parent=root_module['ns3::Channel']) ## 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']) ## ue-phy.h (module 'lte'): ns3::UeLtePhy [class] module.add_class('UeLtePhy', parent=root_module['ns3::LtePhy']) ## ue-lte-spectrum-phy.h (module 'lte'): ns3::UeLteSpectrumPhy [class] module.add_class('UeLteSpectrumPhy', parent=root_module['ns3::LteSpectrumPhy']) ## ue-mac-entity.h (module 'lte'): ns3::UeMacEntity [class] module.add_class('UeMacEntity', parent=root_module['ns3::MacEntity']) ## uinteger.h (module 'core'): ns3::UintegerValue [class] module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector2DChecker [class] module.add_class('Vector2DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector2DValue [class] module.add_class('Vector2DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector3DChecker [class] module.add_class('Vector3DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector3DValue [class] module.add_class('Vector3DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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::CqiIdealControlMessage [class] module.add_class('CqiIdealControlMessage', parent=root_module['ns3::IdealControlMessage']) ## ideal-control-messages.h (module 'lte'): ns3::CqiIdealControlMessage::CqiFeedback [struct] module.add_class('CqiFeedback', outer_class=root_module['ns3::CqiIdealControlMessage']) ## enb-phy.h (module 'lte'): ns3::EnbLtePhy [class] module.add_class('EnbLtePhy', parent=root_module['ns3::LtePhy']) ## enb-lte-spectrum-phy.h (module 'lte'): ns3::EnbLteSpectrumPhy [class] module.add_class('EnbLteSpectrumPhy', parent=root_module['ns3::LteSpectrumPhy']) ## enb-mac-entity.h (module 'lte'): ns3::EnbMacEntity [class] module.add_class('EnbMacEntity', parent=root_module['ns3::MacEntity']) ## lte-net-device.h (module 'lte'): ns3::LteNetDevice [class] module.add_class('LteNetDevice', parent=root_module['ns3::NetDevice']) ## single-model-spectrum-channel.h (module 'spectrum'): ns3::SingleModelSpectrumChannel [class] module.add_class('SingleModelSpectrumChannel', import_from_module='ns.spectrum', parent=root_module['ns3::SpectrumChannel']) ## ue-net-device.h (module 'lte'): ns3::UeNetDevice [class] module.add_class('UeNetDevice', parent=root_module['ns3::LteNetDevice']) ## enb-net-device.h (module 'lte'): ns3::EnbNetDevice [class] module.add_class('EnbNetDevice', parent=root_module['ns3::LteNetDevice']) 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< ns3::Ptr< ns3::RadioBearerInstance > >', 'ns3::Ptr< ns3::RadioBearerInstance >', container_type='vector') module.add_container('std::vector< double >', 'double', container_type='vector') module.add_container('ns3::Bands', 'ns3::BandInfo', container_type='vector') module.add_container('std::vector< ns3::Ptr< ns3::UeRecord > >', 'ns3::Ptr< ns3::UeRecord >', container_type='vector') module.add_container('std::vector< ns3::UeRecord::CqiFeedback >', 'ns3::UeRecord::CqiFeedback', container_type='vector') module.add_container('std::vector< std::vector< double > >', 'std::vector< double >', container_type='vector') module.add_container('std::deque< ns3::LteMacQueue::QueueElement >', 'ns3::LteMacQueue::QueueElement', container_type='dequeue') module.add_container('std::list< ns3::PdcchMapIdealControlMessage::IdealPdcchRecord >', 'ns3::PdcchMapIdealControlMessage::IdealPdcchRecord', container_type='list') module.add_container('std::list< ns3::CqiIdealControlMessage::CqiFeedback >', 'ns3::CqiIdealControlMessage::CqiFeedback', container_type='list') module.add_container('std::vector< ns3::Ptr< ns3::SpectrumPhy > >', 'ns3::Ptr< ns3::SpectrumPhy >', container_type='vector') 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::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::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('void ( * ) ( std::ostream & ) *', 'ns3::LogNodePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) **', 'ns3::LogNodePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *&', 'ns3::LogNodePrinter&') 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::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('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('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('void ( * ) ( std::ostream & ) *', 'ns3::LogTimePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) **', 'ns3::LogTimePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *&', 'ns3::LogTimePrinter&') 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('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< 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&') ## 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 addressUtils nested_module = module.add_cpp_namespace('addressUtils') register_types_ns3_addressUtils(nested_module) ## Register a nested module for the namespace internal nested_module = module.add_cpp_namespace('internal') register_types_ns3_internal(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_addressUtils(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_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_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_Ns3DataRate_methods(root_module, root_module['ns3::DataRate']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3IpcsClassifierRecord_methods(root_module, root_module['ns3::IpcsClassifierRecord']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent']) register_Ns3LteHelper_methods(root_module, root_module['ns3::LteHelper']) register_Ns3LteSpectrumValueHelper_methods(root_module, root_module['ns3::LteSpectrumValueHelper']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3RandomVariable_methods(root_module, root_module['ns3::RandomVariable']) register_Ns3SeedManager_methods(root_module, root_module['ns3::SeedManager']) register_Ns3SequentialVariable_methods(root_module, root_module['ns3::SequentialVariable']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TlvValue_methods(root_module, root_module['ns3::TlvValue']) register_Ns3TosTlvValue_methods(root_module, root_module['ns3::TosTlvValue']) 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_Ns3U16TlvValue_methods(root_module, root_module['ns3::U16TlvValue']) register_Ns3U32TlvValue_methods(root_module, root_module['ns3::U32TlvValue']) register_Ns3U8TlvValue_methods(root_module, root_module['ns3::U8TlvValue']) 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_Ns3VectorTlvValue_methods(root_module, root_module['ns3::VectorTlvValue']) 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_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3ClassificationRuleVectorTlvValue_methods(root_module, root_module['ns3::ClassificationRuleVectorTlvValue']) register_Ns3ConstantVariable_methods(root_module, root_module['ns3::ConstantVariable']) register_Ns3CsParamVectorTlvValue_methods(root_module, root_module['ns3::CsParamVectorTlvValue']) 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_Ns3Ipv4AddressTlvValue_methods(root_module, root_module['ns3::Ipv4AddressTlvValue']) register_Ns3Ipv4AddressTlvValueIpv4Addr_methods(root_module, root_module['ns3::Ipv4AddressTlvValue::ipv4Addr']) register_Ns3LogNormalVariable_methods(root_module, root_module['ns3::LogNormalVariable']) register_Ns3LteMacHeader_methods(root_module, root_module['ns3::LteMacHeader']) 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_Ns3PacketScheduler_methods(root_module, root_module['ns3::PacketScheduler']) register_Ns3ParetoVariable_methods(root_module, root_module['ns3::ParetoVariable']) register_Ns3PortRangeTlvValue_methods(root_module, root_module['ns3::PortRangeTlvValue']) register_Ns3PortRangeTlvValuePortRange_methods(root_module, root_module['ns3::PortRangeTlvValue::PortRange']) register_Ns3ProtocolTlvValue_methods(root_module, root_module['ns3::ProtocolTlvValue']) register_Ns3RadioBearerInstance_methods(root_module, root_module['ns3::RadioBearerInstance']) register_Ns3RlcEntity_methods(root_module, root_module['ns3::RlcEntity']) register_Ns3RrcEntity_methods(root_module, root_module['ns3::RrcEntity']) register_Ns3SfVectorTlvValue_methods(root_module, root_module['ns3::SfVectorTlvValue']) register_Ns3SimplePacketScheduler_methods(root_module, root_module['ns3::SimplePacketScheduler']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3IdealControlMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3IdealControlMessage__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::IdealControlMessage, ns3::empty, ns3::DefaultDeleter<ns3::IdealControlMessage> >']) 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_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_Ns3Tlv_methods(root_module, root_module['ns3::Tlv']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3UeManager_methods(root_module, root_module['ns3::UeManager']) register_Ns3UeRecord_methods(root_module, root_module['ns3::UeRecord']) register_Ns3UeRecordCqiFeedback_methods(root_module, root_module['ns3::UeRecord::CqiFeedback']) register_Ns3AmcModule_methods(root_module, root_module['ns3::AmcModule']) 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_Ns3BearerQosParameters_methods(root_module, root_module['ns3::BearerQosParameters']) 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_Ns3ChannelRealization_methods(root_module, root_module['ns3::ChannelRealization']) register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker']) register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue']) register_Ns3DiscreteTimeLossModel_methods(root_module, root_module['ns3::DiscreteTimeLossModel']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3IdealControlMessage_methods(root_module, root_module['ns3::IdealControlMessage']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3JakesFadingLossModel_methods(root_module, root_module['ns3::JakesFadingLossModel']) register_Ns3LteMacQueue_methods(root_module, root_module['ns3::LteMacQueue']) register_Ns3LtePhy_methods(root_module, root_module['ns3::LtePhy']) register_Ns3LtePropagationLossModel_methods(root_module, root_module['ns3::LtePropagationLossModel']) register_Ns3LteSpectrumPhy_methods(root_module, root_module['ns3::LteSpectrumPhy']) register_Ns3LteSpectrumSignalParameters_methods(root_module, root_module['ns3::LteSpectrumSignalParameters']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3MacEntity_methods(root_module, root_module['ns3::MacEntity']) 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_Ns3PathLossModel_methods(root_module, root_module['ns3::PathLossModel']) register_Ns3PdcchMapIdealControlMessage_methods(root_module, root_module['ns3::PdcchMapIdealControlMessage']) register_Ns3PdcchMapIdealControlMessageIdealPdcchRecord_methods(root_module, root_module['ns3::PdcchMapIdealControlMessage::IdealPdcchRecord']) register_Ns3PenetrationLossModel_methods(root_module, root_module['ns3::PenetrationLossModel']) register_Ns3RandomVariableChecker_methods(root_module, root_module['ns3::RandomVariableChecker']) register_Ns3RandomVariableValue_methods(root_module, root_module['ns3::RandomVariableValue']) register_Ns3ShadowingLossModel_methods(root_module, root_module['ns3::ShadowingLossModel']) register_Ns3SpectrumChannel_methods(root_module, root_module['ns3::SpectrumChannel']) 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_Ns3UeLtePhy_methods(root_module, root_module['ns3::UeLtePhy']) register_Ns3UeLteSpectrumPhy_methods(root_module, root_module['ns3::UeLteSpectrumPhy']) register_Ns3UeMacEntity_methods(root_module, root_module['ns3::UeMacEntity']) register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue']) register_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker']) register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue']) register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker']) register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3CqiIdealControlMessage_methods(root_module, root_module['ns3::CqiIdealControlMessage']) register_Ns3CqiIdealControlMessageCqiFeedback_methods(root_module, root_module['ns3::CqiIdealControlMessage::CqiFeedback']) register_Ns3EnbLtePhy_methods(root_module, root_module['ns3::EnbLtePhy']) register_Ns3EnbLteSpectrumPhy_methods(root_module, root_module['ns3::EnbLteSpectrumPhy']) register_Ns3EnbMacEntity_methods(root_module, root_module['ns3::EnbMacEntity']) register_Ns3LteNetDevice_methods(root_module, root_module['ns3::LteNetDevice']) register_Ns3SingleModelSpectrumChannel_methods(root_module, root_module['ns3::SingleModelSpectrumChannel']) register_Ns3UeNetDevice_methods(root_module, root_module['ns3::UeNetDevice']) register_Ns3EnbNetDevice_methods(root_module, root_module['ns3::EnbNetDevice']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_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_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_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_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_Ns3IpcsClassifierRecord_methods(root_module, cls): ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord::IpcsClassifierRecord(ns3::IpcsClassifierRecord const & arg0) [copy constructor] cls.add_constructor([param('ns3::IpcsClassifierRecord const &', 'arg0')]) ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord::IpcsClassifierRecord() [constructor] cls.add_constructor([]) ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord::IpcsClassifierRecord(ns3::Ipv4Address srcAddress, ns3::Ipv4Mask srcMask, ns3::Ipv4Address dstAddress, ns3::Ipv4Mask dstMask, uint16_t srcPortLow, uint16_t srcPortHigh, uint16_t dstPortLow, uint16_t dstPortHigh, uint8_t protocol, uint8_t priority) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'srcAddress'), param('ns3::Ipv4Mask', 'srcMask'), param('ns3::Ipv4Address', 'dstAddress'), param('ns3::Ipv4Mask', 'dstMask'), param('uint16_t', 'srcPortLow'), param('uint16_t', 'srcPortHigh'), param('uint16_t', 'dstPortLow'), param('uint16_t', 'dstPortHigh'), param('uint8_t', 'protocol'), param('uint8_t', 'priority')]) ## ipcs-classifier-record.h (module 'wimax'): ns3::IpcsClassifierRecord::IpcsClassifierRecord(ns3::Tlv tlv) [constructor] cls.add_constructor([param('ns3::Tlv', 'tlv')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddDstAddr(ns3::Ipv4Address dstAddress, ns3::Ipv4Mask dstMask) [member function] cls.add_method('AddDstAddr', 'void', [param('ns3::Ipv4Address', 'dstAddress'), param('ns3::Ipv4Mask', 'dstMask')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddDstPortRange(uint16_t dstPortLow, uint16_t dstPortHigh) [member function] cls.add_method('AddDstPortRange', 'void', [param('uint16_t', 'dstPortLow'), param('uint16_t', 'dstPortHigh')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddProtocol(uint8_t proto) [member function] cls.add_method('AddProtocol', 'void', [param('uint8_t', 'proto')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddSrcAddr(ns3::Ipv4Address srcAddress, ns3::Ipv4Mask srcMask) [member function] cls.add_method('AddSrcAddr', 'void', [param('ns3::Ipv4Address', 'srcAddress'), param('ns3::Ipv4Mask', 'srcMask')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::AddSrcPortRange(uint16_t srcPortLow, uint16_t srcPortHigh) [member function] cls.add_method('AddSrcPortRange', 'void', [param('uint16_t', 'srcPortLow'), param('uint16_t', 'srcPortHigh')]) ## ipcs-classifier-record.h (module 'wimax'): bool ns3::IpcsClassifierRecord::CheckMatch(ns3::Ipv4Address srcAddress, ns3::Ipv4Address dstAddress, uint16_t srcPort, uint16_t dstPort, uint8_t proto) const [member function] cls.add_method('CheckMatch', 'bool', [param('ns3::Ipv4Address', 'srcAddress'), param('ns3::Ipv4Address', 'dstAddress'), param('uint16_t', 'srcPort'), param('uint16_t', 'dstPort'), param('uint8_t', 'proto')], is_const=True) ## ipcs-classifier-record.h (module 'wimax'): uint16_t ns3::IpcsClassifierRecord::GetCid() const [member function] cls.add_method('GetCid', 'uint16_t', [], is_const=True) ## ipcs-classifier-record.h (module 'wimax'): uint16_t ns3::IpcsClassifierRecord::GetIndex() const [member function] cls.add_method('GetIndex', 'uint16_t', [], is_const=True) ## ipcs-classifier-record.h (module 'wimax'): uint8_t ns3::IpcsClassifierRecord::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::SetCid(uint16_t cid) [member function] cls.add_method('SetCid', 'void', [param('uint16_t', 'cid')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::SetIndex(uint16_t index) [member function] cls.add_method('SetIndex', 'void', [param('uint16_t', 'index')]) ## ipcs-classifier-record.h (module 'wimax'): void ns3::IpcsClassifierRecord::SetPriority(uint8_t prio) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'prio')]) ## ipcs-classifier-record.h (module 'wimax'): ns3::Tlv ns3::IpcsClassifierRecord::ToTlv() const [member function] cls.add_method('ToTlv', 'ns3::Tlv', [], is_const=True) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): 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::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', '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::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3LogComponent_methods(root_module, cls): ## log.h (module 'core'): ns3::LogComponent::LogComponent(ns3::LogComponent const & arg0) [copy constructor] cls.add_constructor([param('ns3::LogComponent const &', 'arg0')]) ## log.h (module 'core'): ns3::LogComponent::LogComponent(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## log.h (module 'core'): void ns3::LogComponent::Disable(ns3::LogLevel level) [member function] cls.add_method('Disable', 'void', [param('ns3::LogLevel', 'level')]) ## log.h (module 'core'): void ns3::LogComponent::Enable(ns3::LogLevel level) [member function] cls.add_method('Enable', 'void', [param('ns3::LogLevel', 'level')]) ## log.h (module 'core'): void ns3::LogComponent::EnvVarCheck(char const * name) [member function] cls.add_method('EnvVarCheck', 'void', [param('char const *', 'name')]) ## log.h (module 'core'): bool ns3::LogComponent::IsEnabled(ns3::LogLevel level) const [member function] cls.add_method('IsEnabled', 'bool', [param('ns3::LogLevel', 'level')], is_const=True) ## log.h (module 'core'): bool ns3::LogComponent::IsNoneEnabled() const [member function] cls.add_method('IsNoneEnabled', 'bool', [], is_const=True) ## log.h (module 'core'): char const * ns3::LogComponent::Name() const [member function] cls.add_method('Name', 'char const *', [], is_const=True) 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::AddDownlinkChannelRealization(ns3::Ptr<ns3::MobilityModel> enbMobility, ns3::Ptr<ns3::MobilityModel> ueMobility, ns3::Ptr<ns3::LtePhy> phy) [member function] cls.add_method('AddDownlinkChannelRealization', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'enbMobility'), param('ns3::Ptr< ns3::MobilityModel >', 'ueMobility'), param('ns3::Ptr< ns3::LtePhy >', 'phy')]) ## lte-helper.h (module 'lte'): void ns3::LteHelper::AddMobility(ns3::Ptr<ns3::LtePhy> phy, ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('AddMobility', 'void', [param('ns3::Ptr< ns3::LtePhy >', 'phy'), param('ns3::Ptr< ns3::MobilityModel >', 'm')]) ## lte-helper.h (module 'lte'): void ns3::LteHelper::EnableLogComponents() [member function] cls.add_method('EnableLogComponents', 'void', []) ## lte-helper.h (module 'lte'): ns3::NetDeviceContainer ns3::LteHelper::Install(ns3::NodeContainer c, ns3::LteHelper::NetDeviceType type) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c'), param('ns3::LteHelper::NetDeviceType', 'type')]) ## lte-helper.h (module 'lte'): void ns3::LteHelper::RegisterUeToTheEnb(ns3::Ptr<ns3::UeNetDevice> ue, ns3::Ptr<ns3::EnbNetDevice> enb) [member function] cls.add_method('RegisterUeToTheEnb', 'void', [param('ns3::Ptr< ns3::UeNetDevice >', 'ue'), param('ns3::Ptr< ns3::EnbNetDevice >', 'enb')]) 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'): ns3::Ptr<ns3::SpectrumValue> ns3::LteSpectrumValueHelper::CreateDownlinkNoisePowerSpectralDensity() [member function] cls.add_method('CreateDownlinkNoisePowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', []) ## lte-spectrum-value-helper.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::LteSpectrumValueHelper::CreateDownlinkTxPowerSpectralDensity(double powerTx, std::vector<int, std::allocator<int> > channels) [member function] cls.add_method('CreateDownlinkTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('double', 'powerTx'), param('std::vector< int >', 'channels')]) ## lte-spectrum-value-helper.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::LteSpectrumValueHelper::CreateUplinkNoisePowerSpectralDensity() [member function] cls.add_method('CreateUplinkNoisePowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', []) ## lte-spectrum-value-helper.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::LteSpectrumValueHelper::CreateUplinkTxPowerSpectralDensity(double powerTx, std::vector<int, std::allocator<int> > channels) [member function] cls.add_method('CreateUplinkTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('double', 'powerTx'), param('std::vector< int >', 'channels')]) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & 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_Ns3SeedManager_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::SeedManager::SeedManager() [constructor] cls.add_constructor([]) ## random-variable.h (module 'core'): ns3::SeedManager::SeedManager(ns3::SeedManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::SeedManager const &', 'arg0')]) ## random-variable.h (module 'core'): static bool ns3::SeedManager::CheckSeed(uint32_t seed) [member function] cls.add_method('CheckSeed', 'bool', [param('uint32_t', 'seed')], is_static=True) ## random-variable.h (module 'core'): static uint32_t ns3::SeedManager::GetRun() [member function] cls.add_method('GetRun', 'uint32_t', [], is_static=True) ## random-variable.h (module 'core'): static uint32_t ns3::SeedManager::GetSeed() [member function] cls.add_method('GetSeed', 'uint32_t', [], is_static=True) ## random-variable.h (module 'core'): static void ns3::SeedManager::SetRun(uint32_t run) [member function] cls.add_method('SetRun', 'void', [param('uint32_t', 'run')], is_static=True) ## random-variable.h (module 'core'): static void ns3::SeedManager::SetSeed(uint32_t seed) [member function] cls.add_method('SetSeed', 'void', [param('uint32_t', 'seed')], is_static=True) return def register_Ns3SequentialVariable_methods(root_module, cls): ## random-variable.h (module 'core'): ns3::SequentialVariable::SequentialVariable(ns3::SequentialVariable const & arg0) [copy constructor] cls.add_constructor([param('ns3::SequentialVariable const &', 'arg0')]) ## random-variable.h (module 'core'): ns3::SequentialVariable::SequentialVariable(double f, double l, double i=1, uint32_t c=1) [constructor] cls.add_constructor([param('double', 'f'), param('double', 'l'), param('double', 'i', default_value='1'), param('uint32_t', 'c', default_value='1')]) ## random-variable.h (module 'core'): ns3::SequentialVariable::SequentialVariable(double f, double l, ns3::RandomVariable const & i, uint32_t c=1) [constructor] cls.add_constructor([param('double', 'f'), param('double', 'l'), param('ns3::RandomVariable const &', 'i'), param('uint32_t', 'c', default_value='1')]) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_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_Ns3TlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::TlvValue::TlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::TlvValue::TlvValue(ns3::TlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::TlvValue * ns3::TlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::TlvValue *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::TlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLen) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLen')], is_pure_virtual=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::TlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::TlvValue::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_Ns3TosTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue::TosTlvValue(ns3::TosTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TosTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue::TosTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue::TosTlvValue(uint8_t arg0, uint8_t arg1, uint8_t arg2) [constructor] cls.add_constructor([param('uint8_t', 'arg0'), param('uint8_t', 'arg1'), param('uint8_t', 'arg2')]) ## wimax-tlv.h (module 'wimax'): ns3::TosTlvValue * ns3::TosTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::TosTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::TosTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::TosTlvValue::GetHigh() const [member function] cls.add_method('GetHigh', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::TosTlvValue::GetLow() const [member function] cls.add_method('GetLow', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::TosTlvValue::GetMask() const [member function] cls.add_method('GetMask', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::TosTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::TosTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_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')], 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_Ns3U16TlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue::U16TlvValue(ns3::U16TlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::U16TlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue::U16TlvValue(uint16_t value) [constructor] cls.add_constructor([param('uint16_t', 'value')]) ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue::U16TlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::U16TlvValue * ns3::U16TlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::U16TlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U16TlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLen) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLen')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U16TlvValue::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')]) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U16TlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint16_t ns3::U16TlvValue::GetValue() const [member function] cls.add_method('GetValue', 'uint16_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): void ns3::U16TlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3U32TlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue::U32TlvValue(ns3::U32TlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::U32TlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue::U32TlvValue(uint32_t value) [constructor] cls.add_constructor([param('uint32_t', 'value')]) ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue::U32TlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::U32TlvValue * ns3::U32TlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::U32TlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U32TlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLen) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLen')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U32TlvValue::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')]) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U32TlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U32TlvValue::GetValue() const [member function] cls.add_method('GetValue', 'uint32_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): void ns3::U32TlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3U8TlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue::U8TlvValue(ns3::U8TlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::U8TlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue::U8TlvValue(uint8_t value) [constructor] cls.add_constructor([param('uint8_t', 'value')]) ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue::U8TlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::U8TlvValue * ns3::U8TlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::U8TlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U8TlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLen) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLen')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U8TlvValue::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')]) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::U8TlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::U8TlvValue::GetValue() const [member function] cls.add_method('GetValue', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): void ns3::U8TlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_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_Ns3VectorTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::VectorTlvValue::VectorTlvValue(ns3::VectorTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::VectorTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::VectorTlvValue::VectorTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): void ns3::VectorTlvValue::Add(ns3::Tlv const & val) [member function] cls.add_method('Add', 'void', [param('ns3::Tlv const &', 'val')]) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<ns3::Tlv* const*,std::vector<ns3::Tlv*, std::allocator<ns3::Tlv*> > > ns3::VectorTlvValue::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Tlv * const *, std::vector< ns3::Tlv * > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::VectorTlvValue * ns3::VectorTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::VectorTlvValue *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::VectorTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_pure_virtual=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<ns3::Tlv* const*,std::vector<ns3::Tlv*, std::allocator<ns3::Tlv*> > > ns3::VectorTlvValue::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Tlv * const *, std::vector< ns3::Tlv * > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::VectorTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::VectorTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_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_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_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_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3ClassificationRuleVectorTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue::ClassificationRuleVectorTlvValue(ns3::ClassificationRuleVectorTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ClassificationRuleVectorTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue::ClassificationRuleVectorTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::ClassificationRuleVectorTlvValue * ns3::ClassificationRuleVectorTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::ClassificationRuleVectorTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::ClassificationRuleVectorTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], 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_Ns3CsParamVectorTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue::CsParamVectorTlvValue(ns3::CsParamVectorTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CsParamVectorTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue::CsParamVectorTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::CsParamVectorTlvValue * ns3::CsParamVectorTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::CsParamVectorTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::CsParamVectorTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) 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_Ns3Ipv4AddressTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::Ipv4AddressTlvValue(ns3::Ipv4AddressTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::Ipv4AddressTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): void ns3::Ipv4AddressTlvValue::Add(ns3::Ipv4Address address, ns3::Ipv4Mask Mask) [member function] cls.add_method('Add', 'void', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'Mask')]) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const ns3::Ipv4AddressTlvValue::ipv4Addr*,std::vector<ns3::Ipv4AddressTlvValue::ipv4Addr, std::allocator<ns3::Ipv4AddressTlvValue::ipv4Addr> > > ns3::Ipv4AddressTlvValue::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ipv4AddressTlvValue::ipv4Addr const *, std::vector< ns3::Ipv4AddressTlvValue::ipv4Addr > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue * ns3::Ipv4AddressTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ipv4AddressTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::Ipv4AddressTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const ns3::Ipv4AddressTlvValue::ipv4Addr*,std::vector<ns3::Ipv4AddressTlvValue::ipv4Addr, std::allocator<ns3::Ipv4AddressTlvValue::ipv4Addr> > > ns3::Ipv4AddressTlvValue::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ipv4AddressTlvValue::ipv4Addr const *, std::vector< ns3::Ipv4AddressTlvValue::ipv4Addr > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::Ipv4AddressTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::Ipv4AddressTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3Ipv4AddressTlvValueIpv4Addr_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr::ipv4Addr() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr::ipv4Addr(ns3::Ipv4AddressTlvValue::ipv4Addr const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressTlvValue::ipv4Addr const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr::Address [variable] cls.add_instance_attribute('Address', 'ns3::Ipv4Address', is_const=False) ## wimax-tlv.h (module 'wimax'): ns3::Ipv4AddressTlvValue::ipv4Addr::Mask [variable] cls.add_instance_attribute('Mask', 'ns3::Ipv4Mask', is_const=False) 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_Ns3LteMacHeader_methods(root_module, cls): ## lte-mac-header.h (module 'lte'): ns3::LteMacHeader::LteMacHeader() [constructor] cls.add_constructor([]) ## lte-mac-header.h (module 'lte'): ns3::LteMacHeader::LteMacHeader(ns3::LteMacHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::LteMacHeader const &', 'arg0')]) ## lte-mac-header.h (module 'lte'): uint32_t ns3::LteMacHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## lte-mac-header.h (module 'lte'): ns3::Mac48Address ns3::LteMacHeader::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Mac48Address', [], is_const=True) ## lte-mac-header.h (module 'lte'): ns3::TypeId ns3::LteMacHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## lte-mac-header.h (module 'lte'): uint32_t ns3::LteMacHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## lte-mac-header.h (module 'lte'): ns3::Mac48Address ns3::LteMacHeader::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Mac48Address', [], is_const=True) ## lte-mac-header.h (module 'lte'): static ns3::TypeId ns3::LteMacHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## lte-mac-header.h (module 'lte'): void ns3::LteMacHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## lte-mac-header.h (module 'lte'): void ns3::LteMacHeader::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-mac-header.h (module 'lte'): void ns3::LteMacHeader::SetDestination(ns3::Mac48Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Mac48Address', 'destination')]) ## lte-mac-header.h (module 'lte'): void ns3::LteMacHeader::SetSource(ns3::Mac48Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Mac48Address', 'source')]) 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_Ns3PacketScheduler_methods(root_module, cls): ## packet-scheduler.h (module 'lte'): ns3::PacketScheduler::PacketScheduler(ns3::PacketScheduler const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketScheduler const &', 'arg0')]) ## packet-scheduler.h (module 'lte'): ns3::PacketScheduler::PacketScheduler() [constructor] cls.add_constructor([]) ## packet-scheduler.h (module 'lte'): ns3::PacketScheduler::PacketScheduler(ns3::Ptr<ns3::EnbNetDevice> enb) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EnbNetDevice >', 'enb')]) ## packet-scheduler.h (module 'lte'): void ns3::PacketScheduler::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## packet-scheduler.h (module 'lte'): void ns3::PacketScheduler::DoRunPacketScheduler() [member function] cls.add_method('DoRunPacketScheduler', 'void', [], is_pure_virtual=True, is_virtual=True) ## packet-scheduler.h (module 'lte'): ns3::Ptr<ns3::EnbNetDevice> ns3::PacketScheduler::GetDevice() [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::EnbNetDevice >', []) ## packet-scheduler.h (module 'lte'): ns3::Ptr<ns3::MacEntity> ns3::PacketScheduler::GetMacEntity() [member function] cls.add_method('GetMacEntity', 'ns3::Ptr< ns3::MacEntity >', []) ## packet-scheduler.h (module 'lte'): static ns3::TypeId ns3::PacketScheduler::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-scheduler.h (module 'lte'): void ns3::PacketScheduler::RunPacketScheduler() [member function] cls.add_method('RunPacketScheduler', 'void', []) ## packet-scheduler.h (module 'lte'): void ns3::PacketScheduler::SetDevice(ns3::Ptr<ns3::EnbNetDevice> enb) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::EnbNetDevice >', 'enb')]) ## packet-scheduler.h (module 'lte'): void ns3::PacketScheduler::SetMacEntity(ns3::Ptr<ns3::MacEntity> mac) [member function] cls.add_method('SetMacEntity', 'void', [param('ns3::Ptr< ns3::MacEntity >', 'mac')]) 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_Ns3PortRangeTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRangeTlvValue(ns3::PortRangeTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::PortRangeTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRangeTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): void ns3::PortRangeTlvValue::Add(uint16_t portLow, uint16_t portHigh) [member function] cls.add_method('Add', 'void', [param('uint16_t', 'portLow'), param('uint16_t', 'portHigh')]) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const ns3::PortRangeTlvValue::PortRange*,std::vector<ns3::PortRangeTlvValue::PortRange, std::allocator<ns3::PortRangeTlvValue::PortRange> > > ns3::PortRangeTlvValue::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::PortRangeTlvValue::PortRange const *, std::vector< ns3::PortRangeTlvValue::PortRange > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue * ns3::PortRangeTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::PortRangeTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::PortRangeTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const ns3::PortRangeTlvValue::PortRange*,std::vector<ns3::PortRangeTlvValue::PortRange, std::allocator<ns3::PortRangeTlvValue::PortRange> > > ns3::PortRangeTlvValue::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::PortRangeTlvValue::PortRange const *, std::vector< ns3::PortRangeTlvValue::PortRange > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::PortRangeTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::PortRangeTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3PortRangeTlvValuePortRange_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange::PortRange() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange::PortRange(ns3::PortRangeTlvValue::PortRange const & arg0) [copy constructor] cls.add_constructor([param('ns3::PortRangeTlvValue::PortRange const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange::PortHigh [variable] cls.add_instance_attribute('PortHigh', 'uint16_t', is_const=False) ## wimax-tlv.h (module 'wimax'): ns3::PortRangeTlvValue::PortRange::PortLow [variable] cls.add_instance_attribute('PortLow', 'uint16_t', is_const=False) return def register_Ns3ProtocolTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::ProtocolTlvValue::ProtocolTlvValue(ns3::ProtocolTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ProtocolTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::ProtocolTlvValue::ProtocolTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): void ns3::ProtocolTlvValue::Add(uint8_t protiocol) [member function] cls.add_method('Add', 'void', [param('uint8_t', 'protiocol')]) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const unsigned char*,std::vector<unsigned char, std::allocator<unsigned char> > > ns3::ProtocolTlvValue::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::ProtocolTlvValue * ns3::ProtocolTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::ProtocolTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::ProtocolTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): __gnu_cxx::__normal_iterator<const unsigned char*,std::vector<unsigned char, std::allocator<unsigned char> > > ns3::ProtocolTlvValue::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char > >', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::ProtocolTlvValue::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::ProtocolTlvValue::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3RadioBearerInstance_methods(root_module, cls): ## radio-bearer-instance.h (module 'lte'): ns3::RadioBearerInstance::RadioBearerInstance(ns3::RadioBearerInstance const & arg0) [copy constructor] cls.add_constructor([param('ns3::RadioBearerInstance const &', 'arg0')]) ## radio-bearer-instance.h (module 'lte'): ns3::RadioBearerInstance::RadioBearerInstance() [constructor] cls.add_constructor([]) ## radio-bearer-instance.h (module 'lte'): ns3::Ptr<ns3::Packet> ns3::RadioBearerInstance::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', []) ## radio-bearer-instance.h (module 'lte'): ns3::Ptr<ns3::Packet> ns3::RadioBearerInstance::Dequeue(uint32_t availableByte) [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'availableByte')]) ## radio-bearer-instance.h (module 'lte'): bool ns3::RadioBearerInstance::Enqueue(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet')]) ## radio-bearer-instance.h (module 'lte'): ns3::RadioBearerInstance::BearerDirection ns3::RadioBearerInstance::GetBearerDirection() const [member function] cls.add_method('GetBearerDirection', 'ns3::RadioBearerInstance::BearerDirection', [], is_const=True) ## radio-bearer-instance.h (module 'lte'): ns3::RadioBearerInstance::BearerType ns3::RadioBearerInstance::GetBearerType() const [member function] cls.add_method('GetBearerType', 'ns3::RadioBearerInstance::BearerType', [], is_const=True) ## radio-bearer-instance.h (module 'lte'): ns3::IpcsClassifierRecord * ns3::RadioBearerInstance::GetIpcsClassifierRecord() [member function] cls.add_method('GetIpcsClassifierRecord', 'ns3::IpcsClassifierRecord *', []) ## radio-bearer-instance.h (module 'lte'): ns3::Ptr<ns3::BearerQosParameters> ns3::RadioBearerInstance::GetQosParameters() [member function] cls.add_method('GetQosParameters', 'ns3::Ptr< ns3::BearerQosParameters >', []) ## radio-bearer-instance.h (module 'lte'): ns3::Ptr<ns3::LteMacQueue> ns3::RadioBearerInstance::GetQueue() const [member function] cls.add_method('GetQueue', 'ns3::Ptr< ns3::LteMacQueue >', [], is_const=True) ## radio-bearer-instance.h (module 'lte'): ns3::Ptr<ns3::RlcEntity> ns3::RadioBearerInstance::GetRlcEntity() [member function] cls.add_method('GetRlcEntity', 'ns3::Ptr< ns3::RlcEntity >', []) ## radio-bearer-instance.h (module 'lte'): static ns3::TypeId ns3::RadioBearerInstance::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## radio-bearer-instance.h (module 'lte'): bool ns3::RadioBearerInstance::HasPackets() const [member function] cls.add_method('HasPackets', 'bool', [], is_const=True) ## radio-bearer-instance.h (module 'lte'): void ns3::RadioBearerInstance::SetBearerDirection(ns3::RadioBearerInstance::BearerDirection direction) [member function] cls.add_method('SetBearerDirection', 'void', [param('ns3::RadioBearerInstance::BearerDirection', 'direction')]) ## radio-bearer-instance.h (module 'lte'): void ns3::RadioBearerInstance::SetBearerType(ns3::RadioBearerInstance::BearerType type) [member function] cls.add_method('SetBearerType', 'void', [param('ns3::RadioBearerInstance::BearerType', 'type')]) ## radio-bearer-instance.h (module 'lte'): void ns3::RadioBearerInstance::SetIpcsClassifierRecord(ns3::IpcsClassifierRecord * c) [member function] cls.add_method('SetIpcsClassifierRecord', 'void', [param('ns3::IpcsClassifierRecord *', 'c')]) ## radio-bearer-instance.h (module 'lte'): void ns3::RadioBearerInstance::SetQosParameters(ns3::Ptr<ns3::BearerQosParameters> qosParameters) [member function] cls.add_method('SetQosParameters', 'void', [param('ns3::Ptr< ns3::BearerQosParameters >', 'qosParameters')]) ## radio-bearer-instance.h (module 'lte'): void ns3::RadioBearerInstance::SetRlcEntity(ns3::Ptr<ns3::RlcEntity> rlc) [member function] cls.add_method('SetRlcEntity', 'void', [param('ns3::Ptr< ns3::RlcEntity >', 'rlc')]) ## radio-bearer-instance.h (module 'lte'): void ns3::RadioBearerInstance::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3RlcEntity_methods(root_module, cls): ## rlc-entity.h (module 'lte'): ns3::RlcEntity::RlcEntity(ns3::RlcEntity const & arg0) [copy constructor] cls.add_constructor([param('ns3::RlcEntity const &', 'arg0')]) ## rlc-entity.h (module 'lte'): ns3::RlcEntity::RlcEntity() [constructor] cls.add_constructor([]) ## rlc-entity.h (module 'lte'): ns3::RlcEntity::RlcEntity(ns3::Ptr<ns3::LteNetDevice> d) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::LteNetDevice >', 'd')]) ## rlc-entity.h (module 'lte'): ns3::Ptr<ns3::Packet> ns3::RlcEntity::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', []) ## rlc-entity.h (module 'lte'): void ns3::RlcEntity::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## rlc-entity.h (module 'lte'): ns3::Ptr<ns3::LteNetDevice> ns3::RlcEntity::GetDevice() [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::LteNetDevice >', []) ## rlc-entity.h (module 'lte'): ns3::Ptr<ns3::RadioBearerInstance> ns3::RlcEntity::GetRadioBearer() [member function] cls.add_method('GetRadioBearer', 'ns3::Ptr< ns3::RadioBearerInstance >', []) ## rlc-entity.h (module 'lte'): static ns3::TypeId ns3::RlcEntity::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## rlc-entity.h (module 'lte'): void ns3::RlcEntity::SetDevice(ns3::Ptr<ns3::LteNetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::LteNetDevice >', 'd')]) ## rlc-entity.h (module 'lte'): void ns3::RlcEntity::SetRadioBearer(ns3::Ptr<ns3::RadioBearerInstance> b) [member function] cls.add_method('SetRadioBearer', 'void', [param('ns3::Ptr< ns3::RadioBearerInstance >', 'b')]) return def register_Ns3RrcEntity_methods(root_module, cls): ## rrc-entity.h (module 'lte'): ns3::RrcEntity::RrcEntity(ns3::RrcEntity const & arg0) [copy constructor] cls.add_constructor([param('ns3::RrcEntity const &', 'arg0')]) ## rrc-entity.h (module 'lte'): ns3::RrcEntity::RrcEntity() [constructor] cls.add_constructor([]) ## rrc-entity.h (module 'lte'): void ns3::RrcEntity::AddDownlinkGbrBearer(ns3::Ptr<ns3::RadioBearerInstance> bearer) [member function] cls.add_method('AddDownlinkGbrBearer', 'void', [param('ns3::Ptr< ns3::RadioBearerInstance >', 'bearer')]) ## rrc-entity.h (module 'lte'): void ns3::RrcEntity::AddDownlinkNgbrBearer(ns3::Ptr<ns3::RadioBearerInstance> bearer) [member function] cls.add_method('AddDownlinkNgbrBearer', 'void', [param('ns3::Ptr< ns3::RadioBearerInstance >', 'bearer')]) ## rrc-entity.h (module 'lte'): void ns3::RrcEntity::AddUplinkGbrBearer(ns3::Ptr<ns3::RadioBearerInstance> bearer) [member function] cls.add_method('AddUplinkGbrBearer', 'void', [param('ns3::Ptr< ns3::RadioBearerInstance >', 'bearer')]) ## rrc-entity.h (module 'lte'): void ns3::RrcEntity::AddUplinkNgbrBearer(ns3::Ptr<ns3::RadioBearerInstance> bearer) [member function] cls.add_method('AddUplinkNgbrBearer', 'void', [param('ns3::Ptr< ns3::RadioBearerInstance >', 'bearer')]) ## rrc-entity.h (module 'lte'): ns3::Ptr<ns3::RadioBearerInstance> ns3::RrcEntity::Classify(ns3::Ptr<ns3::Packet> p) const [member function] cls.add_method('Classify', 'ns3::Ptr< ns3::RadioBearerInstance >', [param('ns3::Ptr< ns3::Packet >', 'p')], is_const=True) ## rrc-entity.h (module 'lte'): void ns3::RrcEntity::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## rrc-entity.h (module 'lte'): ns3::Ptr<ns3::RadioBearerInstance> ns3::RrcEntity::GetDefaultBearer() [member function] cls.add_method('GetDefaultBearer', 'ns3::Ptr< ns3::RadioBearerInstance >', []) ## rrc-entity.h (module 'lte'): std::vector<ns3::Ptr<ns3::RadioBearerInstance>,std::allocator<ns3::Ptr<ns3::RadioBearerInstance> > > * ns3::RrcEntity::GetDownlinkGbrBearers() const [member function] cls.add_method('GetDownlinkGbrBearers', 'std::vector< ns3::Ptr< ns3::RadioBearerInstance > > *', [], is_const=True) ## rrc-entity.h (module 'lte'): std::vector<ns3::Ptr<ns3::RadioBearerInstance>,std::allocator<ns3::Ptr<ns3::RadioBearerInstance> > > * ns3::RrcEntity::GetDownlinkNgbrBearers() const [member function] cls.add_method('GetDownlinkNgbrBearers', 'std::vector< ns3::Ptr< ns3::RadioBearerInstance > > *', [], is_const=True) ## rrc-entity.h (module 'lte'): static ns3::TypeId ns3::RrcEntity::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## rrc-entity.h (module 'lte'): std::vector<ns3::Ptr<ns3::RadioBearerInstance>,std::allocator<ns3::Ptr<ns3::RadioBearerInstance> > > * ns3::RrcEntity::GetUplinkGbrBearers() const [member function] cls.add_method('GetUplinkGbrBearers', 'std::vector< ns3::Ptr< ns3::RadioBearerInstance > > *', [], is_const=True) ## rrc-entity.h (module 'lte'): std::vector<ns3::Ptr<ns3::RadioBearerInstance>,std::allocator<ns3::Ptr<ns3::RadioBearerInstance> > > * ns3::RrcEntity::GetUplinkNgbrBearers() const [member function] cls.add_method('GetUplinkNgbrBearers', 'std::vector< ns3::Ptr< ns3::RadioBearerInstance > > *', [], is_const=True) return def register_Ns3SfVectorTlvValue_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue::SfVectorTlvValue(ns3::SfVectorTlvValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::SfVectorTlvValue const &', 'arg0')]) ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue::SfVectorTlvValue() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::SfVectorTlvValue * ns3::SfVectorTlvValue::Copy() const [member function] cls.add_method('Copy', 'ns3::SfVectorTlvValue *', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::SfVectorTlvValue::Deserialize(ns3::Buffer::Iterator start, uint64_t valueLength) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('uint64_t', 'valueLength')], is_virtual=True) return def register_Ns3SimplePacketScheduler_methods(root_module, cls): ## simple-packet-scheduler.h (module 'lte'): ns3::SimplePacketScheduler::SimplePacketScheduler(ns3::SimplePacketScheduler const & arg0) [copy constructor] cls.add_constructor([param('ns3::SimplePacketScheduler const &', 'arg0')]) ## simple-packet-scheduler.h (module 'lte'): ns3::SimplePacketScheduler::SimplePacketScheduler() [constructor] cls.add_constructor([]) ## simple-packet-scheduler.h (module 'lte'): ns3::SimplePacketScheduler::SimplePacketScheduler(ns3::Ptr<ns3::EnbNetDevice> enb) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EnbNetDevice >', 'enb')]) ## simple-packet-scheduler.h (module 'lte'): void ns3::SimplePacketScheduler::DoRunPacketScheduler() [member function] cls.add_method('DoRunPacketScheduler', 'void', [], is_virtual=True) ## simple-packet-scheduler.h (module 'lte'): static ns3::TypeId ns3::SimplePacketScheduler::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__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__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_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'): ns3::SpectrumPhy::SpectrumPhy(ns3::SpectrumPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumPhy const &', 'arg0')]) ## 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'): 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'): 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'): 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::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'): 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'): 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'): 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::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_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_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) 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_Ns3Tlv_methods(root_module, cls): ## wimax-tlv.h (module 'wimax'): ns3::Tlv::Tlv(uint8_t type, uint64_t length, ns3::TlvValue const & value) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint64_t', 'length'), param('ns3::TlvValue const &', 'value')]) ## wimax-tlv.h (module 'wimax'): ns3::Tlv::Tlv() [constructor] cls.add_constructor([]) ## wimax-tlv.h (module 'wimax'): ns3::Tlv::Tlv(ns3::Tlv const & tlv) [copy constructor] cls.add_constructor([param('ns3::Tlv const &', 'tlv')]) ## wimax-tlv.h (module 'wimax'): ns3::Tlv * ns3::Tlv::Copy() const [member function] cls.add_method('Copy', 'ns3::Tlv *', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::TlvValue * ns3::Tlv::CopyValue() const [member function] cls.add_method('CopyValue', 'ns3::TlvValue *', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::Tlv::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wimax-tlv.h (module 'wimax'): ns3::TypeId ns3::Tlv::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint64_t ns3::Tlv::GetLength() const [member function] cls.add_method('GetLength', 'uint64_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint32_t ns3::Tlv::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::Tlv::GetSizeOfLen() const [member function] cls.add_method('GetSizeOfLen', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): uint8_t ns3::Tlv::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## wimax-tlv.h (module 'wimax'): ns3::TlvValue * ns3::Tlv::PeekValue() [member function] cls.add_method('PeekValue', 'ns3::TlvValue *', []) ## wimax-tlv.h (module 'wimax'): void ns3::Tlv::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wimax-tlv.h (module 'wimax'): void ns3::Tlv::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_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_Ns3UeManager_methods(root_module, cls): ## ue-manager.h (module 'lte'): ns3::UeManager::UeManager(ns3::UeManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::UeManager const &', 'arg0')]) ## ue-manager.h (module 'lte'): ns3::UeManager::UeManager() [constructor] cls.add_constructor([]) ## ue-manager.h (module 'lte'): void ns3::UeManager::CreateUeRecord(ns3::Ptr<ns3::UeNetDevice> ue, ns3::Ptr<ns3::EnbNetDevice> enb) [member function] cls.add_method('CreateUeRecord', 'void', [param('ns3::Ptr< ns3::UeNetDevice >', 'ue'), param('ns3::Ptr< ns3::EnbNetDevice >', 'enb')]) ## ue-manager.h (module 'lte'): void ns3::UeManager::DeleteUeRecord(ns3::Ptr<ns3::UeNetDevice> ue) [member function] cls.add_method('DeleteUeRecord', 'void', [param('ns3::Ptr< ns3::UeNetDevice >', 'ue')]) ## ue-manager.h (module 'lte'): void ns3::UeManager::DeleteUeRecord(ns3::Mac48Address const & macAddress) [member function] cls.add_method('DeleteUeRecord', 'void', [param('ns3::Mac48Address const &', 'macAddress')]) ## ue-manager.h (module 'lte'): uint32_t ns3::UeManager::GetNRegisteredUes() const [member function] cls.add_method('GetNRegisteredUes', 'uint32_t', [], is_const=True) ## ue-manager.h (module 'lte'): ns3::Ptr<ns3::UeRecord> ns3::UeManager::GetUeRecord(ns3::Ptr<ns3::UeNetDevice> ue) [member function] cls.add_method('GetUeRecord', 'ns3::Ptr< ns3::UeRecord >', [param('ns3::Ptr< ns3::UeNetDevice >', 'ue')]) ## ue-manager.h (module 'lte'): ns3::Ptr<ns3::UeRecord> ns3::UeManager::GetUeRecord(ns3::Mac48Address const macAddress) [member function] cls.add_method('GetUeRecord', 'ns3::Ptr< ns3::UeRecord >', [param('ns3::Mac48Address const', 'macAddress')]) ## ue-manager.h (module 'lte'): std::vector<ns3::Ptr<ns3::UeRecord>,std::allocator<ns3::Ptr<ns3::UeRecord> > > * ns3::UeManager::GetUeRecords() [member function] cls.add_method('GetUeRecords', 'std::vector< ns3::Ptr< ns3::UeRecord > > *', []) ## ue-manager.h (module 'lte'): bool ns3::UeManager::IsRegistered(ns3::Ptr<ns3::UeNetDevice> ue) const [member function] cls.add_method('IsRegistered', 'bool', [param('ns3::Ptr< ns3::UeNetDevice >', 'ue')], is_const=True) ## ue-manager.h (module 'lte'): bool ns3::UeManager::IsRegistered(ns3::Mac48Address const & macAddress) const [member function] cls.add_method('IsRegistered', 'bool', [param('ns3::Mac48Address const &', 'macAddress')], is_const=True) return def register_Ns3UeRecord_methods(root_module, cls): ## ue-record.h (module 'lte'): ns3::UeRecord::UeRecord(ns3::UeRecord const & arg0) [copy constructor] cls.add_constructor([param('ns3::UeRecord const &', 'arg0')]) ## ue-record.h (module 'lte'): ns3::UeRecord::UeRecord() [constructor] cls.add_constructor([]) ## ue-record.h (module 'lte'): ns3::UeRecord::UeRecord(ns3::Ptr<ns3::NetDevice> ue, ns3::Ptr<ns3::NetDevice> enb) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'ue'), param('ns3::Ptr< ns3::NetDevice >', 'enb')]) ## ue-record.h (module 'lte'): std::vector<ns3::UeRecord::CqiFeedback, std::allocator<ns3::UeRecord::CqiFeedback> > ns3::UeRecord::GetCqiFeedbacks() [member function] cls.add_method('GetCqiFeedbacks', 'std::vector< ns3::UeRecord::CqiFeedback >', []) ## ue-record.h (module 'lte'): ns3::Ptr<ns3::NetDevice> ns3::UeRecord::GetEnb() [member function] cls.add_method('GetEnb', 'ns3::Ptr< ns3::NetDevice >', []) ## ue-record.h (module 'lte'): ns3::Ptr<ns3::NetDevice> ns3::UeRecord::GetUe() [member function] cls.add_method('GetUe', 'ns3::Ptr< ns3::NetDevice >', []) ## ue-record.h (module 'lte'): void ns3::UeRecord::SetCqiFeedbacks(std::vector<ns3::UeRecord::CqiFeedback, std::allocator<ns3::UeRecord::CqiFeedback> > cqiFeedbacks) [member function] cls.add_method('SetCqiFeedbacks', 'void', [param('std::vector< ns3::UeRecord::CqiFeedback >', 'cqiFeedbacks')]) ## ue-record.h (module 'lte'): void ns3::UeRecord::SetEnb(ns3::Ptr<ns3::NetDevice> enb) [member function] cls.add_method('SetEnb', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'enb')]) ## ue-record.h (module 'lte'): void ns3::UeRecord::SetUe(ns3::Ptr<ns3::NetDevice> ue) [member function] cls.add_method('SetUe', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'ue')]) return def register_Ns3UeRecordCqiFeedback_methods(root_module, cls): ## ue-record.h (module 'lte'): ns3::UeRecord::CqiFeedback::CqiFeedback() [constructor] cls.add_constructor([]) ## ue-record.h (module 'lte'): ns3::UeRecord::CqiFeedback::CqiFeedback(ns3::UeRecord::CqiFeedback const & arg0) [copy constructor] cls.add_constructor([param('ns3::UeRecord::CqiFeedback const &', 'arg0')]) ## ue-record.h (module 'lte'): ns3::UeRecord::CqiFeedback::m_cqi [variable] cls.add_instance_attribute('m_cqi', 'int', is_const=False) ## ue-record.h (module 'lte'): ns3::UeRecord::CqiFeedback::m_subChannelId [variable] cls.add_instance_attribute('m_subChannelId', 'int', is_const=False) return def register_Ns3AmcModule_methods(root_module, cls): ## amc-module.h (module 'lte'): ns3::AmcModule::AmcModule(ns3::AmcModule const & arg0) [copy constructor] cls.add_constructor([param('ns3::AmcModule const &', 'arg0')]) ## amc-module.h (module 'lte'): ns3::AmcModule::AmcModule() [constructor] cls.add_constructor([]) ## amc-module.h (module 'lte'): std::vector<int, std::allocator<int> > ns3::AmcModule::CreateCqiFeedbacks(std::vector<double, std::allocator<double> > sinr) [member function] cls.add_method('CreateCqiFeedbacks', 'std::vector< int >', [param('std::vector< double >', 'sinr')]) ## amc-module.h (module 'lte'): int ns3::AmcModule::GetMcsFromCqi(int cqi) [member function] cls.add_method('GetMcsFromCqi', 'int', [param('int', 'cqi')]) ## amc-module.h (module 'lte'): double ns3::AmcModule::GetSpectralEfficiencyFromCqi(int cqi) [member function] cls.add_method('GetSpectralEfficiencyFromCqi', 'double', [param('int', 'cqi')]) ## amc-module.h (module 'lte'): int ns3::AmcModule::GetTbSizeFromMcs(int mcs) [member function] cls.add_method('GetTbSizeFromMcs', 'int', [param('int', 'mcs')]) ## amc-module.h (module 'lte'): static ns3::TypeId ns3::AmcModule::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## amc-module.h (module 'lte'): void ns3::AmcModule::Initialize() [member function] cls.add_method('Initialize', 'void', []) 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_Ns3BearerQosParameters_methods(root_module, cls): ## bearer-qos-parameters.h (module 'lte'): ns3::BearerQosParameters::BearerQosParameters(ns3::BearerQosParameters const & arg0) [copy constructor] cls.add_constructor([param('ns3::BearerQosParameters const &', 'arg0')]) ## bearer-qos-parameters.h (module 'lte'): ns3::BearerQosParameters::BearerQosParameters() [constructor] cls.add_constructor([]) ## bearer-qos-parameters.h (module 'lte'): ns3::BearerQosParameters::BearerQosParameters(int qci, double gbr, double mbr) [constructor] cls.add_constructor([param('int', 'qci'), param('double', 'gbr'), param('double', 'mbr')]) ## bearer-qos-parameters.h (module 'lte'): ns3::BearerQosParameters::BearerQosParameters(int qci, bool apec, bool apev, double gbr, double mbr) [constructor] cls.add_constructor([param('int', 'qci'), param('bool', 'apec'), param('bool', 'apev'), param('double', 'gbr'), param('double', 'mbr')]) ## bearer-qos-parameters.h (module 'lte'): bool ns3::BearerQosParameters::GetArpPreEmptionCapability() const [member function] cls.add_method('GetArpPreEmptionCapability', 'bool', [], is_const=True) ## bearer-qos-parameters.h (module 'lte'): bool ns3::BearerQosParameters::GetArpPreEmptionVulnerability() const [member function] cls.add_method('GetArpPreEmptionVulnerability', 'bool', [], is_const=True) ## bearer-qos-parameters.h (module 'lte'): ns3::BearerQosParameters::BearerQosType ns3::BearerQosParameters::GetBearerQosType() const [member function] cls.add_method('GetBearerQosType', 'ns3::BearerQosParameters::BearerQosType', [], is_const=True) ## bearer-qos-parameters.h (module 'lte'): double ns3::BearerQosParameters::GetGbr() const [member function] cls.add_method('GetGbr', 'double', [], is_const=True) ## bearer-qos-parameters.h (module 'lte'): double ns3::BearerQosParameters::GetMaxDelay() const [member function] cls.add_method('GetMaxDelay', 'double', [], is_const=True) ## bearer-qos-parameters.h (module 'lte'): double ns3::BearerQosParameters::GetMbr() const [member function] cls.add_method('GetMbr', 'double', [], is_const=True) ## bearer-qos-parameters.h (module 'lte'): int ns3::BearerQosParameters::GetQci() const [member function] cls.add_method('GetQci', 'int', [], is_const=True) ## bearer-qos-parameters.h (module 'lte'): void ns3::BearerQosParameters::SetArpPreEmptionCapability(bool apec) [member function] cls.add_method('SetArpPreEmptionCapability', 'void', [param('bool', 'apec')]) ## bearer-qos-parameters.h (module 'lte'): void ns3::BearerQosParameters::SetArpPreEmptionVulnerability(bool apev) [member function] cls.add_method('SetArpPreEmptionVulnerability', 'void', [param('bool', 'apev')]) ## bearer-qos-parameters.h (module 'lte'): void ns3::BearerQosParameters::SetBearerQosType(ns3::BearerQosParameters::BearerQosType QosType) [member function] cls.add_method('SetBearerQosType', 'void', [param('ns3::BearerQosParameters::BearerQosType', 'QosType')]) ## bearer-qos-parameters.h (module 'lte'): void ns3::BearerQosParameters::SetGbr(double gbr) [member function] cls.add_method('SetGbr', 'void', [param('double', 'gbr')]) ## bearer-qos-parameters.h (module 'lte'): void ns3::BearerQosParameters::SetMaxDelay(double targetDelay) [member function] cls.add_method('SetMaxDelay', 'void', [param('double', 'targetDelay')]) ## bearer-qos-parameters.h (module 'lte'): void ns3::BearerQosParameters::SetMbr(double mbr) [member function] cls.add_method('SetMbr', 'void', [param('double', 'mbr')]) ## bearer-qos-parameters.h (module 'lte'): void ns3::BearerQosParameters::SetQci(int qci) [member function] cls.add_method('SetQci', 'void', [param('int', 'qci')]) 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_Ns3ChannelRealization_methods(root_module, cls): ## channel-realization.h (module 'lte'): ns3::ChannelRealization::ChannelRealization(ns3::ChannelRealization const & arg0) [copy constructor] cls.add_constructor([param('ns3::ChannelRealization const &', 'arg0')]) ## channel-realization.h (module 'lte'): ns3::ChannelRealization::ChannelRealization() [constructor] cls.add_constructor([]) ## channel-realization.h (module 'lte'): ns3::Ptr<ns3::JakesFadingLossModel> ns3::ChannelRealization::GetJakesFadingLossModel() [member function] cls.add_method('GetJakesFadingLossModel', 'ns3::Ptr< ns3::JakesFadingLossModel >', []) ## channel-realization.h (module 'lte'): ns3::Ptr<ns3::PathLossModel> ns3::ChannelRealization::GetPathLossModel() [member function] cls.add_method('GetPathLossModel', 'ns3::Ptr< ns3::PathLossModel >', []) ## channel-realization.h (module 'lte'): ns3::Ptr<ns3::PenetrationLossModel> ns3::ChannelRealization::GetPenetrationLossModel() [member function] cls.add_method('GetPenetrationLossModel', 'ns3::Ptr< ns3::PenetrationLossModel >', []) ## channel-realization.h (module 'lte'): ns3::Ptr<ns3::ShadowingLossModel> ns3::ChannelRealization::GetShadowingLossModel() [member function] cls.add_method('GetShadowingLossModel', 'ns3::Ptr< ns3::ShadowingLossModel >', []) ## channel-realization.h (module 'lte'): static ns3::TypeId ns3::ChannelRealization::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## channel-realization.h (module 'lte'): void ns3::ChannelRealization::SetJakesFadingLossModel(ns3::Ptr<ns3::JakesFadingLossModel> l) [member function] cls.add_method('SetJakesFadingLossModel', 'void', [param('ns3::Ptr< ns3::JakesFadingLossModel >', 'l')]) ## channel-realization.h (module 'lte'): void ns3::ChannelRealization::SetPathLossModel(ns3::Ptr<ns3::PathLossModel> l) [member function] cls.add_method('SetPathLossModel', 'void', [param('ns3::Ptr< ns3::PathLossModel >', 'l')]) ## channel-realization.h (module 'lte'): void ns3::ChannelRealization::SetPenetrationLossModel(ns3::Ptr<ns3::PenetrationLossModel> l) [member function] cls.add_method('SetPenetrationLossModel', 'void', [param('ns3::Ptr< ns3::PenetrationLossModel >', 'l')]) ## channel-realization.h (module 'lte'): void ns3::ChannelRealization::SetShadowingLossModel(ns3::Ptr<ns3::ShadowingLossModel> l) [member function] cls.add_method('SetShadowingLossModel', 'void', [param('ns3::Ptr< ns3::ShadowingLossModel >', 'l')]) 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_Ns3DiscreteTimeLossModel_methods(root_module, cls): ## discrete-time-loss-model.h (module 'lte'): ns3::DiscreteTimeLossModel::DiscreteTimeLossModel(ns3::DiscreteTimeLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::DiscreteTimeLossModel const &', 'arg0')]) ## discrete-time-loss-model.h (module 'lte'): ns3::DiscreteTimeLossModel::DiscreteTimeLossModel() [constructor] cls.add_constructor([]) ## discrete-time-loss-model.h (module 'lte'): ns3::Time ns3::DiscreteTimeLossModel::GetLastUpdate() [member function] cls.add_method('GetLastUpdate', 'ns3::Time', []) ## discrete-time-loss-model.h (module 'lte'): double ns3::DiscreteTimeLossModel::GetSamplingPeriod() [member function] cls.add_method('GetSamplingPeriod', 'double', []) ## discrete-time-loss-model.h (module 'lte'): static ns3::TypeId ns3::DiscreteTimeLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## discrete-time-loss-model.h (module 'lte'): bool ns3::DiscreteTimeLossModel::NeedForUpdate() [member function] cls.add_method('NeedForUpdate', 'bool', []) ## discrete-time-loss-model.h (module 'lte'): void ns3::DiscreteTimeLossModel::SetLastUpdate() [member function] cls.add_method('SetLastUpdate', 'void', []) ## discrete-time-loss-model.h (module 'lte'): void ns3::DiscreteTimeLossModel::SetSamplingPeriod(double sp) [member function] cls.add_method('SetSamplingPeriod', 'void', [param('double', 'sp')]) 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_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_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_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3JakesFadingLossModel_methods(root_module, cls): ## jakes-fading-loss-model.h (module 'lte'): ns3::JakesFadingLossModel::JakesFadingLossModel(ns3::JakesFadingLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::JakesFadingLossModel const &', 'arg0')]) ## jakes-fading-loss-model.h (module 'lte'): ns3::JakesFadingLossModel::JakesFadingLossModel() [constructor] cls.add_constructor([]) ## jakes-fading-loss-model.h (module 'lte'): ns3::Ptr<ns3::LtePhy> ns3::JakesFadingLossModel::GetPhy() [member function] cls.add_method('GetPhy', 'ns3::Ptr< ns3::LtePhy >', []) ## jakes-fading-loss-model.h (module 'lte'): static ns3::TypeId ns3::JakesFadingLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## jakes-fading-loss-model.h (module 'lte'): double ns3::JakesFadingLossModel::GetValue(int subChannel) [member function] cls.add_method('GetValue', 'double', [param('int', 'subChannel')]) ## jakes-fading-loss-model.h (module 'lte'): void ns3::JakesFadingLossModel::SetPhy(ns3::Ptr<ns3::LtePhy> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::LtePhy >', 'phy')]) ## jakes-fading-loss-model.h (module 'lte'): void ns3::JakesFadingLossModel::SetValue() [member function] cls.add_method('SetValue', 'void', []) return def register_Ns3LteMacQueue_methods(root_module, cls): ## lte-mac-queue.h (module 'lte'): ns3::LteMacQueue::LteMacQueue(ns3::LteMacQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::LteMacQueue const &', 'arg0')]) ## lte-mac-queue.h (module 'lte'): ns3::LteMacQueue::LteMacQueue() [constructor] cls.add_constructor([]) ## lte-mac-queue.h (module 'lte'): ns3::LteMacQueue::LteMacQueue(uint32_t maxSize) [constructor] cls.add_constructor([param('uint32_t', 'maxSize')]) ## lte-mac-queue.h (module 'lte'): ns3::Ptr<ns3::Packet> ns3::LteMacQueue::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', []) ## lte-mac-queue.h (module 'lte'): ns3::Ptr<ns3::Packet> ns3::LteMacQueue::Dequeue(uint32_t availableByte) [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'availableByte')]) ## lte-mac-queue.h (module 'lte'): bool ns3::LteMacQueue::Enqueue(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet')]) ## lte-mac-queue.h (module 'lte'): uint32_t ns3::LteMacQueue::GetMaxSize() const [member function] cls.add_method('GetMaxSize', 'uint32_t', [], is_const=True) ## lte-mac-queue.h (module 'lte'): uint32_t ns3::LteMacQueue::GetNBytes() const [member function] cls.add_method('GetNBytes', 'uint32_t', [], is_const=True) ## lte-mac-queue.h (module 'lte'): std::deque<ns3::LteMacQueue::QueueElement, std::allocator<ns3::LteMacQueue::QueueElement> > const & ns3::LteMacQueue::GetPacketQueue() const [member function] cls.add_method('GetPacketQueue', 'std::deque< ns3::LteMacQueue::QueueElement > const &', [], is_const=True) ## lte-mac-queue.h (module 'lte'): uint32_t ns3::LteMacQueue::GetQueueLengthWithMACOverhead() [member function] cls.add_method('GetQueueLengthWithMACOverhead', 'uint32_t', []) ## lte-mac-queue.h (module 'lte'): uint32_t ns3::LteMacQueue::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## lte-mac-queue.h (module 'lte'): static ns3::TypeId ns3::LteMacQueue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## lte-mac-queue.h (module 'lte'): bool ns3::LteMacQueue::IsEmpty() const [member function] cls.add_method('IsEmpty', 'bool', [], is_const=True) ## lte-mac-queue.h (module 'lte'): ns3::Ptr<ns3::Packet> ns3::LteMacQueue::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## lte-mac-queue.h (module 'lte'): void ns3::LteMacQueue::SetMaxSize(uint32_t maxSize) [member function] cls.add_method('SetMaxSize', 'void', [param('uint32_t', 'maxSize')]) 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::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::DoSetDownlinkSubChannels() [member function] cls.add_method('DoSetDownlinkSubChannels', 'void', [], 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'): 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::SpectrumChannel> ns3::LtePhy::GetDownlinkChannel() [member function] cls.add_method('GetDownlinkChannel', 'ns3::Ptr< ns3::SpectrumChannel >', []) ## 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'): uint32_t ns3::LtePhy::GetNrFrames() const [member function] cls.add_method('GetNrFrames', 'uint32_t', [], is_const=True) ## lte-phy.h (module 'lte'): uint32_t ns3::LtePhy::GetNrSubFrames() const [member function] cls.add_method('GetNrSubFrames', 'uint32_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'): double ns3::LtePhy::GetTxPower() [member function] cls.add_method('GetTxPower', 'double', []) ## 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::SpectrumChannel> ns3::LtePhy::GetUplinkChannel() [member function] cls.add_method('GetUplinkChannel', 'ns3::Ptr< ns3::SpectrumChannel >', []) ## 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::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-phy.h (module 'lte'): bool ns3::LtePhy::SendPacket(ns3::Ptr<ns3::PacketBurst> pb) [member function] cls.add_method('SendPacket', 'bool', [param('ns3::Ptr< ns3::PacketBurst >', 'pb')], is_pure_virtual=True, is_virtual=True) ## 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::SetDownlinkSpectrumPhy(ns3::Ptr<ns3::LteSpectrumPhy> s) [member function] cls.add_method('SetDownlinkSpectrumPhy', 'void', [param('ns3::Ptr< ns3::LteSpectrumPhy >', 's')]) ## 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::SetNrFrames(uint32_t nrFrames) [member function] cls.add_method('SetNrFrames', 'void', [param('uint32_t', 'nrFrames')]) ## lte-phy.h (module 'lte'): void ns3::LtePhy::SetNrSubFrames(uint32_t nrSubFrames) [member function] cls.add_method('SetNrSubFrames', 'void', [param('uint32_t', 'nrSubFrames')]) ## 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::SetTxPower(double pw) [member function] cls.add_method('SetTxPower', 'void', [param('double', 'pw')]) ## 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::SetUplinkSpectrumPhy(ns3::Ptr<ns3::LteSpectrumPhy> s) [member function] cls.add_method('SetUplinkSpectrumPhy', 'void', [param('ns3::Ptr< ns3::LteSpectrumPhy >', 's')]) ## 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_Ns3LtePropagationLossModel_methods(root_module, cls): ## lte-propagation-loss-model.h (module 'lte'): ns3::LtePropagationLossModel::LtePropagationLossModel(ns3::LtePropagationLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::LtePropagationLossModel const &', 'arg0')]) ## lte-propagation-loss-model.h (module 'lte'): ns3::LtePropagationLossModel::LtePropagationLossModel() [constructor] cls.add_constructor([]) ## lte-propagation-loss-model.h (module 'lte'): void ns3::LtePropagationLossModel::CreateChannelRealization(ns3::Ptr<const ns3::MobilityModel> enbMobility, ns3::Ptr<const ns3::MobilityModel> ueMobility) [member function] cls.add_method('CreateChannelRealization', 'void', [param('ns3::Ptr< ns3::MobilityModel const >', 'enbMobility'), param('ns3::Ptr< ns3::MobilityModel const >', 'ueMobility')]) ## lte-propagation-loss-model.h (module 'lte'): ns3::Ptr<ns3::ChannelRealization> ns3::LtePropagationLossModel::GetChannelRealization(ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function] cls.add_method('GetChannelRealization', 'ns3::Ptr< ns3::ChannelRealization >', [param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')], is_const=True) ## lte-propagation-loss-model.h (module 'lte'): static ns3::TypeId ns3::LtePropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## lte-propagation-loss-model.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::LtePropagationLossModel::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_Ns3LteSpectrumPhy_methods(root_module, cls): ## lte-spectrum-phy.h (module 'lte'): ns3::LteSpectrumPhy::LteSpectrumPhy(ns3::LteSpectrumPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::LteSpectrumPhy const &', 'arg0')]) ## lte-spectrum-phy.h (module 'lte'): ns3::LteSpectrumPhy::LteSpectrumPhy() [constructor] cls.add_constructor([]) ## lte-spectrum-phy.h (module 'lte'): void ns3::LteSpectrumPhy::CalcSinrValues(ns3::Ptr<ns3::SpectrumValue const> rxPsd, ns3::Ptr<ns3::SpectrumValue const> noise) [member function] cls.add_method('CalcSinrValues', 'void', [param('ns3::Ptr< ns3::SpectrumValue const >', 'rxPsd'), param('ns3::Ptr< ns3::SpectrumValue const >', 'noise')], is_pure_virtual=True, is_virtual=True) ## lte-spectrum-phy.h (module 'lte'): ns3::Ptr<ns3::SpectrumChannel> ns3::LteSpectrumPhy::GetChannel() [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::SpectrumChannel >', []) ## 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::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::SpectrumValue const> ns3::LteSpectrumPhy::GetNoisePowerSpectralDensity() [member function] cls.add_method('GetNoisePowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue const >', []) ## 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'): 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::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::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'): 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::SetGenericPhyRxStartCallback(ns3::GenericPhyRxStartCallback c) [member function] cls.add_method('SetGenericPhyRxStartCallback', 'void', [param('ns3::GenericPhyRxStartCallback', 'c')]) ## 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::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::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::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::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::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'): 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::EndRx() [member function] cls.add_method('EndRx', 'void', [], visibility='private', is_virtual=True) 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_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_Ns3MacEntity_methods(root_module, cls): ## mac-entity.h (module 'lte'): ns3::MacEntity::MacEntity(ns3::MacEntity const & arg0) [copy constructor] cls.add_constructor([param('ns3::MacEntity const &', 'arg0')]) ## mac-entity.h (module 'lte'): ns3::MacEntity::MacEntity() [constructor] cls.add_constructor([]) ## mac-entity.h (module 'lte'): void ns3::MacEntity::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## mac-entity.h (module 'lte'): ns3::Ptr<ns3::AmcModule> ns3::MacEntity::GetAmcModule() const [member function] cls.add_method('GetAmcModule', 'ns3::Ptr< ns3::AmcModule >', [], is_const=True) ## mac-entity.h (module 'lte'): ns3::Ptr<ns3::LteNetDevice> ns3::MacEntity::GetDevice() [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::LteNetDevice >', []) ## mac-entity.h (module 'lte'): static ns3::TypeId ns3::MacEntity::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mac-entity.h (module 'lte'): void ns3::MacEntity::SetAmcModule(ns3::Ptr<ns3::AmcModule> amcModule) [member function] cls.add_method('SetAmcModule', 'void', [param('ns3::Ptr< ns3::AmcModule >', 'amcModule')]) ## mac-entity.h (module 'lte'): void ns3::MacEntity::SetDevice(ns3::Ptr<ns3::LteNetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::LteNetDevice >', 'd')]) 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_Ns3PathLossModel_methods(root_module, cls): ## path-loss-model.h (module 'lte'): ns3::PathLossModel::PathLossModel(ns3::PathLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::PathLossModel const &', 'arg0')]) ## path-loss-model.h (module 'lte'): ns3::PathLossModel::PathLossModel() [constructor] cls.add_constructor([]) ## path-loss-model.h (module 'lte'): static ns3::TypeId ns3::PathLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## path-loss-model.h (module 'lte'): double ns3::PathLossModel::GetValue(ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) [member function] cls.add_method('GetValue', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')]) ## path-loss-model.h (module 'lte'): void ns3::PathLossModel::SetValue(double pl) [member function] cls.add_method('SetValue', 'void', [param('double', 'pl')]) return def register_Ns3PdcchMapIdealControlMessage_methods(root_module, cls): ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::PdcchMapIdealControlMessage(ns3::PdcchMapIdealControlMessage const & arg0) [copy constructor] cls.add_constructor([param('ns3::PdcchMapIdealControlMessage const &', 'arg0')]) ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::PdcchMapIdealControlMessage() [constructor] cls.add_constructor([]) ## ideal-control-messages.h (module 'lte'): void ns3::PdcchMapIdealControlMessage::AddNewRecord(ns3::PdcchMapIdealControlMessage::Direction direction, int subChannel, ns3::Ptr<ns3::LteNetDevice> ue, double mcs) [member function] cls.add_method('AddNewRecord', 'void', [param('ns3::PdcchMapIdealControlMessage::Direction', 'direction'), param('int', 'subChannel'), param('ns3::Ptr< ns3::LteNetDevice >', 'ue'), param('double', 'mcs')]) ## ideal-control-messages.h (module 'lte'): std::list<ns3::PdcchMapIdealControlMessage::IdealPdcchRecord,std::allocator<ns3::PdcchMapIdealControlMessage::IdealPdcchRecord> > * ns3::PdcchMapIdealControlMessage::GetMessage() [member function] cls.add_method('GetMessage', 'std::list< ns3::PdcchMapIdealControlMessage::IdealPdcchRecord > *', []) return def register_Ns3PdcchMapIdealControlMessageIdealPdcchRecord_methods(root_module, cls): ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::IdealPdcchRecord::IdealPdcchRecord() [constructor] cls.add_constructor([]) ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::IdealPdcchRecord::IdealPdcchRecord(ns3::PdcchMapIdealControlMessage::IdealPdcchRecord const & arg0) [copy constructor] cls.add_constructor([param('ns3::PdcchMapIdealControlMessage::IdealPdcchRecord const &', 'arg0')]) ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::IdealPdcchRecord::m_direction [variable] cls.add_instance_attribute('m_direction', 'ns3::PdcchMapIdealControlMessage::Direction', is_const=False) ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::IdealPdcchRecord::m_idSubChannel [variable] cls.add_instance_attribute('m_idSubChannel', 'int', is_const=False) ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::IdealPdcchRecord::m_mcsIndex [variable] cls.add_instance_attribute('m_mcsIndex', 'double', is_const=False) ## ideal-control-messages.h (module 'lte'): ns3::PdcchMapIdealControlMessage::IdealPdcchRecord::m_ue [variable] cls.add_instance_attribute('m_ue', 'ns3::Ptr< ns3::LteNetDevice >', is_const=False) return def register_Ns3PenetrationLossModel_methods(root_module, cls): ## penetration-loss-model.h (module 'lte'): ns3::PenetrationLossModel::PenetrationLossModel(ns3::PenetrationLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::PenetrationLossModel const &', 'arg0')]) ## penetration-loss-model.h (module 'lte'): ns3::PenetrationLossModel::PenetrationLossModel() [constructor] cls.add_constructor([]) ## penetration-loss-model.h (module 'lte'): static ns3::TypeId ns3::PenetrationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## penetration-loss-model.h (module 'lte'): double ns3::PenetrationLossModel::GetValue() [member function] cls.add_method('GetValue', 'double', []) ## penetration-loss-model.h (module 'lte'): void ns3::PenetrationLossModel::SetValue(double pnl) [member function] cls.add_method('SetValue', 'void', [param('double', 'pnl')]) 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_Ns3ShadowingLossModel_methods(root_module, cls): ## shadowing-loss-model.h (module 'lte'): ns3::ShadowingLossModel::ShadowingLossModel(ns3::ShadowingLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ShadowingLossModel const &', 'arg0')]) ## shadowing-loss-model.h (module 'lte'): ns3::ShadowingLossModel::ShadowingLossModel() [constructor] cls.add_constructor([]) ## shadowing-loss-model.h (module 'lte'): ns3::ShadowingLossModel::ShadowingLossModel(double mu, double sigma, double samplingPeriod) [constructor] cls.add_constructor([param('double', 'mu'), param('double', 'sigma'), param('double', 'samplingPeriod')]) ## shadowing-loss-model.h (module 'lte'): static ns3::TypeId ns3::ShadowingLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## shadowing-loss-model.h (module 'lte'): double ns3::ShadowingLossModel::GetValue() [member function] cls.add_method('GetValue', 'double', []) ## shadowing-loss-model.h (module 'lte'): void ns3::ShadowingLossModel::SetValue(double sh) [member function] cls.add_method('SetValue', 'void', [param('double', 'sh')]) 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_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_Ns3UeLtePhy_methods(root_module, cls): ## ue-phy.h (module 'lte'): ns3::UeLtePhy::UeLtePhy(ns3::UeLtePhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::UeLtePhy const &', 'arg0')]) ## ue-phy.h (module 'lte'): ns3::UeLtePhy::UeLtePhy() [constructor] cls.add_constructor([]) ## ue-phy.h (module 'lte'): ns3::UeLtePhy::UeLtePhy(ns3::Ptr<ns3::LteNetDevice> d) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::LteNetDevice >', 'd')]) ## ue-phy.h (module 'lte'): void ns3::UeLtePhy::CreateCqiFeedbacks(std::vector<double, std::allocator<double> > sinr) [member function] cls.add_method('CreateCqiFeedbacks', 'void', [param('std::vector< double >', 'sinr')]) ## ue-phy.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::UeLtePhy::CreateTxPowerSpectralDensity() [member function] cls.add_method('CreateTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [], is_virtual=True) ## ue-phy.h (module 'lte'): void ns3::UeLtePhy::DoSetUplinkSubChannels() [member function] cls.add_method('DoSetUplinkSubChannels', 'void', [], is_virtual=True) ## ue-phy.h (module 'lte'): std::vector<int, std::allocator<int> > ns3::UeLtePhy::GetSubChannelsForReception() [member function] cls.add_method('GetSubChannelsForReception', 'std::vector< int >', []) ## ue-phy.h (module 'lte'): std::vector<int, std::allocator<int> > ns3::UeLtePhy::GetSubChannelsForTransmission() [member function] cls.add_method('GetSubChannelsForTransmission', 'std::vector< int >', []) ## ue-phy.h (module 'lte'): static ns3::TypeId ns3::UeLtePhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ue-phy.h (module 'lte'): void ns3::UeLtePhy::ReceiveIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function] cls.add_method('ReceiveIdealControlMessage', 'void', [param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')], is_virtual=True) ## ue-phy.h (module 'lte'): void ns3::UeLtePhy::SendIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function] cls.add_method('SendIdealControlMessage', 'void', [param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')], is_virtual=True) ## ue-phy.h (module 'lte'): bool ns3::UeLtePhy::SendPacket(ns3::Ptr<ns3::PacketBurst> pb) [member function] cls.add_method('SendPacket', 'bool', [param('ns3::Ptr< ns3::PacketBurst >', 'pb')], is_virtual=True) ## ue-phy.h (module 'lte'): void ns3::UeLtePhy::SetSubChannelsForReception(std::vector<int, std::allocator<int> > mask) [member function] cls.add_method('SetSubChannelsForReception', 'void', [param('std::vector< int >', 'mask')]) ## ue-phy.h (module 'lte'): void ns3::UeLtePhy::SetSubChannelsForTransmission(std::vector<int, std::allocator<int> > mask) [member function] cls.add_method('SetSubChannelsForTransmission', 'void', [param('std::vector< int >', 'mask')]) return def register_Ns3UeLteSpectrumPhy_methods(root_module, cls): ## ue-lte-spectrum-phy.h (module 'lte'): ns3::UeLteSpectrumPhy::UeLteSpectrumPhy(ns3::UeLteSpectrumPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::UeLteSpectrumPhy const &', 'arg0')]) ## ue-lte-spectrum-phy.h (module 'lte'): ns3::UeLteSpectrumPhy::UeLteSpectrumPhy() [constructor] cls.add_constructor([]) ## ue-lte-spectrum-phy.h (module 'lte'): void ns3::UeLteSpectrumPhy::CalcSinrValues(ns3::Ptr<ns3::SpectrumValue const> rxPsd, ns3::Ptr<ns3::SpectrumValue const> noise) [member function] cls.add_method('CalcSinrValues', 'void', [param('ns3::Ptr< ns3::SpectrumValue const >', 'rxPsd'), param('ns3::Ptr< ns3::SpectrumValue const >', 'noise')], is_virtual=True) ## ue-lte-spectrum-phy.h (module 'lte'): static ns3::TypeId ns3::UeLteSpectrumPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UeMacEntity_methods(root_module, cls): ## ue-mac-entity.h (module 'lte'): ns3::UeMacEntity::UeMacEntity(ns3::UeMacEntity const & arg0) [copy constructor] cls.add_constructor([param('ns3::UeMacEntity const &', 'arg0')]) ## ue-mac-entity.h (module 'lte'): ns3::UeMacEntity::UeMacEntity() [constructor] cls.add_constructor([]) ## ue-mac-entity.h (module 'lte'): ns3::Ptr<ns3::CqiIdealControlMessage> ns3::UeMacEntity::CreateCqiFeedbacks(std::vector<double, std::allocator<double> > sinr) [member function] cls.add_method('CreateCqiFeedbacks', 'ns3::Ptr< ns3::CqiIdealControlMessage >', [param('std::vector< double >', 'sinr')]) ## ue-mac-entity.h (module 'lte'): static ns3::TypeId ns3::UeMacEntity::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UintegerValue_methods(root_module, cls): ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor] cls.add_constructor([]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor] cls.add_constructor([param('uint64_t const &', 'value')]) ## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function] cls.add_method('Get', 'uint64_t', [], is_const=True) ## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function] cls.add_method('Set', 'void', [param('uint64_t const &', 'value')]) return def register_Ns3Vector2DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')]) return def register_Ns3Vector2DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor] cls.add_constructor([param('ns3::Vector2D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector2DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector2DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector2D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector2DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector2D const &', 'value')]) return def register_Ns3Vector3DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')]) return def register_Ns3Vector3DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor] cls.add_constructor([param('ns3::Vector3D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector3DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector3DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector3D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector3DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector3D const &', 'value')]) return def register_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_Ns3CqiIdealControlMessage_methods(root_module, cls): ## ideal-control-messages.h (module 'lte'): ns3::CqiIdealControlMessage::CqiIdealControlMessage(ns3::CqiIdealControlMessage const & arg0) [copy constructor] cls.add_constructor([param('ns3::CqiIdealControlMessage const &', 'arg0')]) ## ideal-control-messages.h (module 'lte'): ns3::CqiIdealControlMessage::CqiIdealControlMessage() [constructor] cls.add_constructor([]) ## ideal-control-messages.h (module 'lte'): void ns3::CqiIdealControlMessage::AddNewRecord(int subChannel, double cqi) [member function] cls.add_method('AddNewRecord', 'void', [param('int', 'subChannel'), param('double', 'cqi')]) ## ideal-control-messages.h (module 'lte'): std::list<ns3::CqiIdealControlMessage::CqiFeedback,std::allocator<ns3::CqiIdealControlMessage::CqiFeedback> > * ns3::CqiIdealControlMessage::GetMessage() [member function] cls.add_method('GetMessage', 'std::list< ns3::CqiIdealControlMessage::CqiFeedback > *', []) return def register_Ns3CqiIdealControlMessageCqiFeedback_methods(root_module, cls): ## ideal-control-messages.h (module 'lte'): ns3::CqiIdealControlMessage::CqiFeedback::CqiFeedback() [constructor] cls.add_constructor([]) ## ideal-control-messages.h (module 'lte'): ns3::CqiIdealControlMessage::CqiFeedback::CqiFeedback(ns3::CqiIdealControlMessage::CqiFeedback const & arg0) [copy constructor] cls.add_constructor([param('ns3::CqiIdealControlMessage::CqiFeedback const &', 'arg0')]) ## ideal-control-messages.h (module 'lte'): ns3::CqiIdealControlMessage::CqiFeedback::m_cqi [variable] cls.add_instance_attribute('m_cqi', 'double', is_const=False) ## ideal-control-messages.h (module 'lte'): ns3::CqiIdealControlMessage::CqiFeedback::m_idSubChannel [variable] cls.add_instance_attribute('m_idSubChannel', 'int', is_const=False) return def register_Ns3EnbLtePhy_methods(root_module, cls): ## enb-phy.h (module 'lte'): ns3::EnbLtePhy::EnbLtePhy(ns3::EnbLtePhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnbLtePhy const &', 'arg0')]) ## enb-phy.h (module 'lte'): ns3::EnbLtePhy::EnbLtePhy() [constructor] cls.add_constructor([]) ## enb-phy.h (module 'lte'): ns3::EnbLtePhy::EnbLtePhy(ns3::Ptr<ns3::LteNetDevice> d) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::LteNetDevice >', 'd')]) ## enb-phy.h (module 'lte'): void ns3::EnbLtePhy::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')]) ## enb-phy.h (module 'lte'): ns3::Ptr<ns3::SpectrumValue> ns3::EnbLtePhy::CreateTxPowerSpectralDensity() [member function] cls.add_method('CreateTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [], is_virtual=True) ## enb-phy.h (module 'lte'): void ns3::EnbLtePhy::DoSetDownlinkSubChannels() [member function] cls.add_method('DoSetDownlinkSubChannels', 'void', [], is_virtual=True) ## enb-phy.h (module 'lte'): void ns3::EnbLtePhy::EndFrame() [member function] cls.add_method('EndFrame', 'void', []) ## enb-phy.h (module 'lte'): void ns3::EnbLtePhy::EndSubFrame() [member function] cls.add_method('EndSubFrame', 'void', []) ## enb-phy.h (module 'lte'): static ns3::TypeId ns3::EnbLtePhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## enb-phy.h (module 'lte'): void ns3::EnbLtePhy::ReceiveIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function] cls.add_method('ReceiveIdealControlMessage', 'void', [param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')], is_virtual=True) ## enb-phy.h (module 'lte'): void ns3::EnbLtePhy::SendIdealControlMessage(ns3::Ptr<ns3::IdealControlMessage> msg) [member function] cls.add_method('SendIdealControlMessage', 'void', [param('ns3::Ptr< ns3::IdealControlMessage >', 'msg')], is_virtual=True) ## enb-phy.h (module 'lte'): bool ns3::EnbLtePhy::SendPacket(ns3::Ptr<ns3::PacketBurst> pb) [member function] cls.add_method('SendPacket', 'bool', [param('ns3::Ptr< ns3::PacketBurst >', 'pb')], is_virtual=True) ## enb-phy.h (module 'lte'): void ns3::EnbLtePhy::StartFrame() [member function] cls.add_method('StartFrame', 'void', []) ## enb-phy.h (module 'lte'): void ns3::EnbLtePhy::StartSubFrame() [member function] cls.add_method('StartSubFrame', 'void', []) return def register_Ns3EnbLteSpectrumPhy_methods(root_module, cls): ## enb-lte-spectrum-phy.h (module 'lte'): ns3::EnbLteSpectrumPhy::EnbLteSpectrumPhy(ns3::EnbLteSpectrumPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnbLteSpectrumPhy const &', 'arg0')]) ## enb-lte-spectrum-phy.h (module 'lte'): ns3::EnbLteSpectrumPhy::EnbLteSpectrumPhy() [constructor] cls.add_constructor([]) ## enb-lte-spectrum-phy.h (module 'lte'): void ns3::EnbLteSpectrumPhy::CalcSinrValues(ns3::Ptr<ns3::SpectrumValue const> rxPsd, ns3::Ptr<ns3::SpectrumValue const> noise) [member function] cls.add_method('CalcSinrValues', 'void', [param('ns3::Ptr< ns3::SpectrumValue const >', 'rxPsd'), param('ns3::Ptr< ns3::SpectrumValue const >', 'noise')], is_virtual=True) ## enb-lte-spectrum-phy.h (module 'lte'): static ns3::TypeId ns3::EnbLteSpectrumPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3EnbMacEntity_methods(root_module, cls): ## enb-mac-entity.h (module 'lte'): ns3::EnbMacEntity::EnbMacEntity(ns3::EnbMacEntity const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnbMacEntity const &', 'arg0')]) ## enb-mac-entity.h (module 'lte'): ns3::EnbMacEntity::EnbMacEntity() [constructor] cls.add_constructor([]) ## enb-mac-entity.h (module 'lte'): void ns3::EnbMacEntity::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## enb-mac-entity.h (module 'lte'): ns3::Ptr<ns3::PacketScheduler> ns3::EnbMacEntity::GetDownlinkPacketScheduler() [member function] cls.add_method('GetDownlinkPacketScheduler', 'ns3::Ptr< ns3::PacketScheduler >', []) ## enb-mac-entity.h (module 'lte'): static ns3::TypeId ns3::EnbMacEntity::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## enb-mac-entity.h (module 'lte'): ns3::Ptr<ns3::PacketScheduler> ns3::EnbMacEntity::GetUplinkPacketScheduler() [member function] cls.add_method('GetUplinkPacketScheduler', 'ns3::Ptr< ns3::PacketScheduler >', []) ## enb-mac-entity.h (module 'lte'): void ns3::EnbMacEntity::ReceiveCqiIdealControlMessage(ns3::Ptr<ns3::CqiIdealControlMessage> msg) [member function] cls.add_method('ReceiveCqiIdealControlMessage', 'void', [param('ns3::Ptr< ns3::CqiIdealControlMessage >', 'msg')]) ## enb-mac-entity.h (module 'lte'): void ns3::EnbMacEntity::SendPdcchMapIdealControlMessage(ns3::Ptr<ns3::PdcchMapIdealControlMessage> msg) [member function] cls.add_method('SendPdcchMapIdealControlMessage', 'void', [param('ns3::Ptr< ns3::PdcchMapIdealControlMessage >', 'msg')]) ## enb-mac-entity.h (module 'lte'): void ns3::EnbMacEntity::SetDownlinkPacketScheduler(ns3::Ptr<ns3::PacketScheduler> s) [member function] cls.add_method('SetDownlinkPacketScheduler', 'void', [param('ns3::Ptr< ns3::PacketScheduler >', 's')]) ## enb-mac-entity.h (module 'lte'): void ns3::EnbMacEntity::SetUplinkPacketScheduler(ns3::Ptr<ns3::PacketScheduler> s) [member function] cls.add_method('SetUplinkPacketScheduler', 'void', [param('ns3::Ptr< ns3::PacketScheduler >', 's')]) 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::SetGenericPhyTxStartCallback(ns3::GenericPhyTxStartCallback c) [member function] cls.add_method('SetGenericPhyTxStartCallback', 'void', [param('ns3::GenericPhyTxStartCallback', 'c')]) ## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::SetPhy(ns3::Ptr<ns3::LtePhy> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::LtePhy >', 'phy')]) ## lte-net-device.h (module 'lte'): ns3::Ptr<ns3::LtePhy> ns3::LteNetDevice::GetPhy() const [member function] cls.add_method('GetPhy', 'ns3::Ptr< ns3::LtePhy >', [], is_const=True) ## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::SetRrcEntity(ns3::Ptr<ns3::RrcEntity> rrc) [member function] cls.add_method('SetRrcEntity', 'void', [param('ns3::Ptr< ns3::RrcEntity >', 'rrc')]) ## lte-net-device.h (module 'lte'): ns3::Ptr<ns3::RrcEntity> ns3::LteNetDevice::GetRrcEntity() [member function] cls.add_method('GetRrcEntity', 'ns3::Ptr< ns3::RrcEntity >', []) ## 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'): void ns3::LteNetDevice::Start() [member function] cls.add_method('Start', 'void', [], is_pure_virtual=True, is_virtual=True) ## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::Stop() [member function] cls.add_method('Stop', 'void', [], is_pure_virtual=True, is_virtual=True) ## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::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-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')]) ## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::ForwardUp(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address const & source, ns3::Mac48Address const & dest) [member function] cls.add_method('ForwardUp', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address const &', 'source'), param('ns3::Mac48Address const &', 'dest')]) ## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::ForwardUp(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('ForwardUp', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')]) ## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::SetPacketToSend(ns3::Ptr<ns3::PacketBurst> p) [member function] cls.add_method('SetPacketToSend', 'void', [param('ns3::Ptr< ns3::PacketBurst >', 'p')]) ## lte-net-device.h (module 'lte'): ns3::Ptr<ns3::PacketBurst> ns3::LteNetDevice::GetPacketToSend() [member function] cls.add_method('GetPacketToSend', 'ns3::Ptr< ns3::PacketBurst >', []) ## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::StartTransmission() [member function] cls.add_method('StartTransmission', 'void', [], is_pure_virtual=True, is_virtual=True) ## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::SendPacket(ns3::Ptr<ns3::PacketBurst> p) [member function] cls.add_method('SendPacket', 'bool', [param('ns3::Ptr< ns3::PacketBurst >', 'p')], is_pure_virtual=True, is_virtual=True) ## lte-net-device.h (module 'lte'): bool ns3::LteNetDevice::DoSend(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address const & source, ns3::Mac48Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('DoSend', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address const &', 'source'), param('ns3::Mac48Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, visibility='private', is_virtual=True) ## lte-net-device.h (module 'lte'): void ns3::LteNetDevice::DoReceive(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoReceive', 'void', [param('ns3::Ptr< ns3::Packet >', 'p')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3SingleModelSpectrumChannel_methods(root_module, cls): ## single-model-spectrum-channel.h (module 'spectrum'): ns3::SingleModelSpectrumChannel::SingleModelSpectrumChannel(ns3::SingleModelSpectrumChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SingleModelSpectrumChannel const &', 'arg0')]) ## single-model-spectrum-channel.h (module 'spectrum'): ns3::SingleModelSpectrumChannel::SingleModelSpectrumChannel() [constructor] cls.add_constructor([]) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::AddPropagationLossModel(ns3::Ptr<ns3::PropagationLossModel> loss) [member function] cls.add_method('AddPropagationLossModel', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'loss')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::AddRx(ns3::Ptr<ns3::SpectrumPhy> phy) [member function] cls.add_method('AddRx', 'void', [param('ns3::Ptr< ns3::SpectrumPhy >', 'phy')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::AddSpectrumPropagationLossModel(ns3::Ptr<ns3::SpectrumPropagationLossModel> loss) [member function] cls.add_method('AddSpectrumPropagationLossModel', 'void', [param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'loss')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::SingleModelSpectrumChannel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): uint32_t ns3::SingleModelSpectrumChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumPropagationLossModel> ns3::SingleModelSpectrumChannel::GetSpectrumPropagationLossModel() [member function] cls.add_method('GetSpectrumPropagationLossModel', 'ns3::Ptr< ns3::SpectrumPropagationLossModel >', [], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): static ns3::TypeId ns3::SingleModelSpectrumChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::SetPropagationDelayModel(ns3::Ptr<ns3::PropagationDelayModel> delay) [member function] cls.add_method('SetPropagationDelayModel', 'void', [param('ns3::Ptr< ns3::PropagationDelayModel >', 'delay')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::StartTx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartTx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## single-model-spectrum-channel.h (module 'spectrum'): void ns3::SingleModelSpectrumChannel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3UeNetDevice_methods(root_module, cls): ## ue-net-device.h (module 'lte'): static ns3::TypeId ns3::UeNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ue-net-device.h (module 'lte'): ns3::UeNetDevice::UeNetDevice() [constructor] cls.add_constructor([]) ## ue-net-device.h (module 'lte'): ns3::UeNetDevice::UeNetDevice(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::LtePhy> phy) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::LtePhy >', 'phy')]) ## ue-net-device.h (module 'lte'): ns3::UeNetDevice::UeNetDevice(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::LtePhy> phy, ns3::Ptr<ns3::EnbNetDevice> targetEnb) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::LtePhy >', 'phy'), param('ns3::Ptr< ns3::EnbNetDevice >', 'targetEnb')]) ## ue-net-device.h (module 'lte'): void ns3::UeNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## ue-net-device.h (module 'lte'): void ns3::UeNetDevice::SetMacEntity(ns3::Ptr<ns3::UeMacEntity> m) [member function] cls.add_method('SetMacEntity', 'void', [param('ns3::Ptr< ns3::UeMacEntity >', 'm')]) ## ue-net-device.h (module 'lte'): ns3::Ptr<ns3::UeMacEntity> ns3::UeNetDevice::GetMacEntity() [member function] cls.add_method('GetMacEntity', 'ns3::Ptr< ns3::UeMacEntity >', []) ## ue-net-device.h (module 'lte'): void ns3::UeNetDevice::InitUeNetDevice() [member function] cls.add_method('InitUeNetDevice', 'void', []) ## ue-net-device.h (module 'lte'): void ns3::UeNetDevice::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## ue-net-device.h (module 'lte'): void ns3::UeNetDevice::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## ue-net-device.h (module 'lte'): void ns3::UeNetDevice::SetTargetEnb(ns3::Ptr<ns3::EnbNetDevice> enb) [member function] cls.add_method('SetTargetEnb', 'void', [param('ns3::Ptr< ns3::EnbNetDevice >', 'enb')]) ## ue-net-device.h (module 'lte'): ns3::Ptr<ns3::EnbNetDevice> ns3::UeNetDevice::GetTargetEnb() [member function] cls.add_method('GetTargetEnb', 'ns3::Ptr< ns3::EnbNetDevice >', []) ## ue-net-device.h (module 'lte'): void ns3::UeNetDevice::StartTransmission() [member function] cls.add_method('StartTransmission', 'void', [], is_virtual=True) ## ue-net-device.h (module 'lte'): bool ns3::UeNetDevice::SendPacket(ns3::Ptr<ns3::PacketBurst> p) [member function] cls.add_method('SendPacket', 'bool', [param('ns3::Ptr< ns3::PacketBurst >', 'p')], is_virtual=True) ## ue-net-device.h (module 'lte'): bool ns3::UeNetDevice::DoSend(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address const & source, ns3::Mac48Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('DoSend', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address const &', 'source'), param('ns3::Mac48Address const &', 'dest'), param('uint16_t', 'protocolNumber')], visibility='private', is_virtual=True) ## ue-net-device.h (module 'lte'): void ns3::UeNetDevice::DoReceive(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoReceive', 'void', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) return def register_Ns3EnbNetDevice_methods(root_module, cls): ## enb-net-device.h (module 'lte'): static ns3::TypeId ns3::EnbNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## enb-net-device.h (module 'lte'): ns3::EnbNetDevice::EnbNetDevice() [constructor] cls.add_constructor([]) ## enb-net-device.h (module 'lte'): ns3::EnbNetDevice::EnbNetDevice(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::LtePhy> phy) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::LtePhy >', 'phy')]) ## enb-net-device.h (module 'lte'): void ns3::EnbNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## enb-net-device.h (module 'lte'): void ns3::EnbNetDevice::InitEnbNetDevice() [member function] cls.add_method('InitEnbNetDevice', 'void', []) ## enb-net-device.h (module 'lte'): void ns3::EnbNetDevice::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## enb-net-device.h (module 'lte'): void ns3::EnbNetDevice::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## enb-net-device.h (module 'lte'): void ns3::EnbNetDevice::SetUeManager(ns3::Ptr<ns3::UeManager> m) [member function] cls.add_method('SetUeManager', 'void', [param('ns3::Ptr< ns3::UeManager >', 'm')]) ## enb-net-device.h (module 'lte'): ns3::Ptr<ns3::UeManager> ns3::EnbNetDevice::GetUeManager() [member function] cls.add_method('GetUeManager', 'ns3::Ptr< ns3::UeManager >', []) ## enb-net-device.h (module 'lte'): void ns3::EnbNetDevice::SetMacEntity(ns3::Ptr<ns3::EnbMacEntity> m) [member function] cls.add_method('SetMacEntity', 'void', [param('ns3::Ptr< ns3::EnbMacEntity >', 'm')]) ## enb-net-device.h (module 'lte'): ns3::Ptr<ns3::EnbMacEntity> ns3::EnbNetDevice::GetMacEntity() [member function] cls.add_method('GetMacEntity', 'ns3::Ptr< ns3::EnbMacEntity >', []) ## enb-net-device.h (module 'lte'): void ns3::EnbNetDevice::StartTransmission() [member function] cls.add_method('StartTransmission', 'void', [], is_virtual=True) ## enb-net-device.h (module 'lte'): bool ns3::EnbNetDevice::SendPacket(ns3::Ptr<ns3::PacketBurst> p) [member function] cls.add_method('SendPacket', 'bool', [param('ns3::Ptr< ns3::PacketBurst >', 'p')], is_virtual=True) ## enb-net-device.h (module 'lte'): void ns3::EnbNetDevice::SendIdealPdcchMessage() [member function] cls.add_method('SendIdealPdcchMessage', 'void', []) ## enb-net-device.h (module 'lte'): bool ns3::EnbNetDevice::DoSend(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address const & source, ns3::Mac48Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('DoSend', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address const &', 'source'), param('ns3::Mac48Address const &', 'dest'), param('uint16_t', 'protocolNumber')], visibility='private', is_virtual=True) ## enb-net-device.h (module 'lte'): void ns3::EnbNetDevice::DoReceive(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoReceive', 'void', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module) register_functions_ns3_internal(module.get_submodule('internal'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_addressUtils(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
zkan/intern-checklist
docs/conf.py
1
7864
# -*- coding: utf-8 -*- # # Intern Checklist documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Intern Checklist' copyright = u"2015, Kan Ouivirach" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'intern-checklistdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'intern-checklist.tex', u'Intern Checklist Documentation', u"Kan Ouivirach", 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'intern-checklist', u'Intern Checklist Documentation', [u"Kan Ouivirach"], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'intern-checklist', u'Intern Checklist Documentation', u"Kan Ouivirach", 'Intern Checklist', 'Intern Checklist', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
bsd-3-clause
berny6969/enigma2
po/xml2po.py
40
1590
#!/usr/bin/python import sys import os import string import re from xml.sax import make_parser from xml.sax.handler import ContentHandler, property_lexical_handler try: from _xmlplus.sax.saxlib import LexicalHandler no_comments = False except ImportError: class LexicalHandler: pass no_comments = True class parseXML(ContentHandler, LexicalHandler): def __init__(self, attrlist): self.isPointsElement, self.isReboundsElement = 0, 0 self.attrlist = attrlist self.last_comment = None self.ishex = re.compile('#[0-9a-fA-F]+\Z') def comment(self, comment): if "TRANSLATORS:" in comment: self.last_comment = comment def startElement(self, name, attrs): for x in ["text", "title", "value", "caption", "description"]: try: k = str(attrs[x]) if k.strip() != "" and not self.ishex.match(k): attrlist.add((attrs[x], self.last_comment)) self.last_comment = None except KeyError: pass parser = make_parser() attrlist = set() contentHandler = parseXML(attrlist) parser.setContentHandler(contentHandler) if not no_comments: parser.setProperty(property_lexical_handler, contentHandler) for arg in sys.argv[1:]: if os.path.isdir(arg): for file in os.listdir(arg): if (file.endswith(".xml")): parser.parse(os.path.join(arg, file)) else: parser.parse(arg) attrlist = list(attrlist) attrlist.sort(key=lambda a: a[0]) for (k,c) in attrlist: print print '#: ' + arg string.replace(k, "\\n", "\"\n\"") if c: for l in c.split('\n'): print "#. ", l print 'msgid "' + str(k) + '"' print 'msgstr ""' attrlist = set()
gpl-2.0
benfinke/ns_python
nssrc/com/citrix/netscaler/nitro/resource/config/ssl/sslpolicy_sslservice_binding.py
3
6009
# # Copyright (c) 2008-2015 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response from nssrc.com.citrix.netscaler.nitro.service.options import options from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util class sslpolicy_sslservice_binding(base_resource) : """ Binding class showing the sslservice that can be bound to sslpolicy. """ def __init__(self) : self._boundto = "" self._priority = 0 self._activepolicy = 0 self._gotopriorityexpression = "" self._labeltype = "" self._labelname = "" self._name = "" self.___count = 0 @property def name(self) : ur"""Name of the SSL policy for which to display detailed information.<br/>Minimum length = 1. """ try : return self._name except Exception as e: raise e @name.setter def name(self, name) : ur"""Name of the SSL policy for which to display detailed information.<br/>Minimum length = 1 """ try : self._name = name except Exception as e: raise e @property def boundto(self) : ur"""The entity name to which policy is bound. """ try : return self._boundto except Exception as e: raise e @boundto.setter def boundto(self, boundto) : ur"""The entity name to which policy is bound. """ try : self._boundto = boundto except Exception as e: raise e @property def priority(self) : try : return self._priority except Exception as e: raise e @property def labelname(self) : ur"""Name of the label to invoke if the current policy rule evaluates to TRUE. """ try : return self._labelname except Exception as e: raise e @property def gotopriorityexpression(self) : ur"""Expression specifying the priority of the next policy which will get evaluated if the current policy rule evaluates to TRUE. """ try : return self._gotopriorityexpression except Exception as e: raise e @property def labeltype(self) : ur"""Type of policy label invocation.<br/>Possible values = vserver, service, policylabel. """ try : return self._labeltype except Exception as e: raise e @property def activepolicy(self) : try : return self._activepolicy except Exception as e: raise e def _get_nitro_response(self, service, response) : ur""" converts nitro response into object and returns the object array in case of get request. """ try : result = service.payload_formatter.string_to_resource(sslpolicy_sslservice_binding_response, response, self.__class__.__name__) if(result.errorcode != 0) : if (result.errorcode == 444) : service.clear_session(self) if result.severity : if (result.severity == "ERROR") : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) else : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) return result.sslpolicy_sslservice_binding except Exception as e : raise e def _get_object_name(self) : ur""" Returns the value of object identifier argument """ try : if self.name is not None : return str(self.name) return None except Exception as e : raise e @classmethod def get(cls, service, name) : ur""" Use this API to fetch sslpolicy_sslservice_binding resources. """ try : obj = sslpolicy_sslservice_binding() obj.name = name response = obj.get_resources(service) return response except Exception as e: raise e @classmethod def get_filtered(cls, service, name, filter_) : ur""" Use this API to fetch filtered set of sslpolicy_sslservice_binding resources. Filter string should be in JSON format.eg: "port:80,servicetype:HTTP". """ try : obj = sslpolicy_sslservice_binding() obj.name = name option_ = options() option_.filter = filter_ response = obj.getfiltered(service, option_) return response except Exception as e: raise e @classmethod def count(cls, service, name) : ur""" Use this API to count sslpolicy_sslservice_binding resources configued on NetScaler. """ try : obj = sslpolicy_sslservice_binding() obj.name = name option_ = options() option_.count = True response = obj.get_resources(service, option_) if response : return response[0].__dict__['___count'] return 0 except Exception as e: raise e @classmethod def count_filtered(cls, service, name, filter_) : ur""" Use this API to count the filtered set of sslpolicy_sslservice_binding resources. Filter string should be in JSON format.eg: "port:80,servicetype:HTTP". """ try : obj = sslpolicy_sslservice_binding() obj.name = name option_ = options() option_.count = True option_.filter = filter_ response = obj.getfiltered(service, option_) if response : return response[0].__dict__['___count'] return 0 except Exception as e: raise e class Labeltype: vserver = "vserver" service = "service" policylabel = "policylabel" class sslpolicy_sslservice_binding_response(base_response) : def __init__(self, length=1) : self.sslpolicy_sslservice_binding = [] self.errorcode = 0 self.message = "" self.severity = "" self.sessionid = "" self.sslpolicy_sslservice_binding = [sslpolicy_sslservice_binding() for _ in range(length)]
apache-2.0
sridevikoushik31/nova
nova/db/mysqldb/instance_metadata.py
1
1820
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2013 Rackspace Hosting # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from nova.db.mysqldb import sql from nova.openstack.common import log as logging from nova.openstack.common import timeutils LOG = logging.getLogger(__name__) _WHERE_STR = '(`key` = %(key)s AND `instance_uuid`=%(instance_uuid)s)' class Mixin(object): @classmethod def update(cls, conn, instance_uuid, key, value): now = timeutils.utcnow() query = sql.UpdateQuery(cls, values=dict(value=value, updated_at=now)) query = query.where(_WHERE_STR, key=key, instance_uuid=instance_uuid) return query.update(conn) @classmethod def insert(cls, conn, instance_uuid, key, value): now = timeutils.utcnow() query = sql.InsertQuery(cls, values=dict(key=key, value=value, created_at=now, deleted=0, instance_uuid=instance_uuid)) return query.insert(conn) @classmethod def soft_delete(cls, conn, instance_uuid, key): return super(Mixin, cls).soft_delete(conn, _WHERE_STR, key=key, instance_uuid=instance_uuid)
apache-2.0
h4ck3rm1k3/FEC-Field-Documentation
fec/version/v2/SH1.py
1
2170
import fechbase class Records(fechbase.RecordsBase): def __init__(self): fechbase.RecordsBase.__init__(self) self.fields = [ {'name': 'FORM TYPE', 'number': '1'}, {'name': 'FILER FEC CMTE ID', 'number': '2'}, {'name': 'NAT PARTY COMMITTEES %', 'number': '3'}, {'name': 'HSE/SEN PTY COMMITTEES', 'number': '4'}, {'name': 'HSE/SEN PTY COMMITTEES PERCENTAGE', 'number': '5'}, {'name': 'HSE/SEN PTY COMMITTEES PERCENTAGE', 'number': '6'}, {'name': 'HSE/SEN PTY COMMITTEES', 'number': '7'}, {'name': 'HSE/SEN PTY COMMITTEES', 'number': '8'}, {'name': 'HSE/SEN PTY COMMITTEES PERCENTAGE', 'number': '9'}, {'name': 'SEP. SEG FUNDS & PERCENTAGE', 'number': '10'}, {'name': 'SEP. SEG FUNDS & PERCENTAGE', 'number': '11'}, {'name': 'SEP. SEG FUNDS &', 'number': '12'}, {'name': 'SEP. SEG FUNDS &', 'number': '13'}, {'name': 'SEP. SEG FUNDS & PERCENTAGE', 'number': '14'}, {'name': 'BALLOT COMP PRES BLANK OR 1', 'number': '15-1.'}, {'name': 'BALLOT COMP SEN BLANK OR 1', 'number': '16-2.'}, {'name': 'BALLOT COMP HSE BLANK OR 1', 'number': '17-3.'}, {'name': 'SUBTOTAL-FED', 'number': '18-4.'}, {'name': 'BALLOT COMP GOV BLANK OR 1', 'number': '19-5.'}, {'name': 'OTHER STATEWIDE', 'number': '20-6.'}, {'name': 'STATE SENATE', 'number': '21-7.'}, {'name': 'STATE REP.', 'number': '22-8.'}, {'name': 'LOCAL CANDIDATES BLANK, 1 OR 2', 'number': '23-9.'}, {'name': 'EXTRA NON-FED POINT BLANK OR 1', 'number': '24-10.'}, {'name': 'SUBTOTAL', 'number': '25-11.'}, {'name': 'TOTAL POINTS', 'number': '26-12.'}, {'name': 'FEDERAL ALLOCATION PERCENTAGE', 'number': '27'}, {'name': 'AMENDED-CD', 'number': '28'}, {'name': 'TRAN_ID', 'number': '29'}, {'name': 'ORIG_TRAN_ID', 'number': '30'}, {'name': 'SUPR_TRAN_ID', 'number': '31'}, ] self.fields_names = self.hash_names(self.fields)
unlicense
alexandrebarachant/mne-python
mne/gui/_marker_gui.py
11
14997
"""Mayavi/traits GUI for averaging two sets of KIT marker points""" # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> # # License: BSD (3-clause) import os import numpy as np # allow import without traits try: from mayavi.core.ui.mayavi_scene import MayaviScene from mayavi.tools.mlab_scene_model import MlabSceneModel from pyface.api import confirm, error, FileDialog, OK, YES from traits.api import (HasTraits, HasPrivateTraits, on_trait_change, cached_property, Instance, Property, Array, Bool, Button, Enum, File, Float, List, Str) from traitsui.api import View, Item, HGroup, VGroup, CheckListEditor from traitsui.menu import NoButtons from tvtk.pyface.scene_editor import SceneEditor except Exception: from ..utils import trait_wraith HasTraits = HasPrivateTraits = object cached_property = on_trait_change = MayaviScene = MlabSceneModel = \ Array = Bool = Button = Enum = File = Float = Instance = Int = \ List = Property = Str = View = Item = HGroup = VGroup = \ CheckListEditor = NoButtons = SceneEditor = trait_wraith from ..transforms import apply_trans, rotation, translation from ..coreg import fit_matched_points from ..io.kit import read_mrk from ..io.meas_info import _write_dig_points from ._viewer import HeadViewController, headview_borders, PointObject backend_is_wx = False # is there a way to determine this? if backend_is_wx: mrk_wildcard = ['Supported Files (*.sqd, *.mrk, *.txt, *.pickled)|' '*.sqd;*.mrk;*.txt;*.pickled', 'Sqd marker file (*.sqd;*.mrk)|*.sqd;*.mrk', 'Text marker file (*.txt)|*.txt', 'Pickled markers (*.pickled)|*.pickled'] mrk_out_wildcard = ["Tab separated values file (*.txt)|*.txt"] else: mrk_wildcard = ["*.sqd;*.mrk;*.txt;*.pickled"] mrk_out_wildcard = "*.txt" out_ext = '.txt' use_editor_v = CheckListEditor(cols=1, values=[(i, str(i)) for i in range(5)]) use_editor_h = CheckListEditor(cols=5, values=[(i, str(i)) for i in range(5)]) mrk_view_editable = View( VGroup('file', Item('name', show_label=False, style='readonly'), HGroup( Item('use', editor=use_editor_v, enabled_when="enabled", style='custom'), 'points', ), HGroup(Item('clear', enabled_when="can_save", show_label=False), Item('save_as', enabled_when="can_save", show_label=False)), )) mrk_view_basic = View( VGroup('file', Item('name', show_label=False, style='readonly'), Item('use', editor=use_editor_h, enabled_when="enabled", style='custom'), HGroup(Item('clear', enabled_when="can_save", show_label=False), Item('edit', show_label=False), Item('save_as', enabled_when="can_save", show_label=False)), )) mrk_view_edit = View(VGroup('points')) class MarkerPoints(HasPrivateTraits): """Represent 5 marker points""" points = Array(float, (5, 3)) can_save = Property(depends_on='points') save_as = Button() view = View(VGroup('points', Item('save_as', enabled_when='can_save'))) @cached_property def _get_can_save(self): return np.any(self.points) def _save_as_fired(self): dlg = FileDialog(action="save as", wildcard=mrk_out_wildcard, default_filename=self.name, default_directory=self.dir) dlg.open() if dlg.return_code != OK: return path, ext = os.path.splitext(dlg.path) if not path.endswith(out_ext) and len(ext) != 0: ValueError("The extension '%s' is not supported." % ext) path = path + out_ext if os.path.exists(path): answer = confirm(None, "The file %r already exists. Should it " "be replaced?", "Overwrite File?") if answer != YES: return self.save(path) def save(self, path): """Save the marker points Parameters ---------- path : str Path to the file to write. The kind of file to write is determined based on the extension: '.txt' for tab separated text file, '.pickled' for pickled file. """ _write_dig_points(path, self.points) class MarkerPointSource(MarkerPoints): """MarkerPoints subclass for source files""" file = File(filter=mrk_wildcard, exists=True) name = Property(Str, depends_on='file') dir = Property(Str, depends_on='file') use = List(list(range(5)), desc="Which points to use for the interpolated " "marker.") enabled = Property(Bool, depends_on=['points', 'use']) clear = Button(desc="Clear the current marker data") edit = Button(desc="Edit the marker coordinates manually") view = mrk_view_basic @cached_property def _get_enabled(self): return np.any(self.points) @cached_property def _get_dir(self): if self.file: return os.path.dirname(self.file) @cached_property def _get_name(self): if self.file: return os.path.basename(self.file) @on_trait_change('file') def load(self, fname): if not fname: self.reset_traits(['points']) return try: pts = read_mrk(fname) except Exception as err: error(None, str(err), "Error Reading mrk") self.reset_traits(['points']) else: self.points = pts def _clear_fired(self): self.reset_traits(['file', 'points', 'use']) def _edit_fired(self): self.edit_traits(view=mrk_view_edit) class MarkerPointDest(MarkerPoints): """MarkerPoints subclass that serves for derived points""" src1 = Instance(MarkerPointSource) src2 = Instance(MarkerPointSource) name = Property(Str, depends_on='src1.name,src2.name') dir = Property(Str, depends_on='src1.dir,src2.dir') points = Property(Array(float, (5, 3)), depends_on=['method', 'src1.points', 'src1.use', 'src2.points', 'src2.use']) enabled = Property(Bool, depends_on=['points']) method = Enum('Transform', 'Average', desc="Transform: estimate a rotation" "/translation from mrk1 to mrk2; Average: use the average " "of the mrk1 and mrk2 coordinates for each point.") view = View(VGroup(Item('method', style='custom'), Item('save_as', enabled_when='can_save', show_label=False))) @cached_property def _get_dir(self): return self.src1.dir @cached_property def _get_name(self): n1 = self.src1.name n2 = self.src2.name if not n1: if n2: return n2 else: return '' elif not n2: return n1 if n1 == n2: return n1 i = 0 l1 = len(n1) - 1 l2 = len(n1) - 2 while n1[i] == n2[i]: if i == l1: return n1 elif i == l2: return n2 i += 1 return n1[:i] @cached_property def _get_enabled(self): return np.any(self.points) @cached_property def _get_points(self): # in case only one or no source is enabled if not (self.src1 and self.src1.enabled): if (self.src2 and self.src2.enabled): return self.src2.points else: return np.zeros((5, 3)) elif not (self.src2 and self.src2.enabled): return self.src1.points # Average method if self.method == 'Average': if len(np.union1d(self.src1.use, self.src2.use)) < 5: error(None, "Need at least one source for each point.", "Marker Average Error") return np.zeros((5, 3)) pts = (self.src1.points + self.src2.points) / 2. for i in np.setdiff1d(self.src1.use, self.src2.use): pts[i] = self.src1.points[i] for i in np.setdiff1d(self.src2.use, self.src1.use): pts[i] = self.src2.points[i] return pts # Transform method idx = np.intersect1d(self.src1.use, self.src2.use, assume_unique=True) if len(idx) < 3: error(None, "Need at least three shared points for trans" "formation.", "Marker Interpolation Error") return np.zeros((5, 3)) src_pts = self.src1.points[idx] tgt_pts = self.src2.points[idx] est = fit_matched_points(src_pts, tgt_pts, out='params') rot = np.array(est[:3]) / 2. tra = np.array(est[3:]) / 2. if len(self.src1.use) == 5: trans = np.dot(translation(*tra), rotation(*rot)) pts = apply_trans(trans, self.src1.points) elif len(self.src2.use) == 5: trans = np.dot(translation(* -tra), rotation(* -rot)) pts = apply_trans(trans, self.src2.points) else: trans1 = np.dot(translation(*tra), rotation(*rot)) pts = apply_trans(trans1, self.src1.points) trans2 = np.dot(translation(* -tra), rotation(* -rot)) for i in np.setdiff1d(self.src2.use, self.src1.use): pts[i] = apply_trans(trans2, self.src2.points[i]) return pts class CombineMarkersModel(HasPrivateTraits): mrk1_file = Instance(File) mrk2_file = Instance(File) mrk1 = Instance(MarkerPointSource) mrk2 = Instance(MarkerPointSource) mrk3 = Instance(MarkerPointDest) clear = Button(desc="Clear the current marker data") # stats distance = Property(Str, depends_on=['mrk1.points', 'mrk2.points']) def _clear_fired(self): self.mrk1.clear = True self.mrk2.clear = True self.mrk3.reset_traits(['method']) def _mrk1_default(self): mrk = MarkerPointSource() return mrk def _mrk1_file_default(self): return self.mrk1.trait('file') def _mrk2_default(self): mrk = MarkerPointSource() return mrk def _mrk2_file_default(self): return self.mrk2.trait('file') def _mrk3_default(self): mrk = MarkerPointDest(src1=self.mrk1, src2=self.mrk2) return mrk @cached_property def _get_distance(self): if (self.mrk1 is None or self.mrk2 is None or (not np.any(self.mrk1.points)) or (not np.any(self.mrk2.points))): return "" ds = np.sqrt(np.sum((self.mrk1.points - self.mrk2.points) ** 2, 1)) desc = '\t'.join('%.1f mm' % (d * 1000) for d in ds) return desc class CombineMarkersPanel(HasTraits): """Has two marker points sources and interpolates to a third one""" model = Instance(CombineMarkersModel, ()) # model references for UI mrk1 = Instance(MarkerPointSource) mrk2 = Instance(MarkerPointSource) mrk3 = Instance(MarkerPointDest) distance = Str # Visualization scene = Instance(MlabSceneModel) scale = Float(5e-3) mrk1_obj = Instance(PointObject) mrk2_obj = Instance(PointObject) mrk3_obj = Instance(PointObject) trans = Array() view = View(VGroup(VGroup(Item('mrk1', style='custom'), Item('mrk1_obj', style='custom'), show_labels=False, label="Source Marker 1", show_border=True), VGroup(Item('mrk2', style='custom'), Item('mrk2_obj', style='custom'), show_labels=False, label="Source Marker 2", show_border=True), VGroup(Item('distance', style='readonly'), label='Stats', show_border=True), VGroup(Item('mrk3', style='custom'), Item('mrk3_obj', style='custom'), show_labels=False, label="New Marker", show_border=True), )) def _mrk1_default(self): return self.model.mrk1 def _mrk2_default(self): return self.model.mrk2 def _mrk3_default(self): return self.model.mrk3 def __init__(self, *args, **kwargs): super(CombineMarkersPanel, self).__init__(*args, **kwargs) m = self.model m.sync_trait('distance', self, 'distance', mutual=False) self.mrk1_obj = PointObject(scene=self.scene, color=(155, 55, 55), point_scale=self.scale) self.sync_trait('trans', self.mrk1_obj, mutual=False) m.mrk1.sync_trait('points', self.mrk1_obj, 'points', mutual=False) m.mrk1.sync_trait('enabled', self.mrk1_obj, 'visible', mutual=False) self.mrk2_obj = PointObject(scene=self.scene, color=(55, 155, 55), point_scale=self.scale) self.sync_trait('trans', self.mrk2_obj, mutual=False) m.mrk2.sync_trait('points', self.mrk2_obj, 'points', mutual=False) m.mrk2.sync_trait('enabled', self.mrk2_obj, 'visible', mutual=False) self.mrk3_obj = PointObject(scene=self.scene, color=(150, 200, 255), point_scale=self.scale) self.sync_trait('trans', self.mrk3_obj, mutual=False) m.mrk3.sync_trait('points', self.mrk3_obj, 'points', mutual=False) m.mrk3.sync_trait('enabled', self.mrk3_obj, 'visible', mutual=False) class CombineMarkersFrame(HasTraits): """GUI for interpolating between two KIT marker files Parameters ---------- mrk1, mrk2 : str Path to pre- and post measurement marker files (*.sqd) or empty string. """ model = Instance(CombineMarkersModel, ()) scene = Instance(MlabSceneModel, ()) headview = Instance(HeadViewController) panel = Instance(CombineMarkersPanel) def _headview_default(self): return HeadViewController(scene=self.scene, system='ALS') def _panel_default(self): return CombineMarkersPanel(model=self.model, scene=self.scene) view = View(HGroup(Item('scene', editor=SceneEditor(scene_class=MayaviScene), dock='vertical'), VGroup(headview_borders, Item('panel', style="custom"), show_labels=False), show_labels=False, ), width=1100, resizable=True, buttons=NoButtons)
bsd-3-clause
pydlv/rlauncher
requests/packages/urllib3/contrib/ntlmpool.py
312
4478
""" NTLM authenticating pool, contributed by erikcederstran Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 """ from __future__ import absolute_import from logging import getLogger from ntlm import ntlm from .. import HTTPSConnectionPool from ..packages.six.moves.http_client import HTTPSConnection log = getLogger(__name__) class NTLMConnectionPool(HTTPSConnectionPool): """ Implements an NTLM authentication version of an urllib3 connection pool """ scheme = 'https' def __init__(self, user, pw, authurl, *args, **kwargs): """ authurl is a random URL on the server that is protected by NTLM. user is the Windows user, probably in the DOMAIN\\username format. pw is the password for the user. """ super(NTLMConnectionPool, self).__init__(*args, **kwargs) self.authurl = authurl self.rawuser = user user_parts = user.split('\\', 1) self.domain = user_parts[0].upper() self.user = user_parts[1] self.pw = pw def _new_conn(self): # Performs the NTLM handshake that secures the connection. The socket # must be kept open while requests are performed. self.num_connections += 1 log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s', self.num_connections, self.host, self.authurl) headers = {} headers['Connection'] = 'Keep-Alive' req_header = 'Authorization' resp_header = 'www-authenticate' conn = HTTPSConnection(host=self.host, port=self.port) # Send negotiation message headers[req_header] = ( 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser)) log.debug('Request headers: %s', headers) conn.request('GET', self.authurl, None, headers) res = conn.getresponse() reshdr = dict(res.getheaders()) log.debug('Response status: %s %s', res.status, res.reason) log.debug('Response headers: %s', reshdr) log.debug('Response data: %s [...]', res.read(100)) # Remove the reference to the socket, so that it can not be closed by # the response object (we want to keep the socket open) res.fp = None # Server should respond with a challenge message auth_header_values = reshdr[resp_header].split(', ') auth_header_value = None for s in auth_header_values: if s[:5] == 'NTLM ': auth_header_value = s[5:] if auth_header_value is None: raise Exception('Unexpected %s response header: %s' % (resp_header, reshdr[resp_header])) # Send authentication message ServerChallenge, NegotiateFlags = \ ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value) auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags) headers[req_header] = 'NTLM %s' % auth_msg log.debug('Request headers: %s', headers) conn.request('GET', self.authurl, None, headers) res = conn.getresponse() log.debug('Response status: %s %s', res.status, res.reason) log.debug('Response headers: %s', dict(res.getheaders())) log.debug('Response data: %s [...]', res.read()[:100]) if res.status != 200: if res.status == 401: raise Exception('Server rejected request: wrong ' 'username or password') raise Exception('Wrong server response: %s %s' % (res.status, res.reason)) res.fp = None log.debug('Connection established') return conn def urlopen(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True): if headers is None: headers = {} headers['Connection'] = 'Keep-Alive' return super(NTLMConnectionPool, self).urlopen(method, url, body, headers, retries, redirect, assert_same_host)
mit
tomleo/djqna
djqna/forum/tests.py
1
3736
from django.test import TestCase from django.contrib.auth.models import User from django.core.urlresolvers import reverse from .models import Question, Answer, Vote from .views import questions, question, answers, answer def make_users(n): return { 'u%s' % i: User(first_name='fn%s' % i, last_name='ln%s' % i, username='fn%sln%s' % (i, i), email='fn%s@ln%s.com' % (i, i)) for i in range(1, n+1) } def save_users(user_dict): for user in user_dict.values(): user.save() return user_dict # Model Tests class TestAnswers(TestCase): def test_positive_vote_counts(self): users = save_users(make_users(4)) q1 = Question.objects.create(title='a', user=users['u1'], text='a') v1 = Vote.objects.create(user=users['u2'], content_object=q1) v2 = Vote.objects.create(user=users['u3'], content_object=q1) v3 = Vote.objects.create(user=users['u4'], content_object=q1) self.assertEqual(v1.object_id, q1.id) self.assertEqual(v1.content_type.name, 'question') self.assertEqual(v1.content_object, q1) q1 = Question.objects.get(pk=q1.pk) # CREAM self.assertEqual(q1.up_votes, 3) self.assertEqual(q1.down_votes, 0) def test_negative_vote_counts(self): users = save_users(make_users(4)) q1 = Question.objects.create(title='a', user=users['u1'], text='a') v1 = Vote.objects.create(user=users['u2'], content_object=q1, is_positive=False) v2 = Vote.objects.create(user=users['u3'], content_object=q1, is_positive=False) v3 = Vote.objects.create(user=users['u4'], content_object=q1, is_positive=False) self.assertEqual(v1.object_id, q1.id) self.assertEqual(v1.content_type.name, 'question') self.assertEqual(v1.content_object, q1) q1 = Question.objects.get(pk=q1.pk) # CREAM self.assertEqual(q1.up_votes, 0) self.assertEqual(q1.down_votes, 3) class TestQuestions(TestCase): pass # View Tests class TestQuestionsView(TestCase): def test_questions(self): users = save_users(make_users(1)) q1 = Question.objects.create(title='a', user=users['u1'], text='a') response = self.client.get(reverse('questions')) tmpl_questions = response.context['questions'] self.assertSetEqual(set(tmpl_questions.values_list('pk', flat=True)), set([q1.id])) class TestQuestionView(TestCase): def test_question(self): users = save_users(make_users(1)) q1 = Question.objects.create(title='a', user=users['u1'], text='a') response = self.client.get(reverse('question', kwargs={'question_id': q1.id})) tmpl_question = response.context['question'] self.assertEqual(tmpl_question.id, q1.id) class TestAnswersView(TestCase): def test_answers(self): users = save_users(make_users(2)) q1 = Question.objects.create(title='a', user=users['u1'], text='a') a1 = Answer.objects.create(title='b', user=users['u2'], text='b', question=q1) response = self.client.get(reverse('answers', kwargs={'question_id': q1.id})) self.assertSetEqual(set(response.context['answers'].values_list('pk', flat=True)), set([a1.id])) class TestAnswerView(TestCase): def test_answer(self): users = save_users(make_users(2)) q1 = Question.objects.create(title='a', user=users['u1'], text='a') a1 = Answer.objects.create(title='b', user=users['u2'], text='b', question=q1) response = self.client.get(reverse('answer', kwargs={'answer_id': a1.id})) self.assertEqual(response.context['answer'].id, a1.id)
gpl-3.0
edgedb/edgedb
docs/conf.py
1
9624
# -*- coding: utf-8 -*- # # EdgeDB documentation build configuration file, created by # sphinx-quickstart on Wed Aug 3 17:58:14 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.viewcode', 'edb.tools.docs', 'sphinxcontrib.asyncio', 'sphinx.ext.intersphinx', ] intersphinx_mapping = {'python': ('https://docs.python.org/3', None)} # Add any paths that contain templates here, relative to this directory. templates_path = [] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'EdgeDB' copyright = u'2016, magicstack' author = u'magicstack' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.5.0' # The full version, including alpha/beta/rc tags. release = '0.5.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False primary_domain = None # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { '**': [ 'globaltoc.html', 'searchbox.html', ] } # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'EdgeDBdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', # Latex figure (float) alignment # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'EdgeDB.tex', u'EdgeDB Documentation', u'magicstack', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'edgedb', u'EdgeDB Documentation', [author], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'EdgeDB', u'EdgeDB Documentation', author, 'EdgeDB', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # config for srclink srclink_project = 'https://github.com/edgedb/edgedb' srclink_src_path = 'doc/' srclink_branch = 'doc'
apache-2.0
mmardini/django
django/contrib/auth/backends.py
42
6113
from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission class ModelBackend(object): """ Authenticates against settings.AUTH_USER_MODEL. """ def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel._default_manager.get_by_natural_key(username) if user.check_password(password): return user except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). UserModel().set_password(password) def _get_user_permissions(self, user_obj): return user_obj.user_permissions.all() def _get_group_permissions(self, user_obj): user_groups_field = get_user_model()._meta.get_field('groups') user_groups_query = 'group__%s' % user_groups_field.related_query_name() return Permission.objects.filter(**{user_groups_query: user_obj}) def _get_permissions(self, user_obj, obj, from_name): """ Returns the permissions of `user_obj` from `from_name`. `from_name` can be either "group" or "user" to return permissions from `_get_group_permissions` or `_get_user_permissions` respectively. """ if not user_obj.is_active or user_obj.is_anonymous() or obj is not None: return set() perm_cache_name = '_%s_perm_cache' % from_name if not hasattr(user_obj, perm_cache_name): if user_obj.is_superuser: perms = Permission.objects.all() else: perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj) perms = perms.values_list('content_type__app_label', 'codename').order_by() setattr(user_obj, perm_cache_name, set("%s.%s" % (ct, name) for ct, name in perms)) return getattr(user_obj, perm_cache_name) def get_user_permissions(self, user_obj, obj=None): """ Returns a set of permission strings the user `user_obj` has from their `user_permissions`. """ return self._get_permissions(user_obj, obj, 'user') def get_group_permissions(self, user_obj, obj=None): """ Returns a set of permission strings the user `user_obj` has from the groups they belong. """ return self._get_permissions(user_obj, obj, 'group') def get_all_permissions(self, user_obj, obj=None): if not user_obj.is_active or user_obj.is_anonymous() or obj is not None: return set() if not hasattr(user_obj, '_perm_cache'): user_obj._perm_cache = self.get_user_permissions(user_obj) user_obj._perm_cache.update(self.get_group_permissions(user_obj)) return user_obj._perm_cache def has_perm(self, user_obj, perm, obj=None): if not user_obj.is_active: return False return perm in self.get_all_permissions(user_obj, obj) def has_module_perms(self, user_obj, app_label): """ Returns True if user_obj has any permissions in the given app_label. """ if not user_obj.is_active: return False for perm in self.get_all_permissions(user_obj): if perm[:perm.index('.')] == app_label: return True return False def get_user(self, user_id): UserModel = get_user_model() try: return UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None class RemoteUserBackend(ModelBackend): """ This backend is to be used in conjunction with the ``RemoteUserMiddleware`` found in the middleware module of this package, and is used when the server is handling authentication outside of Django. By default, the ``authenticate`` method creates ``User`` objects for usernames that don't already exist in the database. Subclasses can disable this behavior by setting the ``create_unknown_user`` attribute to ``False``. """ # Create a User object if not already in the database? create_unknown_user = True def authenticate(self, remote_user): """ The username passed as ``remote_user`` is considered trusted. This method simply returns the ``User`` object with the given username, creating a new ``User`` object if ``create_unknown_user`` is ``True``. Returns None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given username is not found in the database. """ if not remote_user: return user = None username = self.clean_username(remote_user) UserModel = get_user_model() # Note that this could be accomplished in one try-except clause, but # instead we use get_or_create when creating unknown users since it has # built-in safeguards for multiple threads. if self.create_unknown_user: user, created = UserModel._default_manager.get_or_create(**{ UserModel.USERNAME_FIELD: username }) if created: user = self.configure_user(user) else: try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: pass return user def clean_username(self, username): """ Performs any cleaning on the "username" prior to using it to get or create the user object. Returns the cleaned username. By default, returns the username unchanged. """ return username def configure_user(self, user): """ Configures a user after creation and returns the updated user. By default, returns the user unmodified. """ return user
bsd-3-clause