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
lasr/orbital_elements
convert/mee_meeMl0.py
1
1808
import numpy as np from .meefl_meeMl import meefl_meeMl __author__ = "Nathan I. Budd" __email__ = "nibudd@gmail.com" __copyright__ = "Copyright 2017, LASR Lab" __license__ = "MIT" __version__ = "0.1" __status__ = "Production" __date__ = "27 Mar 2017" def mee_meeMl0(T, meeMl0, mu=1.0): """Convert MEEs with mean longitude at epoch to MEEs. Args: T: ndarray (m, 1) array of times. meeMl0: ndarray (m, 6) array of modified equinoctial elements ordered as (p, f, g, h, k, Ml0), where p = semi-latus rectum f = 1-component of ecentricity vector in perifocal frame g = 2-component of eccentricity vector in perifocal frame h = 1-component of the ascending node vector in equinoctial frame k = 2-component of the ascending node vector in equinoctial frame Ml0 = mean longitude at epoch mu: float, optional Standard Gravitational Parameter. Defaults to 1.0, the standard value in canonical units. Returns: mee: ndarray (m, 6) array of modified equinoctial elements ordered as (p, f, g, h, k, L), where p = semi-latus rectum f = 1-component of eccentricity vector in perifocal frame g = 2-component of eccentricity vector in perifocal frame h = 1-component of the ascending node vector in equinoctial frame k = 2-component of the ascending node vector in equinoctial frame L = true longitude """ p = meeMl0[:, 0:1] f = meeMl0[:, 1:2] g = meeMl0[:, 2:3] Ml0 = meeMl0[:, 5:6] a = p / (1 - f**2 - g**2) n = (mu / a**3)**0.5 Ml = Ml0 + n*T return meefl_meeMl(np.concatenate((meeMl0[:, 0:5], Ml), axis=1))
mit
samthor/intellij-community
python/lib/Lib/gzip.py
81
17411
"""Functions that read and write gzipped files. The user of the file doesn't have to worry about the compression, but random access is not allowed.""" # based on Andrew Kuchling's minigzip.py distributed with the zlib module import struct, sys, time import zlib import __builtin__ __all__ = ["GzipFile","open"] FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16 READ, WRITE = 1, 2 def U32(i): """Return i as an unsigned integer, assuming it fits in 32 bits. If it's >= 2GB when viewed as a 32-bit unsigned int, return a long. """ if i < 0: i += 1L << 32 return i def LOWU32(i): """Return the low-order 32 bits of an int, as a non-negative int.""" return i & 0xFFFFFFFFL def write32(output, value): output.write(struct.pack("<l", value)) def write32u(output, value): # The L format writes the bit pattern correctly whether signed # or unsigned. output.write(struct.pack("<L", value)) def read32(input): return struct.unpack("<l", input.read(4))[0] def open(filename, mode="rb", compresslevel=9): """Shorthand for GzipFile(filename, mode, compresslevel). The filename argument is required; mode defaults to 'rb' and compresslevel defaults to 9. """ return GzipFile(filename, mode, compresslevel) class GzipFile: """The GzipFile class simulates most of the methods of a file object with the exception of the readinto() and truncate() methods. """ myfileobj = None # XXX: repeated 10mb chunk reads hurt test_gzip.test_many_append's # performance on Jython (maybe CPython's allocator recycles the same # 10mb buffer whereas Java's doesn't) #max_read_chunk = 10 * 1024 * 1024 # 10Mb max_read_chunk = 256 * 1024 # 256kb def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None): """Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobj, which can be a regular file, a StringIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file object. When fileobj is not None, the filename argument is only used to be included in the gzip file header, which may includes the original filename of the uncompressed file. It defaults to the filename of fileobj, if discernible; otherwise, it defaults to the empty string, and in this case the original filename is not included in the header. The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb', depending on whether the file will be read or written. The default is the mode of fileobj if discernible; otherwise, the default is 'rb'. Be aware that only the 'rb', 'ab', and 'wb' values should be used for cross-platform portability. The compresslevel argument is an integer from 1 to 9 controlling the level of compression; 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression. The default is 9. """ # guarantee the file is opened in binary mode on platforms # that care about that sort of thing if mode and 'b' not in mode: mode += 'b' if fileobj is None: fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb') if filename is None: if hasattr(fileobj, 'name'): filename = fileobj.name else: filename = '' if mode is None: if hasattr(fileobj, 'mode'): mode = fileobj.mode else: mode = 'rb' if mode[0:1] == 'r': self.mode = READ # Set flag indicating start of a new member self._new_member = True self.extrabuf = "" self.extrasize = 0 self.filename = filename # Starts small, scales exponentially self.min_readsize = 100 elif mode[0:1] == 'w' or mode[0:1] == 'a': self.mode = WRITE self._init_write(filename) self.compress = zlib.compressobj(compresslevel, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0) else: raise IOError, "Mode " + mode + " not supported" self.fileobj = fileobj self.offset = 0 if self.mode == WRITE: self._write_gzip_header() def __repr__(self): s = repr(self.fileobj) return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>' def _init_write(self, filename): if filename[-3:] != '.gz': filename = filename + '.gz' self.filename = filename self.crc = zlib.crc32("") self.size = 0 self.writebuf = [] self.bufsize = 0 def _write_gzip_header(self): self.fileobj.write('\037\213') # magic header self.fileobj.write('\010') # compression method fname = self.filename[:-3] flags = 0 if fname: flags = FNAME self.fileobj.write(chr(flags)) write32u(self.fileobj, long(time.time())) self.fileobj.write('\002') self.fileobj.write('\377') if fname: self.fileobj.write(fname + '\000') def _init_read(self): self.crc = zlib.crc32("") self.size = 0 def _read_gzip_header(self): magic = self.fileobj.read(2) if magic != '\037\213': raise IOError, 'Not a gzipped file' method = ord( self.fileobj.read(1) ) if method != 8: raise IOError, 'Unknown compression method' flag = ord( self.fileobj.read(1) ) # modtime = self.fileobj.read(4) # extraflag = self.fileobj.read(1) # os = self.fileobj.read(1) self.fileobj.read(6) if flag & FEXTRA: # Read & discard the extra field, if present xlen = ord(self.fileobj.read(1)) xlen = xlen + 256*ord(self.fileobj.read(1)) self.fileobj.read(xlen) if flag & FNAME: # Read and discard a null-terminated string containing the filename while True: s = self.fileobj.read(1) if not s or s=='\000': break if flag & FCOMMENT: # Read and discard a null-terminated string containing a comment while True: s = self.fileobj.read(1) if not s or s=='\000': break if flag & FHCRC: self.fileobj.read(2) # Read & discard the 16-bit header CRC def write(self,data): if self.mode != WRITE: import errno raise IOError(errno.EBADF, "write() on read-only GzipFile object") if self.fileobj is None: raise ValueError, "write() on closed GzipFile object" if len(data) > 0: self.size = self.size + len(data) self.crc = zlib.crc32(data, self.crc) self.fileobj.write( self.compress.compress(data) ) self.offset += len(data) def read(self, size=-1): if self.mode != READ: import errno raise IOError(errno.EBADF, "read() on write-only GzipFile object") if self.extrasize <= 0 and self.fileobj is None: return '' readsize = 1024 if size < 0: # get the whole thing try: while True: self._read(readsize) readsize = min(self.max_read_chunk, readsize * 2) except EOFError: size = self.extrasize else: # just get some more of it try: while size > self.extrasize: self._read(readsize) readsize = min(self.max_read_chunk, readsize * 2) except EOFError: if size > self.extrasize: size = self.extrasize chunk = self.extrabuf[:size] self.extrabuf = self.extrabuf[size:] self.extrasize = self.extrasize - size self.offset += size return chunk def _unread(self, buf): self.extrabuf = buf + self.extrabuf self.extrasize = len(buf) + self.extrasize self.offset -= len(buf) def _read(self, size=1024): if self.fileobj is None: raise EOFError, "Reached EOF" if self._new_member: # If the _new_member flag is set, we have to # jump to the next member, if there is one. # # First, check if we're at the end of the file; # if so, it's time to stop; no more members to read. pos = self.fileobj.tell() # Save current position self.fileobj.seek(0, 2) # Seek to end of file if pos == self.fileobj.tell(): raise EOFError, "Reached EOF" else: self.fileobj.seek( pos ) # Return to original position self._init_read() self._read_gzip_header() self.decompress = zlib.decompressobj(-zlib.MAX_WBITS) self._new_member = False # Read a chunk of data from the file buf = self.fileobj.read(size) # If the EOF has been reached, flush the decompression object # and mark this object as finished. if buf == "": uncompress = self.decompress.flush() self._read_eof() self._add_read_data( uncompress ) raise EOFError, 'Reached EOF' uncompress = self.decompress.decompress(buf) self._add_read_data( uncompress ) if self.decompress.unused_data != "": # Ending case: we've come to the end of a member in the file, # so seek back to the start of the unused data, finish up # this member, and read a new gzip header. # (The number of bytes to seek back is the length of the unused # data, minus 8 because _read_eof() will rewind a further 8 bytes) self.fileobj.seek( -len(self.decompress.unused_data)+8, 1) # Check the CRC and file size, and set the flag so we read # a new member on the next call self._read_eof() self._new_member = True def _add_read_data(self, data): self.crc = zlib.crc32(data, self.crc) self.extrabuf = self.extrabuf + data self.extrasize = self.extrasize + len(data) self.size = self.size + len(data) def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. Note that the size # stored is the true file size mod 2**32. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = U32(read32(self.fileobj)) # may exceed 2GB if U32(crc32) != U32(self.crc): raise IOError, "CRC check failed" elif isize != LOWU32(self.size): raise IOError, "Incorrect length of data produced" def close(self): if self.mode == WRITE: self.fileobj.write(self.compress.flush()) # The native zlib crc is an unsigned 32-bit integer, but # the Python wrapper implicitly casts that to a signed C # long. So, on a 32-bit box self.crc may "look negative", # while the same crc on a 64-bit box may "look positive". # To avoid irksome warnings from the `struct` module, force # it to look positive on all boxes. write32u(self.fileobj, LOWU32(self.crc)) # self.size may exceed 2GB, or even 4GB write32u(self.fileobj, LOWU32(self.size)) self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfileobj: self.myfileobj.close() self.myfileobj = None def __del__(self): try: if (self.myfileobj is None and self.fileobj is None): return except AttributeError: return self.close() if not sys.platform.startswith('java'): def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH): if self.mode == WRITE: # Ensure the compressor's buffer is flushed self.fileobj.write(self.compress.flush(zlib_mode)) self.fileobj.flush() else: # Java lacks Z_SYNC_FLUSH; thus Jython can't flush the # compressobj until EOF def flush(self,zlib_mode=None): self.fileobj.flush() def fileno(self): """Invoke the underlying file object's fileno() method. This will raise AttributeError if the underlying file object doesn't support fileno(). """ return self.fileobj.fileno() def isatty(self): return False def tell(self): return self.offset def rewind(self): '''Return the uncompressed stream file position indicator to the beginning of the file''' if self.mode != READ: raise IOError("Can't rewind in write mode") self.fileobj.seek(0) self._new_member = True self.extrabuf = "" self.extrasize = 0 self.offset = 0 def seek(self, offset): if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') count = offset - self.offset for i in range(count // 1024): self.write(1024 * '\0') self.write((count % 1024) * '\0') elif self.mode == READ: if offset < self.offset: # for negative seek, rewind and do positive seek self.rewind() count = offset - self.offset for i in range(count // 1024): self.read(1024) self.read(count % 1024) def readline(self, size=-1): if size < 0: size = sys.maxint readsize = self.min_readsize else: readsize = size bufs = [] while size != 0: c = self.read(readsize) i = c.find('\n') # We set i=size to break out of the loop under two # conditions: 1) there's no newline, and the chunk is # larger than size, or 2) there is a newline, but the # resulting line would be longer than 'size'. if (size <= i) or (i == -1 and len(c) > size): i = size - 1 if i >= 0 or c == '': bufs.append(c[:i + 1]) # Add portion of last chunk self._unread(c[i + 1:]) # Push back rest of chunk break # Append chunk to list, decrease 'size', bufs.append(c) size = size - len(c) readsize = min(size, readsize * 2) if readsize > self.min_readsize: self.min_readsize = min(readsize, self.min_readsize * 2, 512) return ''.join(bufs) # Return resulting line def readlines(self, sizehint=0): # Negative numbers result in reading all the lines if sizehint <= 0: sizehint = sys.maxint L = [] while sizehint > 0: line = self.readline() if line == "": break L.append(line) sizehint = sizehint - len(line) return L def writelines(self, L): for line in L: self.write(line) def __iter__(self): return self def next(self): line = self.readline() if line: return line else: raise StopIteration def _test(): # Act like gzip; with -d, act like gunzip. # The input file is not deleted, however, nor are any other gzip # options or features supported. args = sys.argv[1:] decompress = args and args[0] == "-d" if decompress: args = args[1:] if not args: args = ["-"] for arg in args: if decompress: if arg == "-": f = GzipFile(filename="", mode="rb", fileobj=sys.stdin) g = sys.stdout else: if arg[-3:] != ".gz": print "filename doesn't end in .gz:", repr(arg) continue f = open(arg, "rb") g = __builtin__.open(arg[:-3], "wb") else: if arg == "-": f = sys.stdin g = GzipFile(filename="", mode="wb", fileobj=sys.stdout) else: f = __builtin__.open(arg, "rb") g = open(arg + ".gz", "wb") while True: chunk = f.read(1024) if not chunk: break g.write(chunk) if g is not sys.stdout: g.close() if f is not sys.stdin: f.close() if __name__ == '__main__': _test()
apache-2.0
minghuascode/pyj
examples/minesweeper/__main__.py
8
1057
#!/usr/bin/env python # -*- coding: utf-8 -*- TARGETS = [ 'minesweeper.py', ] PACKAGE = { 'title': 'minesweeper', 'desc': 'minesweeper example', } def setup(targets): '''Setup example for translation, MUST call util.setup(targets).''' util.setup(targets) def translate(): '''Translate example, MUST call util.translate().''' util.translate() def install(package): '''Install and cleanup example module. MUST call util.install(package)''' util.install(package) ##---------------------------------------## # --------- (-: DO NOT EDIT :-) --------- # ##---------------------------------------## import sys import os examples = head = os.path.abspath(os.path.dirname(__file__)) while os.path.split(examples)[1].lower() != 'examples': examples = os.path.split(examples)[0] if not examples: raise ValueError("Cannot determine examples directory") sys.path.insert(0, os.path.join(examples)) from _examples import util sys.path.pop(0) util.init(head) setup(TARGETS) translate() install(PACKAGE)
apache-2.0
tsufiev/horizon
openstack_dashboard/dashboards/project/data_processing/data_plugins/tables.py
51
1400
# 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 logging from django.template import defaultfilters as filters from django.utils.translation import ugettext_lazy as _ from horizon import tables LOG = logging.getLogger(__name__) class PluginsTable(tables.DataTable): title = tables.Column("title", verbose_name=_("Title"), link=("horizon:project:data_processing." "data_plugins:details")) versions = tables.Column("versions", verbose_name=_("Supported Versions"), wrap_list=True, filters=(filters.unordered_list,)) description = tables.Column("description", verbose_name=_("Description")) class Meta(object): name = "plugins" verbose_name = _("Plugins")
apache-2.0
ericlink/adms-server
playframework-dist/1.1-src/python/Lib/distutils/dep_util.py
2
3665
"""distutils.dep_util Utility functions for simple, timestamp-based dependency of files and groups of files; also, function based entirely on such timestamp dependency analysis.""" # This module should be kept compatible with Python 2.1. __revision__ = "$Id: dep_util.py 37828 2004-11-10 22:23:15Z loewis $" import os from distutils.errors import DistutilsFileError def newer (source, target): """Return true if 'source' exists and is more recently modified than 'target', or if 'source' exists and 'target' doesn't. Return false if both exist and 'target' is the same age or younger than 'source'. Raise DistutilsFileError if 'source' does not exist. """ if not os.path.exists(source): raise DistutilsFileError, "file '%s' does not exist" % source if not os.path.exists(target): return 1 from stat import ST_MTIME mtime1 = os.stat(source)[ST_MTIME] mtime2 = os.stat(target)[ST_MTIME] return mtime1 > mtime2 # newer () def newer_pairwise (sources, targets): """Walk two filename lists in parallel, testing if each source is newer than its corresponding target. Return a pair of lists (sources, targets) where source is newer than target, according to the semantics of 'newer()'. """ if len(sources) != len(targets): raise ValueError, "'sources' and 'targets' must be same length" # build a pair of lists (sources, targets) where source is newer n_sources = [] n_targets = [] for i in range(len(sources)): if newer(sources[i], targets[i]): n_sources.append(sources[i]) n_targets.append(targets[i]) return (n_sources, n_targets) # newer_pairwise () def newer_group (sources, target, missing='error'): """Return true if 'target' is out-of-date with respect to any file listed in 'sources'. In other words, if 'target' exists and is newer than every file in 'sources', return false; otherwise return true. 'missing' controls what we do when a source file is missing; the default ("error") is to blow up with an OSError from inside 'stat()'; if it is "ignore", we silently drop any missing source files; if it is "newer", any missing source files make us assume that 'target' is out-of-date (this is handy in "dry-run" mode: it'll make you pretend to carry out commands that wouldn't work because inputs are missing, but that doesn't matter because you're not actually going to run the commands). """ # If the target doesn't even exist, then it's definitely out-of-date. if not os.path.exists(target): return 1 # Otherwise we have to find out the hard way: if *any* source file # is more recent than 'target', then 'target' is out-of-date and # we can immediately return true. If we fall through to the end # of the loop, then 'target' is up-to-date and we return false. from stat import ST_MTIME target_mtime = os.stat(target)[ST_MTIME] for source in sources: if not os.path.exists(source): if missing == 'error': # blow up when we stat() the file pass elif missing == 'ignore': # missing source dropped from continue # target's dependency list elif missing == 'newer': # missing source means target is return 1 # out-of-date source_mtime = os.stat(source)[ST_MTIME] if source_mtime > target_mtime: return 1 else: return 0 # newer_group ()
mit
salivatears/ansible
contrib/inventory/abiquo.py
39
8967
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' External inventory script for Abiquo ==================================== Shamelessly copied from an existing inventory script. This script generates an inventory that Ansible can understand by making API requests to Abiquo API Requires some python libraries, ensure to have them installed when using this script. This script has been tested in Abiquo 3.0 but it may work also for Abiquo 2.6. Before using this script you may want to modify abiquo.ini config file. This script generates an Ansible hosts file with these host groups: ABQ_xxx: Defines a hosts itself by Abiquo VM name label all: Contains all hosts defined in Abiquo user's enterprise virtualdatecenter: Creates a host group for each virtualdatacenter containing all hosts defined on it virtualappliance: Creates a host group for each virtualappliance containing all hosts defined on it imagetemplate: Creates a host group for each image template containing all hosts using it ''' # (c) 2014, Daniel Beneyto <daniel.beneyto@abiquo.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 import sys import time import ConfigParser import urllib2 import base64 try: import json except ImportError: import simplejson as json def api_get(link, config): try: if link == None: request = urllib2.Request(config.get('api','uri')+config.get('api','login_path')) request.add_header("Accept",config.get('api','login_type')) else: request = urllib2.Request(link['href']+'?limit=0') request.add_header("Accept",link['type']) # Auth base64string = base64.encodestring('%s:%s' % (config.get('auth','apiuser'),config.get('auth','apipass'))).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) result = urllib2.urlopen(request) return json.loads(result.read()) except: return None def save_cache(data, config): ''' saves item to cache ''' dpath = config.get('cache','cache_dir') try: cache = open('/'.join([dpath,'inventory']), 'w') cache.write(json.dumps(data)) cache.close() except IOError as e: pass # not really sure what to do here def get_cache(cache_item, config): ''' returns cached item ''' dpath = config.get('cache','cache_dir') inv = {} try: cache = open('/'.join([dpath,'inventory']), 'r') inv = cache.read() cache.close() except IOError as e: pass # not really sure what to do here return inv def cache_available(config): ''' checks if we have a 'fresh' cache available for item requested ''' if config.has_option('cache','cache_dir'): dpath = config.get('cache','cache_dir') try: existing = os.stat( '/'.join([dpath,'inventory'])) except: # cache doesn't exist or isn't accessible return False if config.has_option('cache', 'cache_max_age'): maxage = config.get('cache', 'cache_max_age') if ((int(time.time()) - int(existing.st_mtime)) <= int(maxage)): return True return False def generate_inv_from_api(enterprise_entity,config): try: inventory['all'] = {} inventory['all']['children'] = [] inventory['all']['hosts'] = [] inventory['_meta'] = {} inventory['_meta']['hostvars'] = {} enterprise = api_get(enterprise_entity,config) vms_entity = next(link for link in (enterprise['links']) if (link['rel']=='virtualmachines')) vms = api_get(vms_entity,config) for vmcollection in vms['collection']: vm_vapp = next(link for link in (vmcollection['links']) if (link['rel']=='virtualappliance'))['title'].replace('[','').replace(']','').replace(' ','_') vm_vdc = next(link for link in (vmcollection['links']) if (link['rel']=='virtualdatacenter'))['title'].replace('[','').replace(']','').replace(' ','_') vm_template = next(link for link in (vmcollection['links']) if (link['rel']=='virtualmachinetemplate'))['title'].replace('[','').replace(']','').replace(' ','_') # From abiquo.ini: Only adding to inventory VMs with public IP if (config.getboolean('defaults', 'public_ip_only')) == True: for link in vmcollection['links']: if (link['type']=='application/vnd.abiquo.publicip+json' and link['rel']=='ip'): vm_nic = link['title'] break else: vm_nic = None # Otherwise, assigning defined network interface IP address else: for link in vmcollection['links']: if (link['rel']==config.get('defaults', 'default_net_interface')): vm_nic = link['title'] break else: vm_nic = None vm_state = True # From abiquo.ini: Only adding to inventory VMs deployed if ((config.getboolean('defaults', 'deployed_only') == True) and (vmcollection['state'] == 'NOT_ALLOCATED')): vm_state = False if not vm_nic == None and vm_state: if not vm_vapp in inventory.keys(): inventory[vm_vapp] = {} inventory[vm_vapp]['children'] = [] inventory[vm_vapp]['hosts'] = [] if not vm_vdc in inventory.keys(): inventory[vm_vdc] = {} inventory[vm_vdc]['hosts'] = [] inventory[vm_vdc]['children'] = [] if not vm_template in inventory.keys(): inventory[vm_template] = {} inventory[vm_template]['children'] = [] inventory[vm_template]['hosts'] = [] if config.getboolean('defaults', 'get_metadata') == True: meta_entity = next(link for link in (vmcollection['links']) if (link['rel']=='metadata')) try: metadata = api_get(meta_entity,config) if (config.getfloat("api","version") >= 3.0): vm_metadata = metadata['metadata'] else: vm_metadata = metadata['metadata']['metadata'] inventory['_meta']['hostvars'][vm_nic] = vm_metadata except Exception as e: pass inventory[vm_vapp]['children'].append(vmcollection['name']) inventory[vm_vdc]['children'].append(vmcollection['name']) inventory[vm_template]['children'].append(vmcollection['name']) inventory['all']['children'].append(vmcollection['name']) inventory[vmcollection['name']] = [] inventory[vmcollection['name']].append(vm_nic) return inventory except Exception as e: # Return empty hosts output return { 'all': {'hosts': []}, '_meta': { 'hostvars': {} } } def get_inventory(enterprise, config): ''' Reads the inventory from cache or Abiquo api ''' if cache_available(config): inv = get_cache('inventory', config) else: default_group = os.path.basename(sys.argv[0]).rstrip('.py') # MAKE ABIQUO API CALLS # inv = generate_inv_from_api(enterprise,config) save_cache(inv, config) return json.dumps(inv) if __name__ == '__main__': inventory = {} enterprise = {} # Read config config = ConfigParser.SafeConfigParser() for configfilename in [os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'abiquo.ini']: if os.path.exists(configfilename): config.read(configfilename) break try: login = api_get(None,config) enterprise = next(link for link in (login['links']) if (link['rel']=='enterprise')) except Exception as e: enterprise = None if cache_available(config): inventory = get_cache('inventory', config) else: inventory = get_inventory(enterprise, config) # return to ansible sys.stdout.write(str(inventory)) sys.stdout.flush()
gpl-3.0
letuananh/puchikarui
docs/conf.py
1
1903
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # 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. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'puchikarui' copyright = '2021, Le Tuan Anh <tuananh.ke@gmail.com>' author = 'Le Tuan Anh <tuananh.ke@gmail.com>' # -- General configuration --------------------------------------------------- # 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'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- 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' # 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']
mit
Azure/azure-sdk-for-python
sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mariadb/operations/_log_files_operations.py
1
5652
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class LogFilesOperations(object): """LogFilesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.rdbms.mariadb.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_server( self, resource_group_name, # type: str server_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.LogFileListResult"] """List all the log files in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param server_name: The name of the server. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LogFileListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.LogFileListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.LogFileListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-06-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_server.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'serverName': self._serialize.url("server_name", server_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('LogFileListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/logFiles'} # type: ignore
mit
qtproject/qtqa
scripts/generic/parse_build_log.py
1
5630
############################################################################ ## ## Copyright (C) 2019 The Qt Company Ltd. ## Contact: https://www.qt.io/licensing/ ## ## This file is part of the Quality Assurance module of the Qt Toolkit. ## ## $QT_BEGIN_LICENSE:GPL-EXCEPT$ ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance with the commercial license agreement provided with the ## Software or, alternatively, in accordance with the terms contained in ## a written agreement between you and The Qt Company. For licensing terms ## and conditions see https://www.qt.io/terms-conditions. For further ## information use the contact form at https://www.qt.io/contact-us. ## ## GNU General Public License Usage ## Alternatively, this file may be used under the terms of the GNU ## General Public License version 3 as published by the Free Software ## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ## included in the packaging of this file. Please review the following ## information to ensure the GNU General Public License requirements will ## be met: https://www.gnu.org/licenses/gpl-3.0.html. ## ## $QT_END_LICENSE$ ## ############################################################################# import re import subprocess import sys usage = """ Usage: parse_build_log.py [log_file] Parses the output of COIN test runs and prints short summaries of compile errors and test fails for usage as gerrit comment. Takes the file name (either text or compressed .gz file). The zcat tool is required for decompressing .gz files. """ # Match the log prefix "agent:2019/06/04 12:32:54 agent.go:262:" prefix_re = re.compile(r'^agent:[\d :/]+\w+\.go:\d+: ') # Match QTestlib output start_test_re = re.compile(r'^\*{9} Start testing of \w+ \*{9}$') end_test_re = re.compile(r'Totals: \d+ passed, (\d+) failed, \d+ skipped, \d+ blacklisted, \d+ms') end_test_crash_re = re.compile(r'\d+/\d+\sTest\s#\d+:.*\*\*\*Failed.*') make_error_re = re.compile(r'make\[.*Error \d+$') def read_file(file_name): """ Read a text file into a list of of chopped lines. """ with open(file_name) as f: return [prefix_re.sub('', l.rstrip()) for l in f.readlines()] def zcat(file_name): """ Read a gzip'ed text file into a list of of chopped lines by means of 'zcat'. Note: Python's zipfile module cannot handle .gz """ lines = [] try: std_out = subprocess.Popen(['zcat', file_name], universal_newlines=1, stdout=subprocess.PIPE).stdout for line in std_out.readlines(): lines.append(prefix_re.sub('', line.rstrip())) std_out.close() except FileNotFoundError: print("ERROR: command 'zcat' not found") sys.exit(-1) return lines def is_compile_error(line): """ Return whether a line is an error from one of the common compilers (g++, MSVC, Python) """ if any(e in line for e in (": error: ", ": error C", "SyntaxError:", "NameError:")): # Ignore error messages in debug output # and also ignore the final ERROR building message, as that one would only print sccache # output if not ("QDEBUG" in line or "QWARN" in line): logging.debug(f"===> Found error in line \n{line}\n") return True has_error = make_error_re.match(line) if has_error: logging.debug(f"===> Found error in line \n{line}\n") return has_error def print_failed_test(lines, start, end): """ For a failed test, print 3 lines following the FAIL!/XPASS and header/footer. """ last_fail = -50 # Print 3 lines after a failure print('\n{}: {}'.format(start, lines[start])) for i in range(start + 1, end): line = lines[i] if 'FAIL!' in line or 'XPASS' or '***Failed' in line: last_fail = i if i - last_fail < 4: print(line) print('{}\n'.format(lines[end])) def parse(lines): """ Parse the output and print compile/test errors. """ test_start_line = -1 within_configure_tests = False for i, line in enumerate(lines): if within_configure_tests: if line == 'Done running configuration tests.': within_configure_tests = False elif test_start_line >= 0: end_match = end_test_re.match(line) if end_match: fails = int(end_match.group(1)) if fails: print_failed_test(lines, test_start_line, i) test_start_line = -1 elif end_test_crash_re.match(line): logging.debug(f"===> test crashed {line} {test_start_line} {i}") print_failed_test(lines, test_start_line, i) test_start_line = -1 # Do not report errors within configuration tests elif line == 'Running configuration tests...': within_configure_tests = True elif start_test_re.match(line): test_start_line = i elif is_compile_error(line): start = max(0, i - 10) sys.stdout.write('\n{}: '.format(start)) for e in range(start, i + 1): print(lines[e]) if __name__ == '__main__': if sys.version_info[0] != 3: print("This script requires Python 3") sys.exit(-2) if len(sys.argv) < 2: print(usage) sys.exit(-1) file_name = sys.argv[1] lines = zcat(file_name) if file_name.endswith('.gz') else read_file(file_name) parse(lines)
gpl-3.0
martydill/url_shortener
code/venv/lib/python2.7/site-packages/sqlalchemy/orm/dependency.py
70
46073
# orm/dependency.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 """Relationship dependencies. """ from .. import sql, util, exc as sa_exc from . import attributes, exc, sync, unitofwork, \ util as mapperutil from .interfaces import ONETOMANY, MANYTOONE, MANYTOMANY class DependencyProcessor(object): def __init__(self, prop): self.prop = prop self.cascade = prop.cascade self.mapper = prop.mapper self.parent = prop.parent self.secondary = prop.secondary self.direction = prop.direction self.post_update = prop.post_update self.passive_deletes = prop.passive_deletes self.passive_updates = prop.passive_updates self.enable_typechecks = prop.enable_typechecks if self.passive_deletes: self._passive_delete_flag = attributes.PASSIVE_NO_INITIALIZE else: self._passive_delete_flag = attributes.PASSIVE_OFF if self.passive_updates: self._passive_update_flag = attributes.PASSIVE_NO_INITIALIZE else: self._passive_update_flag = attributes.PASSIVE_OFF self.key = prop.key if not self.prop.synchronize_pairs: raise sa_exc.ArgumentError( "Can't build a DependencyProcessor for relationship %s. " "No target attributes to populate between parent and " "child are present" % self.prop) @classmethod def from_relationship(cls, prop): return _direction_to_processor[prop.direction](prop) def hasparent(self, state): """return True if the given object instance has a parent, according to the ``InstrumentedAttribute`` handled by this ``DependencyProcessor``. """ return self.parent.class_manager.get_impl(self.key).hasparent(state) def per_property_preprocessors(self, uow): """establish actions and dependencies related to a flush. These actions will operate on all relevant states in the aggregate. """ uow.register_preprocessor(self, True) def per_property_flush_actions(self, uow): after_save = unitofwork.ProcessAll(uow, self, False, True) before_delete = unitofwork.ProcessAll(uow, self, True, True) parent_saves = unitofwork.SaveUpdateAll( uow, self.parent.primary_base_mapper ) child_saves = unitofwork.SaveUpdateAll( uow, self.mapper.primary_base_mapper ) parent_deletes = unitofwork.DeleteAll( uow, self.parent.primary_base_mapper ) child_deletes = unitofwork.DeleteAll( uow, self.mapper.primary_base_mapper ) self.per_property_dependencies(uow, parent_saves, child_saves, parent_deletes, child_deletes, after_save, before_delete ) def per_state_flush_actions(self, uow, states, isdelete): """establish actions and dependencies related to a flush. These actions will operate on all relevant states individually. This occurs only if there are cycles in the 'aggregated' version of events. """ parent_base_mapper = self.parent.primary_base_mapper child_base_mapper = self.mapper.primary_base_mapper child_saves = unitofwork.SaveUpdateAll(uow, child_base_mapper) child_deletes = unitofwork.DeleteAll(uow, child_base_mapper) # locate and disable the aggregate processors # for this dependency if isdelete: before_delete = unitofwork.ProcessAll(uow, self, True, True) before_delete.disabled = True else: after_save = unitofwork.ProcessAll(uow, self, False, True) after_save.disabled = True # check if the "child" side is part of the cycle if child_saves not in uow.cycles: # based on the current dependencies we use, the saves/ # deletes should always be in the 'cycles' collection # together. if this changes, we will have to break up # this method a bit more. assert child_deletes not in uow.cycles # child side is not part of the cycle, so we will link per-state # actions to the aggregate "saves", "deletes" actions child_actions = [ (child_saves, False), (child_deletes, True) ] child_in_cycles = False else: child_in_cycles = True # check if the "parent" side is part of the cycle if not isdelete: parent_saves = unitofwork.SaveUpdateAll( uow, self.parent.base_mapper) parent_deletes = before_delete = None if parent_saves in uow.cycles: parent_in_cycles = True else: parent_deletes = unitofwork.DeleteAll( uow, self.parent.base_mapper) parent_saves = after_save = None if parent_deletes in uow.cycles: parent_in_cycles = True # now create actions /dependencies for each state. for state in states: # detect if there's anything changed or loaded # by a preprocessor on this state/attribute. In the # case of deletes we may try to load missing items here as well. sum_ = state.manager[self.key].impl.get_all_pending( state, state.dict, self._passive_delete_flag if isdelete else attributes.PASSIVE_NO_INITIALIZE) if not sum_: continue if isdelete: before_delete = unitofwork.ProcessState(uow, self, True, state) if parent_in_cycles: parent_deletes = unitofwork.DeleteState( uow, state, parent_base_mapper) else: after_save = unitofwork.ProcessState(uow, self, False, state) if parent_in_cycles: parent_saves = unitofwork.SaveUpdateState( uow, state, parent_base_mapper) if child_in_cycles: child_actions = [] for child_state, child in sum_: if child_state not in uow.states: child_action = (None, None) else: (deleted, listonly) = uow.states[child_state] if deleted: child_action = ( unitofwork.DeleteState( uow, child_state, child_base_mapper), True) else: child_action = ( unitofwork.SaveUpdateState( uow, child_state, child_base_mapper), False) child_actions.append(child_action) # establish dependencies between our possibly per-state # parent action and our possibly per-state child action. for child_action, childisdelete in child_actions: self.per_state_dependencies(uow, parent_saves, parent_deletes, child_action, after_save, before_delete, isdelete, childisdelete) def presort_deletes(self, uowcommit, states): return False def presort_saves(self, uowcommit, states): return False def process_deletes(self, uowcommit, states): pass def process_saves(self, uowcommit, states): pass def prop_has_changes(self, uowcommit, states, isdelete): if not isdelete or self.passive_deletes: passive = attributes.PASSIVE_NO_INITIALIZE elif self.direction is MANYTOONE: passive = attributes.PASSIVE_NO_FETCH_RELATED else: passive = attributes.PASSIVE_OFF for s in states: # TODO: add a high speed method # to InstanceState which returns: attribute # has a non-None value, or had one history = uowcommit.get_attribute_history( s, self.key, passive) if history and not history.empty(): return True else: return states and \ not self.prop._is_self_referential and \ self.mapper in uowcommit.mappers def _verify_canload(self, state): if self.prop.uselist and state is None: raise exc.FlushError( "Can't flush None value found in " "collection %s" % (self.prop, )) elif state is not None and \ not self.mapper._canload( state, allow_subtypes=not self.enable_typechecks): if self.mapper._canload(state, allow_subtypes=True): raise exc.FlushError('Attempting to flush an item of type ' '%(x)s as a member of collection ' '"%(y)s". Expected an object of type ' '%(z)s or a polymorphic subclass of ' 'this type. If %(x)s is a subclass of ' '%(z)s, configure mapper "%(zm)s" to ' 'load this subtype polymorphically, or ' 'set enable_typechecks=False to allow ' 'any subtype to be accepted for flush. ' % { 'x': state.class_, 'y': self.prop, 'z': self.mapper.class_, 'zm': self.mapper, }) else: raise exc.FlushError( 'Attempting to flush an item of type ' '%(x)s as a member of collection ' '"%(y)s". Expected an object of type ' '%(z)s or a polymorphic subclass of ' 'this type.' % { 'x': state.class_, 'y': self.prop, 'z': self.mapper.class_, }) def _synchronize(self, state, child, associationrow, clearkeys, uowcommit): raise NotImplementedError() def _get_reversed_processed_set(self, uow): if not self.prop._reverse_property: return None process_key = tuple(sorted( [self.key] + [p.key for p in self.prop._reverse_property] )) return uow.memo( ('reverse_key', process_key), set ) def _post_update(self, state, uowcommit, related): for x in related: if x is not None: uowcommit.issue_post_update( state, [r for l, r in self.prop.synchronize_pairs] ) break def _pks_changed(self, uowcommit, state): raise NotImplementedError() def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.prop) class OneToManyDP(DependencyProcessor): def per_property_dependencies(self, uow, parent_saves, child_saves, parent_deletes, child_deletes, after_save, before_delete, ): if self.post_update: child_post_updates = unitofwork.IssuePostUpdate( uow, self.mapper.primary_base_mapper, False) child_pre_updates = unitofwork.IssuePostUpdate( uow, self.mapper.primary_base_mapper, True) uow.dependencies.update([ (child_saves, after_save), (parent_saves, after_save), (after_save, child_post_updates), (before_delete, child_pre_updates), (child_pre_updates, parent_deletes), (child_pre_updates, child_deletes), ]) else: uow.dependencies.update([ (parent_saves, after_save), (after_save, child_saves), (after_save, child_deletes), (child_saves, parent_deletes), (child_deletes, parent_deletes), (before_delete, child_saves), (before_delete, child_deletes), ]) def per_state_dependencies(self, uow, save_parent, delete_parent, child_action, after_save, before_delete, isdelete, childisdelete): if self.post_update: child_post_updates = unitofwork.IssuePostUpdate( uow, self.mapper.primary_base_mapper, False) child_pre_updates = unitofwork.IssuePostUpdate( uow, self.mapper.primary_base_mapper, True) # TODO: this whole block is not covered # by any tests if not isdelete: if childisdelete: uow.dependencies.update([ (child_action, after_save), (after_save, child_post_updates), ]) else: uow.dependencies.update([ (save_parent, after_save), (child_action, after_save), (after_save, child_post_updates), ]) else: if childisdelete: uow.dependencies.update([ (before_delete, child_pre_updates), (child_pre_updates, delete_parent), ]) else: uow.dependencies.update([ (before_delete, child_pre_updates), (child_pre_updates, delete_parent), ]) elif not isdelete: uow.dependencies.update([ (save_parent, after_save), (after_save, child_action), (save_parent, child_action) ]) else: uow.dependencies.update([ (before_delete, child_action), (child_action, delete_parent) ]) def presort_deletes(self, uowcommit, states): # head object is being deleted, and we manage its list of # child objects the child objects have to have their # foreign key to the parent set to NULL should_null_fks = not self.cascade.delete and \ not self.passive_deletes == 'all' for state in states: history = uowcommit.get_attribute_history( state, self.key, self._passive_delete_flag) if history: for child in history.deleted: if child is not None and self.hasparent(child) is False: if self.cascade.delete_orphan: uowcommit.register_object(child, isdelete=True) else: uowcommit.register_object(child) if should_null_fks: for child in history.unchanged: if child is not None: uowcommit.register_object( child, operation="delete", prop=self.prop) def presort_saves(self, uowcommit, states): children_added = uowcommit.memo(('children_added', self), set) for state in states: pks_changed = self._pks_changed(uowcommit, state) if not pks_changed or self.passive_updates: passive = attributes.PASSIVE_NO_INITIALIZE else: passive = attributes.PASSIVE_OFF history = uowcommit.get_attribute_history( state, self.key, passive) if history: for child in history.added: if child is not None: uowcommit.register_object(child, cancel_delete=True, operation="add", prop=self.prop) children_added.update(history.added) for child in history.deleted: if not self.cascade.delete_orphan: uowcommit.register_object(child, isdelete=False, operation='delete', prop=self.prop) elif self.hasparent(child) is False: uowcommit.register_object( child, isdelete=True, operation="delete", prop=self.prop) for c, m, st_, dct_ in self.mapper.cascade_iterator( 'delete', child): uowcommit.register_object( st_, isdelete=True) if pks_changed: if history: for child in history.unchanged: if child is not None: uowcommit.register_object( child, False, self.passive_updates, operation="pk change", prop=self.prop) def process_deletes(self, uowcommit, states): # head object is being deleted, and we manage its list of # child objects the child objects have to have their foreign # key to the parent set to NULL this phase can be called # safely for any cascade but is unnecessary if delete cascade # is on. if self.post_update or not self.passive_deletes == 'all': children_added = uowcommit.memo(('children_added', self), set) for state in states: history = uowcommit.get_attribute_history( state, self.key, self._passive_delete_flag) if history: for child in history.deleted: if child is not None and \ self.hasparent(child) is False: self._synchronize( state, child, None, True, uowcommit, False) if self.post_update and child: self._post_update(child, uowcommit, [state]) if self.post_update or not self.cascade.delete: for child in set(history.unchanged).\ difference(children_added): if child is not None: self._synchronize( state, child, None, True, uowcommit, False) if self.post_update and child: self._post_update(child, uowcommit, [state]) # technically, we can even remove each child from the # collection here too. but this would be a somewhat # inconsistent behavior since it wouldn't happen # if the old parent wasn't deleted but child was moved. def process_saves(self, uowcommit, states): for state in states: history = uowcommit.get_attribute_history( state, self.key, attributes.PASSIVE_NO_INITIALIZE) if history: for child in history.added: self._synchronize(state, child, None, False, uowcommit, False) if child is not None and self.post_update: self._post_update(child, uowcommit, [state]) for child in history.deleted: if not self.cascade.delete_orphan and \ not self.hasparent(child): self._synchronize(state, child, None, True, uowcommit, False) if self._pks_changed(uowcommit, state): for child in history.unchanged: self._synchronize(state, child, None, False, uowcommit, True) def _synchronize(self, state, child, associationrow, clearkeys, uowcommit, pks_changed): source = state dest = child self._verify_canload(child) if dest is None or \ (not self.post_update and uowcommit.is_deleted(dest)): return if clearkeys: sync.clear(dest, self.mapper, self.prop.synchronize_pairs) else: sync.populate(source, self.parent, dest, self.mapper, self.prop.synchronize_pairs, uowcommit, self.passive_updates and pks_changed) def _pks_changed(self, uowcommit, state): return sync.source_modified( uowcommit, state, self.parent, self.prop.synchronize_pairs) class ManyToOneDP(DependencyProcessor): def __init__(self, prop): DependencyProcessor.__init__(self, prop) self.mapper._dependency_processors.append(DetectKeySwitch(prop)) def per_property_dependencies(self, uow, parent_saves, child_saves, parent_deletes, child_deletes, after_save, before_delete): if self.post_update: parent_post_updates = unitofwork.IssuePostUpdate( uow, self.parent.primary_base_mapper, False) parent_pre_updates = unitofwork.IssuePostUpdate( uow, self.parent.primary_base_mapper, True) uow.dependencies.update([ (child_saves, after_save), (parent_saves, after_save), (after_save, parent_post_updates), (after_save, parent_pre_updates), (before_delete, parent_pre_updates), (parent_pre_updates, child_deletes), ]) else: uow.dependencies.update([ (child_saves, after_save), (after_save, parent_saves), (parent_saves, child_deletes), (parent_deletes, child_deletes) ]) def per_state_dependencies(self, uow, save_parent, delete_parent, child_action, after_save, before_delete, isdelete, childisdelete): if self.post_update: if not isdelete: parent_post_updates = unitofwork.IssuePostUpdate( uow, self.parent.primary_base_mapper, False) if childisdelete: uow.dependencies.update([ (after_save, parent_post_updates), (parent_post_updates, child_action) ]) else: uow.dependencies.update([ (save_parent, after_save), (child_action, after_save), (after_save, parent_post_updates) ]) else: parent_pre_updates = unitofwork.IssuePostUpdate( uow, self.parent.primary_base_mapper, True) uow.dependencies.update([ (before_delete, parent_pre_updates), (parent_pre_updates, delete_parent), (parent_pre_updates, child_action) ]) elif not isdelete: if not childisdelete: uow.dependencies.update([ (child_action, after_save), (after_save, save_parent), ]) else: uow.dependencies.update([ (after_save, save_parent), ]) else: if childisdelete: uow.dependencies.update([ (delete_parent, child_action) ]) def presort_deletes(self, uowcommit, states): if self.cascade.delete or self.cascade.delete_orphan: for state in states: history = uowcommit.get_attribute_history( state, self.key, self._passive_delete_flag) if history: if self.cascade.delete_orphan: todelete = history.sum() else: todelete = history.non_deleted() for child in todelete: if child is None: continue uowcommit.register_object( child, isdelete=True, operation="delete", prop=self.prop) t = self.mapper.cascade_iterator('delete', child) for c, m, st_, dct_ in t: uowcommit.register_object( st_, isdelete=True) def presort_saves(self, uowcommit, states): for state in states: uowcommit.register_object(state, operation="add", prop=self.prop) if self.cascade.delete_orphan: history = uowcommit.get_attribute_history( state, self.key, self._passive_delete_flag) if history: for child in history.deleted: if self.hasparent(child) is False: uowcommit.register_object( child, isdelete=True, operation="delete", prop=self.prop) t = self.mapper.cascade_iterator('delete', child) for c, m, st_, dct_ in t: uowcommit.register_object(st_, isdelete=True) def process_deletes(self, uowcommit, states): if self.post_update and \ not self.cascade.delete_orphan and \ not self.passive_deletes == 'all': # post_update means we have to update our # row to not reference the child object # before we can DELETE the row for state in states: self._synchronize(state, None, None, True, uowcommit) if state and self.post_update: history = uowcommit.get_attribute_history( state, self.key, self._passive_delete_flag) if history: self._post_update(state, uowcommit, history.sum()) def process_saves(self, uowcommit, states): for state in states: history = uowcommit.get_attribute_history( state, self.key, attributes.PASSIVE_NO_INITIALIZE) if history: if history.added: for child in history.added: self._synchronize(state, child, None, False, uowcommit, "add") if self.post_update: self._post_update(state, uowcommit, history.sum()) def _synchronize(self, state, child, associationrow, clearkeys, uowcommit, operation=None): if state is None or \ (not self.post_update and uowcommit.is_deleted(state)): return if operation is not None and \ child is not None and \ not uowcommit.session._contains_state(child): util.warn( "Object of type %s not in session, %s " "operation along '%s' won't proceed" % (mapperutil.state_class_str(child), operation, self.prop)) return if clearkeys or child is None: sync.clear(state, self.parent, self.prop.synchronize_pairs) else: self._verify_canload(child) sync.populate(child, self.mapper, state, self.parent, self.prop.synchronize_pairs, uowcommit, False) class DetectKeySwitch(DependencyProcessor): """For many-to-one relationships with no one-to-many backref, searches for parents through the unit of work when a primary key has changed and updates them. Theoretically, this approach could be expanded to support transparent deletion of objects referenced via many-to-one as well, although the current attribute system doesn't do enough bookkeeping for this to be efficient. """ def per_property_preprocessors(self, uow): if self.prop._reverse_property: if self.passive_updates: return else: if False in (prop.passive_updates for prop in self.prop._reverse_property): return uow.register_preprocessor(self, False) def per_property_flush_actions(self, uow): parent_saves = unitofwork.SaveUpdateAll( uow, self.parent.base_mapper) after_save = unitofwork.ProcessAll(uow, self, False, False) uow.dependencies.update([ (parent_saves, after_save) ]) def per_state_flush_actions(self, uow, states, isdelete): pass def presort_deletes(self, uowcommit, states): pass def presort_saves(self, uow, states): if not self.passive_updates: # for non-passive updates, register in the preprocess stage # so that mapper save_obj() gets a hold of changes self._process_key_switches(states, uow) def prop_has_changes(self, uow, states, isdelete): if not isdelete and self.passive_updates: d = self._key_switchers(uow, states) return bool(d) return False def process_deletes(self, uowcommit, states): assert False def process_saves(self, uowcommit, states): # for passive updates, register objects in the process stage # so that we avoid ManyToOneDP's registering the object without # the listonly flag in its own preprocess stage (results in UPDATE) # statements being emitted assert self.passive_updates self._process_key_switches(states, uowcommit) def _key_switchers(self, uow, states): switched, notswitched = uow.memo( ('pk_switchers', self), lambda: (set(), set()) ) allstates = switched.union(notswitched) for s in states: if s not in allstates: if self._pks_changed(uow, s): switched.add(s) else: notswitched.add(s) return switched def _process_key_switches(self, deplist, uowcommit): switchers = self._key_switchers(uowcommit, deplist) if switchers: # if primary key values have actually changed somewhere, perform # a linear search through the UOW in search of a parent. for state in uowcommit.session.identity_map.all_states(): if not issubclass(state.class_, self.parent.class_): continue dict_ = state.dict related = state.get_impl(self.key).get( state, dict_, passive=self._passive_update_flag) if related is not attributes.PASSIVE_NO_RESULT and \ related is not None: related_state = attributes.instance_state(dict_[self.key]) if related_state in switchers: uowcommit.register_object(state, False, self.passive_updates) sync.populate( related_state, self.mapper, state, self.parent, self.prop.synchronize_pairs, uowcommit, self.passive_updates) def _pks_changed(self, uowcommit, state): return bool(state.key) and sync.source_modified( uowcommit, state, self.mapper, self.prop.synchronize_pairs) class ManyToManyDP(DependencyProcessor): def per_property_dependencies(self, uow, parent_saves, child_saves, parent_deletes, child_deletes, after_save, before_delete ): uow.dependencies.update([ (parent_saves, after_save), (child_saves, after_save), (after_save, child_deletes), # a rowswitch on the parent from deleted to saved # can make this one occur, as the "save" may remove # an element from the # "deleted" list before we have a chance to # process its child rows (before_delete, parent_saves), (before_delete, parent_deletes), (before_delete, child_deletes), (before_delete, child_saves), ]) def per_state_dependencies(self, uow, save_parent, delete_parent, child_action, after_save, before_delete, isdelete, childisdelete): if not isdelete: if childisdelete: uow.dependencies.update([ (save_parent, after_save), (after_save, child_action), ]) else: uow.dependencies.update([ (save_parent, after_save), (child_action, after_save), ]) else: uow.dependencies.update([ (before_delete, child_action), (before_delete, delete_parent) ]) def presort_deletes(self, uowcommit, states): # TODO: no tests fail if this whole # thing is removed !!!! if not self.passive_deletes: # if no passive deletes, load history on # the collection, so that prop_has_changes() # returns True for state in states: uowcommit.get_attribute_history( state, self.key, self._passive_delete_flag) def presort_saves(self, uowcommit, states): if not self.passive_updates: # if no passive updates, load history on # each collection where parent has changed PK, # so that prop_has_changes() returns True for state in states: if self._pks_changed(uowcommit, state): history = uowcommit.get_attribute_history( state, self.key, attributes.PASSIVE_OFF) if not self.cascade.delete_orphan: return # check for child items removed from the collection # if delete_orphan check is turned on. for state in states: history = uowcommit.get_attribute_history( state, self.key, attributes.PASSIVE_NO_INITIALIZE) if history: for child in history.deleted: if self.hasparent(child) is False: uowcommit.register_object( child, isdelete=True, operation="delete", prop=self.prop) for c, m, st_, dct_ in self.mapper.cascade_iterator( 'delete', child): uowcommit.register_object( st_, isdelete=True) def process_deletes(self, uowcommit, states): secondary_delete = [] secondary_insert = [] secondary_update = [] processed = self._get_reversed_processed_set(uowcommit) tmp = set() for state in states: # this history should be cached already, as # we loaded it in preprocess_deletes history = uowcommit.get_attribute_history( state, self.key, self._passive_delete_flag) if history: for child in history.non_added(): if child is None or \ (processed is not None and (state, child) in processed): continue associationrow = {} if not self._synchronize( state, child, associationrow, False, uowcommit, "delete"): continue secondary_delete.append(associationrow) tmp.update((c, state) for c in history.non_added()) if processed is not None: processed.update(tmp) self._run_crud(uowcommit, secondary_insert, secondary_update, secondary_delete) def process_saves(self, uowcommit, states): secondary_delete = [] secondary_insert = [] secondary_update = [] processed = self._get_reversed_processed_set(uowcommit) tmp = set() for state in states: need_cascade_pks = not self.passive_updates and \ self._pks_changed(uowcommit, state) if need_cascade_pks: passive = attributes.PASSIVE_OFF else: passive = attributes.PASSIVE_NO_INITIALIZE history = uowcommit.get_attribute_history(state, self.key, passive) if history: for child in history.added: if (processed is not None and (state, child) in processed): continue associationrow = {} if not self._synchronize(state, child, associationrow, False, uowcommit, "add"): continue secondary_insert.append(associationrow) for child in history.deleted: if (processed is not None and (state, child) in processed): continue associationrow = {} if not self._synchronize(state, child, associationrow, False, uowcommit, "delete"): continue secondary_delete.append(associationrow) tmp.update((c, state) for c in history.added + history.deleted) if need_cascade_pks: for child in history.unchanged: associationrow = {} sync.update(state, self.parent, associationrow, "old_", self.prop.synchronize_pairs) sync.update(child, self.mapper, associationrow, "old_", self.prop.secondary_synchronize_pairs) secondary_update.append(associationrow) if processed is not None: processed.update(tmp) self._run_crud(uowcommit, secondary_insert, secondary_update, secondary_delete) def _run_crud(self, uowcommit, secondary_insert, secondary_update, secondary_delete): connection = uowcommit.transaction.connection(self.mapper) if secondary_delete: associationrow = secondary_delete[0] statement = self.secondary.delete(sql.and_(*[ c == sql.bindparam(c.key, type_=c.type) for c in self.secondary.c if c.key in associationrow ])) result = connection.execute(statement, secondary_delete) if result.supports_sane_multi_rowcount() and \ result.rowcount != len(secondary_delete): raise exc.StaleDataError( "DELETE statement on table '%s' expected to delete " "%d row(s); Only %d were matched." % (self.secondary.description, len(secondary_delete), result.rowcount) ) if secondary_update: associationrow = secondary_update[0] statement = self.secondary.update(sql.and_(*[ c == sql.bindparam("old_" + c.key, type_=c.type) for c in self.secondary.c if c.key in associationrow ])) result = connection.execute(statement, secondary_update) if result.supports_sane_multi_rowcount() and \ result.rowcount != len(secondary_update): raise exc.StaleDataError( "UPDATE statement on table '%s' expected to update " "%d row(s); Only %d were matched." % (self.secondary.description, len(secondary_update), result.rowcount) ) if secondary_insert: statement = self.secondary.insert() connection.execute(statement, secondary_insert) def _synchronize(self, state, child, associationrow, clearkeys, uowcommit, operation): # this checks for None if uselist=True self._verify_canload(child) # but if uselist=False we get here. If child is None, # no association row can be generated, so return. if child is None: return False if child is not None and not uowcommit.session._contains_state(child): if not child.deleted: util.warn( "Object of type %s not in session, %s " "operation along '%s' won't proceed" % (mapperutil.state_class_str(child), operation, self.prop)) return False sync.populate_dict(state, self.parent, associationrow, self.prop.synchronize_pairs) sync.populate_dict(child, self.mapper, associationrow, self.prop.secondary_synchronize_pairs) return True def _pks_changed(self, uowcommit, state): return sync.source_modified( uowcommit, state, self.parent, self.prop.synchronize_pairs) _direction_to_processor = { ONETOMANY: OneToManyDP, MANYTOONE: ManyToOneDP, MANYTOMANY: ManyToManyDP, }
mit
newerthcom/savagerebirth
libs/python-2.72/Lib/ctypes/test/test_prototypes.py
81
6738
from ctypes import * import unittest # IMPORTANT INFO: # # Consider this call: # func.restype = c_char_p # func(c_char_p("123")) # It returns # "123" # # WHY IS THIS SO? # # argument tuple (c_char_p("123"), ) is destroyed after the function # func is called, but NOT before the result is actually built. # # If the arglist would be destroyed BEFORE the result has been built, # the c_char_p("123") object would already have a zero refcount, # and the pointer passed to (and returned by) the function would # probably point to deallocated space. # # In this case, there would have to be an additional reference to the argument... import _ctypes_test testdll = CDLL(_ctypes_test.__file__) # Return machine address `a` as a (possibly long) non-negative integer. # Starting with Python 2.5, id(anything) is always non-negative, and # the ctypes addressof() inherits that via PyLong_FromVoidPtr(). def positive_address(a): if a >= 0: return a # View the bits in `a` as unsigned instead. import struct num_bits = struct.calcsize("P") * 8 # num bits in native machine address a += 1L << num_bits assert a >= 0 return a def c_wbuffer(init): n = len(init) + 1 return (c_wchar * n)(*init) class CharPointersTestCase(unittest.TestCase): def setUp(self): func = testdll._testfunc_p_p func.restype = c_long func.argtypes = None def test_paramflags(self): # function returns c_void_p result, # and has a required parameter named 'input' prototype = CFUNCTYPE(c_void_p, c_void_p) func = prototype(("_testfunc_p_p", testdll), ((1, "input"),)) try: func() except TypeError, details: self.assertEqual(str(details), "required argument 'input' missing") else: self.fail("TypeError not raised") self.assertEqual(func(None), None) self.assertEqual(func(input=None), None) def test_int_pointer_arg(self): func = testdll._testfunc_p_p func.restype = c_long self.assertEqual(0, func(0)) ci = c_int(0) func.argtypes = POINTER(c_int), self.assertEqual(positive_address(addressof(ci)), positive_address(func(byref(ci)))) func.argtypes = c_char_p, self.assertRaises(ArgumentError, func, byref(ci)) func.argtypes = POINTER(c_short), self.assertRaises(ArgumentError, func, byref(ci)) func.argtypes = POINTER(c_double), self.assertRaises(ArgumentError, func, byref(ci)) def test_POINTER_c_char_arg(self): func = testdll._testfunc_p_p func.restype = c_char_p func.argtypes = POINTER(c_char), self.assertEqual(None, func(None)) self.assertEqual("123", func("123")) self.assertEqual(None, func(c_char_p(None))) self.assertEqual("123", func(c_char_p("123"))) self.assertEqual("123", func(c_buffer("123"))) ca = c_char("a") self.assertEqual("a", func(pointer(ca))[0]) self.assertEqual("a", func(byref(ca))[0]) def test_c_char_p_arg(self): func = testdll._testfunc_p_p func.restype = c_char_p func.argtypes = c_char_p, self.assertEqual(None, func(None)) self.assertEqual("123", func("123")) self.assertEqual(None, func(c_char_p(None))) self.assertEqual("123", func(c_char_p("123"))) self.assertEqual("123", func(c_buffer("123"))) ca = c_char("a") self.assertEqual("a", func(pointer(ca))[0]) self.assertEqual("a", func(byref(ca))[0]) def test_c_void_p_arg(self): func = testdll._testfunc_p_p func.restype = c_char_p func.argtypes = c_void_p, self.assertEqual(None, func(None)) self.assertEqual("123", func("123")) self.assertEqual("123", func(c_char_p("123"))) self.assertEqual(None, func(c_char_p(None))) self.assertEqual("123", func(c_buffer("123"))) ca = c_char("a") self.assertEqual("a", func(pointer(ca))[0]) self.assertEqual("a", func(byref(ca))[0]) func(byref(c_int())) func(pointer(c_int())) func((c_int * 3)()) try: func.restype = c_wchar_p except NameError: pass else: self.assertEqual(None, func(c_wchar_p(None))) self.assertEqual(u"123", func(c_wchar_p(u"123"))) def test_instance(self): func = testdll._testfunc_p_p func.restype = c_void_p class X: _as_parameter_ = None func.argtypes = c_void_p, self.assertEqual(None, func(X())) func.argtypes = None self.assertEqual(None, func(X())) try: c_wchar except NameError: pass else: class WCharPointersTestCase(unittest.TestCase): def setUp(self): func = testdll._testfunc_p_p func.restype = c_int func.argtypes = None def test_POINTER_c_wchar_arg(self): func = testdll._testfunc_p_p func.restype = c_wchar_p func.argtypes = POINTER(c_wchar), self.assertEqual(None, func(None)) self.assertEqual(u"123", func(u"123")) self.assertEqual(None, func(c_wchar_p(None))) self.assertEqual(u"123", func(c_wchar_p(u"123"))) self.assertEqual(u"123", func(c_wbuffer(u"123"))) ca = c_wchar("a") self.assertEqual(u"a", func(pointer(ca))[0]) self.assertEqual(u"a", func(byref(ca))[0]) def test_c_wchar_p_arg(self): func = testdll._testfunc_p_p func.restype = c_wchar_p func.argtypes = c_wchar_p, c_wchar_p.from_param(u"123") self.assertEqual(None, func(None)) self.assertEqual("123", func(u"123")) self.assertEqual(None, func(c_wchar_p(None))) self.assertEqual("123", func(c_wchar_p("123"))) # XXX Currently, these raise TypeErrors, although they shouldn't: self.assertEqual("123", func(c_wbuffer("123"))) ca = c_wchar("a") self.assertEqual("a", func(pointer(ca))[0]) self.assertEqual("a", func(byref(ca))[0]) class ArrayTest(unittest.TestCase): def test(self): func = testdll._testfunc_ai8 func.restype = POINTER(c_int) func.argtypes = c_int * 8, func((c_int * 8)(1, 2, 3, 4, 5, 6, 7, 8)) # This did crash before: def func(): pass CFUNCTYPE(None, c_int * 3)(func) ################################################################ if __name__ == '__main__': unittest.main()
gpl-2.0
gangadharkadam/shfr
frappe/modules/export_file.py
39
2353
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe, os, json import frappe.model from frappe.modules import scrub, get_module_path, lower_case_files_for, scrub_dt_dn def export_doc(doc): export_to_files([[doc.doctype, doc.name]]) def export_to_files(record_list=None, record_module=None, verbose=0, create_init=None): """ Export record_list to files. record_list is a list of lists ([doctype],[docname] ) , """ if frappe.flags.in_import: return if record_list: for record in record_list: write_document_file(frappe.get_doc(record[0], record[1]), record_module, create_init=create_init) def write_document_file(doc, record_module=None, create_init=None): newdoc = doc.as_dict(no_nulls=True) # strip out default fields from children for df in doc.meta.get_table_fields(): for d in newdoc.get(df.fieldname): for fieldname in frappe.model.default_fields: if fieldname in d: del d[fieldname] module = record_module or get_module_name(doc) if create_init is None: create_init = doc.doctype in lower_case_files_for # create folder folder = create_folder(module, doc.doctype, doc.name, create_init) # write the data file fname = (doc.doctype in lower_case_files_for and scrub(doc.name)) or doc.name with open(os.path.join(folder, fname +".json"),'w+') as txtfile: txtfile.write(json.dumps(newdoc, indent=1, sort_keys=True)) def get_module_name(doc): if doc.doctype == 'Module Def': module = doc.name elif doc.doctype=="Workflow": module = frappe.db.get_value("DocType", doc.document_type, "module") else: module = doc.module return module def create_folder(module, dt, dn, create_init): module_path = get_module_path(module) dt, dn = scrub_dt_dn(dt, dn) # create folder folder = os.path.join(module_path, dt, dn) frappe.create_folder(folder) # create init_py_files if create_init: create_init_py(module_path, dt, dn) return folder def create_init_py(module_path, dt, dn): def create_if_not_exists(path): initpy = os.path.join(path, '__init__.py') if not os.path.exists(initpy): open(initpy, 'w').close() create_if_not_exists(os.path.join(module_path)) create_if_not_exists(os.path.join(module_path, dt)) create_if_not_exists(os.path.join(module_path, dt, dn))
mit
levilucio/SyVOLT
t_core/Mutex/HKillRuleLHS.py
1
8932
from core.himesis import Himesis, HimesisPreConditionPatternLHS import cPickle as pickle class HKillRuleLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HKillRuleLHS. """ # Create the himesis graph EDGE_LIST = [(2, 0), (0, 3), (3, 1), (1, 4)] super(HKillRuleLHS, self).__init__(name='HKillRuleLHS', num_nodes=5, edges=EDGE_LIST) self.is_compiled = True # now this instance has been compiled # Set the graph attributes self["MT_constraint__"] = pickle.loads("""S"#===============================================================================@n# This code is executed after the nodes in the LHS have been matched.@n# You can access a matched node labelled n by: PreNode('n').@n# To access attribute x of node n, use: PreNode('n')['x'].@n# The given constraint must evaluate to a boolean expression:@n# returning True enables the rule to be applied,@n# returning False forbids the rule from being applied.@n#===============================================================================@n@nreturn True@n" p1 .""").replace("@n", "\n") self["name"] = pickle.loads("""S'HKillRuleLHS' p1 .""") self["GUID__"] = pickle.loads("""ccopy_reg _reconstructor p1 (cuuid UUID p2 c__builtin__ object p3 NtRp4 (dp5 S'int' p6 L18442321865415244356622957945051150877L sb.""") # Set the node attributes self.vs[0]["MT_subtypeMatching__"] = pickle.loads("""I00 .""") self.vs[0]["MT_label__"] = pickle.loads("""S'4' .""") self.vs[0]["MT_subtypes__"] = pickle.loads("""(lp1 .""") self.vs[0]["mm__"] = pickle.loads("""S'MT_pre__next' p1 .""") self.vs[0]["MT_dirty__"] = pickle.loads("""I00 .""") self.vs[0]["GUID__"] = pickle.loads("""ccopy_reg _reconstructor p1 (cuuid UUID p2 c__builtin__ object p3 NtRp4 (dp5 S'int' p6 L30273376065343805843958472981264470130L sb.""") self.vs[1]["MT_subtypeMatching__"] = pickle.loads("""I00 .""") self.vs[1]["MT_label__"] = pickle.loads("""S'5' .""") self.vs[1]["MT_subtypes__"] = pickle.loads("""(lp1 .""") self.vs[1]["mm__"] = pickle.loads("""S'MT_pre__next' p1 .""") self.vs[1]["MT_dirty__"] = pickle.loads("""I00 .""") self.vs[1]["GUID__"] = pickle.loads("""ccopy_reg _reconstructor p1 (cuuid UUID p2 c__builtin__ object p3 NtRp4 (dp5 S'int' p6 L328554853358455331346205911493797456672L sb.""") self.vs[2]["MT_subtypeMatching__"] = pickle.loads("""I00 .""") self.vs[2]["MT_label__"] = pickle.loads("""S'1' .""") self.vs[2]["MT_subtypes__"] = pickle.loads("""(lp1 .""") self.vs[2]["mm__"] = pickle.loads("""S'MT_pre__Process' p1 .""") self.vs[2]["MT_dirty__"] = pickle.loads("""I00 .""") self.vs[2]["MT_pre__name"] = pickle.loads("""S"@n#===============================================================================@n# This code is executed when evaluating if a node shall be matched by this rule.@n# You can access the value of the current node's attribute value by: attr_value.@n# You can access a matched node 'n' by: PreNode('n').@n# To access attribute x of node n, use: PreNode('n')['x'].@n# The given constraint must evaluate to a boolean expression.@n#===============================================================================@n@nreturn True@n" p1 .""").replace("@n", "\n") self.vs[2]["GUID__"] = pickle.loads("""ccopy_reg _reconstructor p1 (cuuid UUID p2 c__builtin__ object p3 NtRp4 (dp5 S'int' p6 L165009034650108222987415177235648016564L sb.""") self.vs[3]["MT_subtypeMatching__"] = pickle.loads("""I00 .""") self.vs[3]["MT_label__"] = pickle.loads("""S'2' .""") self.vs[3]["MT_subtypes__"] = pickle.loads("""(lp1 .""") self.vs[3]["mm__"] = pickle.loads("""S'MT_pre__Process' p1 .""") self.vs[3]["MT_dirty__"] = pickle.loads("""I00 .""") self.vs[3]["MT_pre__name"] = pickle.loads("""S"@n#===============================================================================@n# This code is executed when evaluating if a node shall be matched by this rule.@n# You can access the value of the current node's attribute value by: attr_value.@n# You can access a matched node 'n' by: PreNode('n').@n# To access attribute x of node n, use: PreNode('n')['x'].@n# The given constraint must evaluate to a boolean expression.@n#===============================================================================@n@nreturn True@n" p1 .""").replace("@n", "\n") self.vs[3]["GUID__"] = pickle.loads("""ccopy_reg _reconstructor p1 (cuuid UUID p2 c__builtin__ object p3 NtRp4 (dp5 S'int' p6 L73980624501117965779453092797674415786L sb.""") self.vs[4]["MT_subtypeMatching__"] = pickle.loads("""I00 .""") self.vs[4]["MT_label__"] = pickle.loads("""S'3' .""") self.vs[4]["MT_subtypes__"] = pickle.loads("""(lp1 .""") self.vs[4]["mm__"] = pickle.loads("""S'MT_pre__Process' p1 .""") self.vs[4]["MT_dirty__"] = pickle.loads("""I00 .""") self.vs[4]["MT_pre__name"] = pickle.loads("""S"@n#===============================================================================@n# This code is executed when evaluating if a node shall be matched by this rule.@n# You can access the value of the current node's attribute value by: attr_value.@n# You can access a matched node 'n' by: PreNode('n').@n# To access attribute x of node n, use: PreNode('n')['x'].@n# The given constraint must evaluate to a boolean expression.@n#===============================================================================@n@nreturn True@n" p1 .""").replace("@n", "\n") self.vs[4]["GUID__"] = pickle.loads("""ccopy_reg _reconstructor p1 (cuuid UUID p2 c__builtin__ object p3 NtRp4 (dp5 S'int' p6 L292064108001480532935557560315945411793L sb.""") def eval_name1(self, attr_value, PreNode, graph): #=============================================================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access a matched node 'n' by: PreNode('n'). # To access attribute x of node n, use: PreNode('n')['x']. # The given constraint must evaluate to a boolean expression. #=============================================================================== return True def eval_name2(self, attr_value, PreNode, graph): #=============================================================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access a matched node 'n' by: PreNode('n'). # To access attribute x of node n, use: PreNode('n')['x']. # The given constraint must evaluate to a boolean expression. #=============================================================================== return True def eval_name3(self, attr_value, PreNode, graph): #=============================================================================== # This code is executed when evaluating if a node shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access a matched node 'n' by: PreNode('n'). # To access attribute x of node n, use: PreNode('n')['x']. # The given constraint must evaluate to a boolean expression. #=============================================================================== return True def constraint(self, PreNode, graph): """ Executable constraint code. @param PreNode: Function taking an integer as parameter and returns the node corresponding to that label. """ #=============================================================================== # This code is executed after the nodes in the LHS have been matched. # You can access a matched node labelled n by: PreNode('n'). # To access attribute x of node n, use: PreNode('n')['x']. # The given constraint must evaluate to a boolean expression: # returning True enables the rule to be applied, # returning False forbids the rule from being applied. #=============================================================================== return True
mit
nabsboss/CouchPotatoServer
libs/sqlalchemy/sql/operators.py
12
15388
# sql/operators.py # Copyright (C) 2005-2012 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 # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Defines operators used in SQL expressions.""" from operator import ( and_, or_, inv, add, mul, sub, mod, truediv, lt, le, ne, gt, ge, eq, neg ) # Py2K from operator import (div,) # end Py2K from sqlalchemy.util import symbol class Operators(object): """Base of comparison and logical operators. Implements base methods :meth:`operate` and :meth:`reverse_operate`, as well as :meth:`__and__`, :meth:`__or__`, :meth:`__invert__`. Usually is used via its most common subclass :class:`.ColumnOperators`. """ def __and__(self, other): """Implement the ``&`` operator. When used with SQL expressions, results in an AND operation, equivalent to :func:`~.expression.and_`, that is:: a & b is equivalent to:: from sqlalchemy import and_ and_(a, b) Care should be taken when using ``&`` regarding operator precedence; the ``&`` operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:: (a == 2) & (b == 4) """ return self.operate(and_, other) def __or__(self, other): """Implement the ``|`` operator. When used with SQL expressions, results in an OR operation, equivalent to :func:`~.expression.or_`, that is:: a | b is equivalent to:: from sqlalchemy import or_ or_(a, b) Care should be taken when using ``|`` regarding operator precedence; the ``|`` operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:: (a == 2) | (b == 4) """ return self.operate(or_, other) def __invert__(self): """Implement the ``~`` operator. When used with SQL expressions, results in a NOT operation, equivalent to :func:`~.expression.not_`, that is:: ~a is equivalent to:: from sqlalchemy import not_ not_(a) """ return self.operate(inv) def op(self, opstring): """produce a generic operator function. e.g.:: somecolumn.op("*")(5) produces:: somecolumn * 5 :param operator: a string which will be output as the infix operator between this :class:`.ClauseElement` and the expression passed to the generated function. This function can also be used to make bitwise operators explicit. For example:: somecolumn.op('&')(0xff) is a bitwise AND of the value in somecolumn. """ def _op(b): return self.operate(op, opstring, b) return _op def operate(self, op, *other, **kwargs): """Operate on an argument. This is the lowest level of operation, raises :class:`NotImplementedError` by default. Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding :class:`.ColumnOperators` to apply ``func.lower()`` to the left and right side:: class MyComparator(ColumnOperators): def operate(self, op, other): return op(func.lower(self), func.lower(other)) :param op: Operator callable. :param \*other: the 'other' side of the operation. Will be a single scalar for most operations. :param \**kwargs: modifiers. These may be passed by special operators such as :meth:`ColumnOperators.contains`. """ raise NotImplementedError(str(op)) def reverse_operate(self, op, other, **kwargs): """Reverse operate on an argument. Usage is the same as :meth:`operate`. """ raise NotImplementedError(str(op)) class ColumnOperators(Operators): """Defines comparison and math operations. By default all methods call down to :meth:`Operators.operate` or :meth:`Operators.reverse_operate` passing in the appropriate operator function from the Python builtin ``operator`` module or a SQLAlchemy-specific operator function from :mod:`sqlalchemy.expression.operators`. For example the ``__eq__`` function:: def __eq__(self, other): return self.operate(operators.eq, other) Where ``operators.eq`` is essentially:: def eq(a, b): return a == b A SQLAlchemy construct like :class:`.ColumnElement` ultimately overrides :meth:`.Operators.operate` and others to return further :class:`.ClauseElement` constructs, so that the ``==`` operation above is replaced by a clause construct. The docstrings here will describe column-oriented behavior of each operator. For ORM-based operators on related objects and collections, see :class:`.RelationshipProperty.Comparator`. """ timetuple = None """Hack, allows datetime objects to be compared on the LHS.""" def __lt__(self, other): """Implement the ``<`` operator. In a column context, produces the clause ``a < b``. """ return self.operate(lt, other) def __le__(self, other): """Implement the ``<=`` operator. In a column context, produces the clause ``a <= b``. """ return self.operate(le, other) __hash__ = Operators.__hash__ def __eq__(self, other): """Implement the ``==`` operator. In a column context, produces the clause ``a = b``. If the target is ``None``, produces ``a IS NULL``. """ return self.operate(eq, other) def __ne__(self, other): """Implement the ``!=`` operator. In a column context, produces the clause ``a != b``. If the target is ``None``, produces ``a IS NOT NULL``. """ return self.operate(ne, other) def __gt__(self, other): """Implement the ``>`` operator. In a column context, produces the clause ``a > b``. """ return self.operate(gt, other) def __ge__(self, other): """Implement the ``>=`` operator. In a column context, produces the clause ``a >= b``. """ return self.operate(ge, other) def __neg__(self): """Implement the ``-`` operator. In a column context, produces the clause ``-a``. """ return self.operate(neg) def concat(self, other): """Implement the 'concat' operator. In a column context, produces the clause ``a || b``, or uses the ``concat()`` operator on MySQL. """ return self.operate(concat_op, other) def like(self, other, escape=None): """Implement the ``like`` operator. In a column context, produces the clause ``a LIKE other``. """ return self.operate(like_op, other, escape=escape) def ilike(self, other, escape=None): """Implement the ``ilike`` operator. In a column context, produces the clause ``a ILIKE other``. """ return self.operate(ilike_op, other, escape=escape) def in_(self, other): """Implement the ``in`` operator. In a column context, produces the clause ``a IN other``. "other" may be a tuple/list of column expressions, or a :func:`~.expression.select` construct. """ return self.operate(in_op, other) def startswith(self, other, **kwargs): """Implement the ``startwith`` operator. In a column context, produces the clause ``LIKE '<other>%'`` """ return self.operate(startswith_op, other, **kwargs) def endswith(self, other, **kwargs): """Implement the 'endswith' operator. In a column context, produces the clause ``LIKE '%<other>'`` """ return self.operate(endswith_op, other, **kwargs) def contains(self, other, **kwargs): """Implement the 'contains' operator. In a column context, produces the clause ``LIKE '%<other>%'`` """ return self.operate(contains_op, other, **kwargs) def match(self, other, **kwargs): """Implements the 'match' operator. In a column context, this produces a MATCH clause, i.e. ``MATCH '<other>'``. The allowed contents of ``other`` are database backend specific. """ return self.operate(match_op, other, **kwargs) def desc(self): """Produce a :func:`~.expression.desc` clause against the parent object.""" return self.operate(desc_op) def asc(self): """Produce a :func:`~.expression.asc` clause against the parent object.""" return self.operate(asc_op) def nullsfirst(self): """Produce a :func:`~.expression.nullsfirst` clause against the parent object.""" return self.operate(nullsfirst_op) def nullslast(self): """Produce a :func:`~.expression.nullslast` clause against the parent object.""" return self.operate(nullslast_op) def collate(self, collation): """Produce a :func:`~.expression.collate` clause against the parent object, given the collation string.""" return self.operate(collate, collation) def __radd__(self, other): """Implement the ``+`` operator in reverse. See :meth:`__add__`. """ return self.reverse_operate(add, other) def __rsub__(self, other): """Implement the ``-`` operator in reverse. See :meth:`__sub__`. """ return self.reverse_operate(sub, other) def __rmul__(self, other): """Implement the ``*`` operator in reverse. See :meth:`__mul__`. """ return self.reverse_operate(mul, other) def __rdiv__(self, other): """Implement the ``/`` operator in reverse. See :meth:`__div__`. """ return self.reverse_operate(div, other) def between(self, cleft, cright): """Produce a :func:`~.expression.between` clause against the parent object, given the lower and upper range.""" return self.operate(between_op, cleft, cright) def distinct(self): """Produce a :func:`~.expression.distinct` clause against the parent object.""" return self.operate(distinct_op) def __add__(self, other): """Implement the ``+`` operator. In a column context, produces the clause ``a + b`` if the parent object has non-string affinity. If the parent object has a string affinity, produces the concatenation operator, ``a || b`` - see :meth:`concat`. """ return self.operate(add, other) def __sub__(self, other): """Implement the ``-`` operator. In a column context, produces the clause ``a - b``. """ return self.operate(sub, other) def __mul__(self, other): """Implement the ``*`` operator. In a column context, produces the clause ``a * b``. """ return self.operate(mul, other) def __div__(self, other): """Implement the ``/`` operator. In a column context, produces the clause ``a / b``. """ return self.operate(div, other) def __mod__(self, other): """Implement the ``%`` operator. In a column context, produces the clause ``a % b``. """ return self.operate(mod, other) def __truediv__(self, other): """Implement the ``//`` operator. In a column context, produces the clause ``a / b``. """ return self.operate(truediv, other) def __rtruediv__(self, other): """Implement the ``//`` operator in reverse. See :meth:`__truediv__`. """ return self.reverse_operate(truediv, other) def from_(): raise NotImplementedError() def as_(): raise NotImplementedError() def exists(): raise NotImplementedError() def is_(a, b): return a.is_(b) def isnot(a, b): return a.isnot(b) def collate(a, b): return a.collate(b) def op(a, opstring, b): return a.op(opstring)(b) def like_op(a, b, escape=None): return a.like(b, escape=escape) def notlike_op(a, b, escape=None): raise NotImplementedError() def ilike_op(a, b, escape=None): return a.ilike(b, escape=escape) def notilike_op(a, b, escape=None): raise NotImplementedError() def between_op(a, b, c): return a.between(b, c) def in_op(a, b): return a.in_(b) def notin_op(a, b): raise NotImplementedError() def distinct_op(a): return a.distinct() def startswith_op(a, b, escape=None): return a.startswith(b, escape=escape) def endswith_op(a, b, escape=None): return a.endswith(b, escape=escape) def contains_op(a, b, escape=None): return a.contains(b, escape=escape) def match_op(a, b): return a.match(b) def comma_op(a, b): raise NotImplementedError() def concat_op(a, b): return a.concat(b) def desc_op(a): return a.desc() def asc_op(a): return a.asc() def nullsfirst_op(a): return a.nullsfirst() def nullslast_op(a): return a.nullslast() _commutative = set([eq, ne, add, mul]) def is_commutative(op): return op in _commutative def is_ordering_modifier(op): return op in (asc_op, desc_op, nullsfirst_op, nullslast_op) _associative = _commutative.union([concat_op, and_, or_]) _smallest = symbol('_smallest') _largest = symbol('_largest') _PRECEDENCE = { from_: 15, mul: 7, truediv: 7, # Py2K div: 7, # end Py2K mod: 7, neg: 7, add: 6, sub: 6, concat_op: 6, match_op: 6, ilike_op: 5, notilike_op: 5, like_op: 5, notlike_op: 5, in_op: 5, notin_op: 5, is_: 5, isnot: 5, eq: 5, ne: 5, gt: 5, lt: 5, ge: 5, le: 5, between_op: 5, distinct_op: 5, inv: 5, and_: 3, or_: 2, comma_op: -1, collate: 7, as_: -1, exists: 0, _smallest: -1000, _largest: 1000 } def is_precedent(operator, against): if operator is against and operator in _associative: return False else: return (_PRECEDENCE.get(operator, _PRECEDENCE[_smallest]) <= _PRECEDENCE.get(against, _PRECEDENCE[_largest]))
gpl-3.0
bdmod/extreme-subversion
BinarySourcce/subversion-1.6.17/build/getversion.py
1
2153
#!/usr/bin/env python # # getversion.py - Parse version numbers from C header files. # import os import re import sys __all__ = ['Parser', 'Result'] class Result: pass class Parser: def __init__(self): self.patterns = {} def search(self, define_name, value_name): 'Add the name of a define to the list of search pattenrs.' self.patterns[define_name] = value_name def parse(self, file): 'Parse the file, extracting defines into a Result object.' stream = open(file, 'rt') result = Result() regex = re.compile(r'^\s*#\s*define\s+(\w+)\s+(\d+)') for line in stream.readlines(): match = regex.match(line) if match: try: name = self.patterns[match.group(1)] except: continue setattr(result, name, int(match.group(2))) stream.close() return result def svn_extractor(parser, include_file): '''Pull values from svn.version.h''' p.search('SVN_VER_MAJOR', 'major') p.search('SVN_VER_MINOR', 'minor') p.search('SVN_VER_PATCH', 'patch') try: r = p.parse(include_file) except IOError, e: usage_and_exit(str(e)) sys.stdout.write("%d.%d.%d" % (r.major, r.minor, r.patch)) def sqlite_extractor(parser, include_file): '''Pull values from sqlite3.h''' p.search('SQLITE_VERSION_NUMBER', 'version') try: r = p.parse(include_file) except IOError, e: usage_and_exit(str(e)) major = r.version / 1000000 minor = (r.version - (major * 1000000)) / 1000 micro = (r.version - (major * 1000000) - (minor * 1000)) sys.stdout.write("%d.%d.%d" % (major, minor, micro)) extractors = { 'SVN' : svn_extractor, 'SQLITE' : sqlite_extractor, } def usage_and_exit(msg): if msg: sys.stderr.write("%s\n\n" % msg) sys.stderr.write("usage: %s [SVN|SQLITE] [header_file]\n" % \ os.path.basename(sys.argv[0])) sys.stderr.flush() sys.exit(1) if __name__ == '__main__': if len(sys.argv) == 3: extractor = extractors[sys.argv[1]] include_file = sys.argv[2] else: usage_and_exit("Incorrect number of arguments") # Extract and print the version number p = Parser() extractor(p, include_file)
gpl-2.0
amyvmiwei/kbengine
kbe/src/lib/python/Lib/socket.py
74
18927
# Wrapper module for _socket, providing some additional facilities # implemented in Python. """\ This module provides socket operations and some related functions. On Unix, it supports IP (Internet Protocol) and Unix domain sockets. On other systems, it only supports IP. Functions specific for a socket are available as methods of the socket object. Functions: socket() -- create a new socket object socketpair() -- create a pair of new socket objects [*] fromfd() -- create a socket object from an open file descriptor [*] fromshare() -- create a socket object from data received from socket.share() [*] gethostname() -- return the current hostname gethostbyname() -- map a hostname to its IP number gethostbyaddr() -- map an IP number or hostname to DNS info getservbyname() -- map a service name and a protocol name to a port number getprotobyname() -- map a protocol name (e.g. 'tcp') to a number ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order htons(), htonl() -- convert 16, 32 bit int from host to network byte order inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) socket.getdefaulttimeout() -- get the default timeout value socket.setdefaulttimeout() -- set the default timeout value create_connection() -- connects to an address, with an optional timeout and optional source address. [*] not available on all platforms! Special objects: SocketType -- type object for socket objects error -- exception raised for I/O errors has_ipv6 -- boolean value indicating if IPv6 is supported Integer constants: AF_INET, AF_UNIX -- socket domains (first argument to socket() call) SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) Many other constants may be defined; these may be used in calls to the setsockopt() and getsockopt() methods. """ import _socket from _socket import * import os, sys, io from enum import IntEnum try: import errno except ImportError: errno = None EBADF = getattr(errno, 'EBADF', 9) EAGAIN = getattr(errno, 'EAGAIN', 11) EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11) __all__ = ["getfqdn", "create_connection"] __all__.extend(os._get_exports_list(_socket)) # Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for # nicer string representations. # Note that _socket only knows about the integer values. The public interface # in this module understands the enums and translates them back from integers # where needed (e.g. .family property of a socket object). AddressFamily = IntEnum('AddressFamily', {name: value for name, value in globals().items() if name.isupper() and name.startswith('AF_')}) globals().update(AddressFamily.__members__) SocketType = IntEnum('SocketType', {name: value for name, value in globals().items() if name.isupper() and name.startswith('SOCK_')}) globals().update(SocketType.__members__) def _intenum_converter(value, enum_klass): """Convert a numeric family value to an IntEnum member. If it's not a known member, return the numeric value itself. """ try: return enum_klass(value) except ValueError: return value _realsocket = socket # WSA error codes if sys.platform.lower().startswith("win"): errorTab = {} errorTab[10004] = "The operation was interrupted." errorTab[10009] = "A bad file handle was passed." errorTab[10013] = "Permission denied." errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT errorTab[10022] = "An invalid operation was attempted." errorTab[10035] = "The socket operation would block" errorTab[10036] = "A blocking operation is already in progress." errorTab[10048] = "The network address is in use." errorTab[10054] = "The connection has been reset." errorTab[10058] = "The network has been shut down." errorTab[10060] = "The operation timed out." errorTab[10061] = "Connection refused." errorTab[10063] = "The name is too long." errorTab[10064] = "The host is down." errorTab[10065] = "The host is unreachable." __all__.append("errorTab") class socket(_socket.socket): """A subclass of _socket.socket adding the makefile() method.""" __slots__ = ["__weakref__", "_io_refs", "_closed"] def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): # For user code address family and type values are IntEnum members, but # for the underlying _socket.socket they're just integers. The # constructor of _socket.socket converts the given argument to an # integer automatically. _socket.socket.__init__(self, family, type, proto, fileno) self._io_refs = 0 self._closed = False def __enter__(self): return self def __exit__(self, *args): if not self._closed: self.close() def __repr__(self): """Wrap __repr__() to reveal the real class name and socket address(es). """ closed = getattr(self, '_closed', False) s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \ % (self.__class__.__module__, self.__class__.__name__, " [closed]" if closed else "", self.fileno(), self.family, self.type, self.proto) if not closed: try: laddr = self.getsockname() if laddr: s += ", laddr=%s" % str(laddr) except error: pass try: raddr = self.getpeername() if raddr: s += ", raddr=%s" % str(raddr) except error: pass s += '>' return s def __getstate__(self): raise TypeError("Cannot serialize socket object") def dup(self): """dup() -> socket object Duplicate the socket. Return a new socket object connected to the same system resource. The new socket is non-inheritable. """ fd = dup(self.fileno()) sock = self.__class__(self.family, self.type, self.proto, fileno=fd) sock.settimeout(self.gettimeout()) return sock def accept(self): """accept() -> (socket object, address info) Wait for an incoming connection. Return a new socket representing the connection, and the address of the client. For IP sockets, the address info is a pair (hostaddr, port). """ fd, addr = self._accept() sock = socket(self.family, self.type, self.proto, fileno=fd) # Issue #7995: if no default timeout is set and the listening # socket had a (non-zero) timeout, force the new socket in blocking # mode to override platform-specific socket flags inheritance. if getdefaulttimeout() is None and self.gettimeout(): sock.setblocking(True) return sock, addr def makefile(self, mode="r", buffering=None, *, encoding=None, errors=None, newline=None): """makefile(...) -> an I/O stream connected to the socket The arguments are as for io.open() after the filename, except the only mode characters supported are 'r', 'w' and 'b'. The semantics are similar too. (XXX refactor to share code?) """ for c in mode: if c not in {"r", "w", "b"}: raise ValueError("invalid mode %r (only r, w, b allowed)") writing = "w" in mode reading = "r" in mode or not writing assert reading or writing binary = "b" in mode rawmode = "" if reading: rawmode += "r" if writing: rawmode += "w" raw = SocketIO(self, rawmode) self._io_refs += 1 if buffering is None: buffering = -1 if buffering < 0: buffering = io.DEFAULT_BUFFER_SIZE if buffering == 0: if not binary: raise ValueError("unbuffered streams must be binary") return raw if reading and writing: buffer = io.BufferedRWPair(raw, raw, buffering) elif reading: buffer = io.BufferedReader(raw, buffering) else: assert writing buffer = io.BufferedWriter(raw, buffering) if binary: return buffer text = io.TextIOWrapper(buffer, encoding, errors, newline) text.mode = mode return text def _decref_socketios(self): if self._io_refs > 0: self._io_refs -= 1 if self._closed: self.close() def _real_close(self, _ss=_socket.socket): # This function should not reference any globals. See issue #808164. _ss.close(self) def close(self): # This function should not reference any globals. See issue #808164. self._closed = True if self._io_refs <= 0: self._real_close() def detach(self): """detach() -> file descriptor Close the socket object without closing the underlying file descriptor. The object cannot be used after this call, but the file descriptor can be reused for other purposes. The file descriptor is returned. """ self._closed = True return super().detach() @property def family(self): """Read-only access to the address family for this socket. """ return _intenum_converter(super().family, AddressFamily) @property def type(self): """Read-only access to the socket type. """ return _intenum_converter(super().type, SocketType) if os.name == 'nt': def get_inheritable(self): return os.get_handle_inheritable(self.fileno()) def set_inheritable(self, inheritable): os.set_handle_inheritable(self.fileno(), inheritable) else: def get_inheritable(self): return os.get_inheritable(self.fileno()) def set_inheritable(self, inheritable): os.set_inheritable(self.fileno(), inheritable) get_inheritable.__doc__ = "Get the inheritable flag of the socket" set_inheritable.__doc__ = "Set the inheritable flag of the socket" def fromfd(fd, family, type, proto=0): """ fromfd(fd, family, type[, proto]) -> socket object Create a socket object from a duplicate of the given file descriptor. The remaining arguments are the same as for socket(). """ nfd = dup(fd) return socket(family, type, proto, nfd) if hasattr(_socket.socket, "share"): def fromshare(info): """ fromshare(info) -> socket object Create a socket object from a the bytes object returned by socket.share(pid). """ return socket(0, 0, 0, info) if hasattr(_socket, "socketpair"): def socketpair(family=None, type=SOCK_STREAM, proto=0): """socketpair([family[, type[, proto]]]) -> (socket object, socket object) Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET. """ if family is None: try: family = AF_UNIX except NameError: family = AF_INET a, b = _socket.socketpair(family, type, proto) a = socket(family, type, proto, a.detach()) b = socket(family, type, proto, b.detach()) return a, b _blocking_errnos = { EAGAIN, EWOULDBLOCK } class SocketIO(io.RawIOBase): """Raw I/O implementation for stream sockets. This class supports the makefile() method on sockets. It provides the raw I/O interface on top of a socket object. """ # One might wonder why not let FileIO do the job instead. There are two # main reasons why FileIO is not adapted: # - it wouldn't work under Windows (where you can't used read() and # write() on a socket handle) # - it wouldn't work with socket timeouts (FileIO would ignore the # timeout and consider the socket non-blocking) # XXX More docs def __init__(self, sock, mode): if mode not in ("r", "w", "rw", "rb", "wb", "rwb"): raise ValueError("invalid mode: %r" % mode) io.RawIOBase.__init__(self) self._sock = sock if "b" not in mode: mode += "b" self._mode = mode self._reading = "r" in mode self._writing = "w" in mode self._timeout_occurred = False def readinto(self, b): """Read up to len(b) bytes into the writable buffer *b* and return the number of bytes read. If the socket is non-blocking and no bytes are available, None is returned. If *b* is non-empty, a 0 return value indicates that the connection was shutdown at the other end. """ self._checkClosed() self._checkReadable() if self._timeout_occurred: raise OSError("cannot read from timed out object") while True: try: return self._sock.recv_into(b) except timeout: self._timeout_occurred = True raise except InterruptedError: continue except error as e: if e.args[0] in _blocking_errnos: return None raise def write(self, b): """Write the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned. """ self._checkClosed() self._checkWritable() try: return self._sock.send(b) except error as e: # XXX what about EINTR? if e.args[0] in _blocking_errnos: return None raise def readable(self): """True if the SocketIO is open for reading. """ if self.closed: raise ValueError("I/O operation on closed socket.") return self._reading def writable(self): """True if the SocketIO is open for writing. """ if self.closed: raise ValueError("I/O operation on closed socket.") return self._writing def seekable(self): """True if the SocketIO is open for seeking. """ if self.closed: raise ValueError("I/O operation on closed socket.") return super().seekable() def fileno(self): """Return the file descriptor of the underlying socket. """ self._checkClosed() return self._sock.fileno() @property def name(self): if not self.closed: return self.fileno() else: return -1 @property def mode(self): return self._mode def close(self): """Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. """ if self.closed: return io.RawIOBase.close(self) self._sock._decref_socketios() self._sock = None def getfqdn(name=''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned. """ name = name.strip() if not name or name == '0.0.0.0': name = gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name _GLOBAL_DEFAULT_TIMEOUT = object() def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address err = None for res in getaddrinfo(host, port, 0, SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket(af, socktype, proto) if timeout is not _GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except error as _: err = _ if sock is not None: sock.close() if err is not None: raise err else: raise error("getaddrinfo returns an empty list") def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): """Resolve host and port into list of address info entries. Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. host is a domain name, a string representation of an IPv4/v6 address or None. port is a string service name such as 'http', a numeric port number or None. By passing None as the value of host and port, you can pass NULL to the underlying C API. The family, type and proto arguments can be optionally specified in order to narrow the list of addresses returned. Passing zero as a value for each of these arguments selects the full range of results. """ # We override this function since we want to translate the numeric family # and socket type values to enum constants. addrlist = [] for res in _socket.getaddrinfo(host, port, family, type, proto, flags): af, socktype, proto, canonname, sa = res addrlist.append((_intenum_converter(af, AddressFamily), _intenum_converter(socktype, SocketType), proto, canonname, sa)) return addrlist
lgpl-3.0
chanceraine/nupic
tests/integration/nupic/opf/opf_experiment_results_test.py
12
15515
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ ## @file This file tests specific experiments to see if they are providing the correct results. These are high level tests of the algorithms themselves. """ import os import shutil from subprocess import call import time import unittest2 as unittest from pkg_resources import resource_filename from nupic.data.file_record_stream import FileRecordStream class OPFExperimentResultsTest(unittest.TestCase): def testExperimentResults(self): """Run specific experiments and verify that they are producing the correct results. opfDir is the examples/opf directory in the install path and is used to find run_opf_experiment.py The testdir is the directory that contains the experiments we will be running. When running in the auto-build setup, this will be a temporary directory that has had this script, as well as the specific experiments we will be running, copied into it by the qa/autotest/prediction_results.py script. When running stand-alone from the command line, this will point to the examples/prediction directory in the install tree (same as predictionDir) """ opfDir = resource_filename("nupic", os.path.join("..", "examples", "opf")) testDir = opfDir # The testdir is the directory that contains the experiments we will be # running. When running in the auto-build setup, this will be a temporary # directory that has had this script, as well as the specific experiments # we will be running, copied into it by the # qa/autotest/prediction_results.py script. # When running stand-alone from the command line, we can simply point to the # examples/prediction directory in the install tree. if not os.path.exists(os.path.join(testDir, "experiments/classification")): testDir = opfDir # Generate any dynamically generated datasets now command = ['python', os.path.join(testDir, 'experiments', 'classification', 'makeDatasets.py')] retval = call(command) self.assertEqual(retval, 0) # Generate any dynamically generated datasets now command = ['python', os.path.join(testDir, 'experiments', 'multistep', 'make_datasets.py')] retval = call(command) self.assertEqual(retval, 0) # Generate any dynamically generated datasets now command = ['python', os.path.join(testDir, 'experiments', 'spatial_classification', 'make_datasets.py')] retval = call(command) self.assertEqual(retval, 0) # Run from the test directory so that we can find our experiments os.chdir(testDir) runExperiment = resource_filename("nupic", os.path.join("..", "scripts", "run_opf_experiment.py")) # A list of experiments to run. Valid attributes: # experimentDir - Required, path to the experiment directory containing # description.py # args - optional. List of arguments for run_opf_experiment # results - A dictionary of expected results. The keys are tuples # containing (predictionLogFileName, columnName). The # value is a (min, max) expected value from the last row # in the prediction log. multistepTests = [ # For this one, in theory the error for 1 step should be < 0.20 { 'experimentDir': 'experiments/multistep/simple_0', 'results': { ('DefaultTask.TemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='avg_err':steps=1:window=200:field=field1"): (0.0, 0.20), } }, # For this one, in theory the error for 1 step should be < 0.50, but we # get slightly higher because our sample size is smaller than ideal { 'experimentDir': 'experiments/multistep/simple_0_f2', 'results': { ('DefaultTask.TemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='aae':steps=1:window=200:field=field2"): (0.0, 0.525), } }, # For this one, in theory the error for 1 step should be < 0.20 { 'experimentDir': 'experiments/multistep/simple_1', 'results': { ('DefaultTask.TemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='avg_err':steps=1:window=200:field=field1"): (0.0, 0.20), } }, # For this test, we haven't figured out the theoretical error, this # error is determined empirically from actual results { 'experimentDir': 'experiments/multistep/simple_1_f2', 'results': { ('DefaultTask.TemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='aae':steps=1:window=200:field=field2"): (0.0, 3.65), } }, # For this one, in theory the error for 1 step should be < 0.20 { 'experimentDir': 'experiments/multistep/simple_2', 'results': { ('DefaultTask.TemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='avg_err':steps=1:window=200:field=field1"): (0.0, 0.20), } }, # For this one, in theory the error for 1 step should be < 0.10 and for # 3 step < 0.30, but our actual results are better. { 'experimentDir': 'experiments/multistep/simple_3', 'results': { ('DefaultTask.TemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='avg_err':steps=1:window=200:field=field1"): (0.0, 0.06), ('DefaultTask.TemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='avg_err':steps=3:window=200:field=field1"): (0.0, 0.20), } }, # For this test, we haven't figured out the theoretical error, this # error is determined empirically from actual results { 'experimentDir': 'experiments/multistep/simple_3_f2', 'results': { ('DefaultTask.TemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='aae':steps=1:window=200:field=field2"): (0.0, 0.6), ('DefaultTask.TemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='aae':steps=3:window=200:field=field2"): (0.0, 1.8), } }, # Test missing record support. # Should have 0 error by the end of the dataset { 'experimentDir': 'experiments/missing_record/simple_0', 'results': { ('DefaultTask.NontemporalMultiStep.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='avg_err':steps=1:window=25:field=field1"): (1.0, 1.0), } }, ] # end of multistepTests classificationTests = [ # ---------------------------------------------------------------------- # Classification Experiments { 'experimentDir': 'experiments/classification/category_hub_TP_0', 'results': { ('OnlineLearning.TemporalClassification.predictionLog.csv', 'classification:avg_err:window=200'): (0.0, 0.005), } }, { 'experimentDir': 'experiments/classification/category_TP_0', 'results': { ('OnlineLearning.TemporalClassification.predictionLog.csv', 'classification:avg_err:window=200'): (0.0, 0.045), ('OnlineLearning.TemporalClassification.predictionLog.csv', 'classConfidences:neg_auc:computeEvery=10:window=200'): (-1.0, -0.99), } }, { 'experimentDir': 'experiments/classification/category_TP_1', 'results': { ('OnlineLearning.TemporalClassification.predictionLog.csv', 'classification:avg_err:window=200'): (0.0, 0.005), } }, { 'experimentDir': 'experiments/classification/scalar_TP_0', 'results': { ('OnlineLearning.TemporalClassification.predictionLog.csv', 'classification:avg_err:window=200'): (0.0, 0.155), ('OnlineLearning.TemporalClassification.predictionLog.csv', 'classConfidences:neg_auc:computeEvery=10:window=200'): (-1.0, -0.900), } }, { 'experimentDir': 'experiments/classification/scalar_TP_1', 'results': { ('OnlineLearning.TemporalClassification.predictionLog.csv', 'classification:avg_err:window=200'): (0.0, 0.03), } }, ] # End of classification tests spatialClassificationTests = [ { 'experimentDir': 'experiments/spatial_classification/category_0', 'results': { ('DefaultTask.NontemporalClassification.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='avg_err':steps=0:window=100:field=classification"): (0.0, 0.05), } }, { 'experimentDir': 'experiments/spatial_classification/category_1', 'results': { ('DefaultTask.NontemporalClassification.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='avg_err':steps=0:window=100:field=classification"): (0.0, 0.0), } }, { 'experimentDir': 'experiments/spatial_classification/scalar_0', 'results': { ('DefaultTask.NontemporalClassification.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='aae':steps=0:window=100:field=classification"): (0.0, 0.025), } }, { 'experimentDir': 'experiments/spatial_classification/scalar_1', 'results': { ('DefaultTask.NontemporalClassification.predictionLog.csv', "multiStepBestPredictions:multiStep:errorMetric='aae':steps=0:window=100:field=classification"): (0.0, 0.01), } }, ] anomalyTests = [ # ---------------------------------------------------------------------- # Classification Experiments { 'experimentDir': 'experiments/anomaly/temporal/simple', 'results': { ('DefaultTask.TemporalAnomaly.predictionLog.csv', 'anomalyScore:passThruPrediction:window=1000:field=f'): (0.13, 0.14), } }, ] # End of anomaly tests tests = [] tests += multistepTests tests += classificationTests tests += spatialClassificationTests tests += anomalyTests # Uncomment this to only run a specific experiment(s) #tests = tests[7:8] # This contains a list of tuples: (expDir, key, results) summaryOfResults = [] startTime = time.time() testIdx = -1 for test in tests: testIdx += 1 expDirectory = test['experimentDir'] # ------------------------------------------------------------------- # Remove files/directories generated by previous tests: toDelete = [] # Remove inference results path = os.path.join(expDirectory, "inference") toDelete.append(path) path = os.path.join(expDirectory, "savedmodels") toDelete.append(path) for path in toDelete: if not os.path.exists(path): continue print "Removing %s ..." % path if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) # ------------------------------------------------------------------------ # Run the test. args = test.get('args', []) print "Running experiment %s ..." % (expDirectory) command = ['python', runExperiment, expDirectory] + args retVal = call(command) # If retVal is non-zero and this was not a negative test or if retVal is # zero and this is a negative test something went wrong. if retVal: print "Details of failed test: %s" % test print("TestIdx %d, OPF experiment '%s' failed with return code %i." % (testIdx, expDirectory, retVal)) self.assertFalse(retVal) # ----------------------------------------------------------------------- # Check the results for (key, expValues) in test['results'].items(): (logFilename, colName) = key # Open the prediction log file logFile = FileRecordStream(os.path.join(expDirectory, 'inference', logFilename)) colNames = [x[0] for x in logFile.getFields()] if not colName in colNames: print "TestIdx %d: %s not one of the columns in " \ "prediction log file. Available column names are: %s" % (testIdx, colName, colNames) self.assertTrue(colName in colNames) colIndex = colNames.index(colName) # Read till we get to the last line while True: try: row = logFile.next() except StopIteration: break result = row[colIndex] # Save summary of results summaryOfResults.append((expDirectory, colName, result)) print "Actual result for %s, %s:" % (expDirectory, colName), result print "Expected range:", expValues failed = (expValues[0] is not None and result < expValues[0]) \ or (expValues[1] is not None and result > expValues[1]) if failed: print ("TestIdx %d: Experiment %s failed. \nThe actual result" " for %s (%s) was outside the allowed range of %s" % (testIdx, expDirectory, colName, result, expValues)) else: print " Within expected range." self.assertFalse(failed) # ======================================================================= # Print summary of results: print print "Summary of results in all experiments run:" print "=========================================" prevExpDir = None for (expDir, key, results) in summaryOfResults: if expDir != prevExpDir: print print expDir prevExpDir = expDir print " %s: %s" % (key, results) print "\nElapsed time: %.1f seconds" % (time.time() - startTime) if __name__ == "__main__": unittest.main()
agpl-3.0
LarryHillyer/PoolHost
PoolHost/env/Lib/site-packages/pip/_vendor/appdirs.py
327
22368
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2005-2010 ActiveState Software Inc. # Copyright (c) 2013 Eddy Petrișor """Utilities for determining application-specific dirs. See <http://github.com/ActiveState/appdirs> for details and usage. """ # Dev Notes: # - MSDN on where to store app data files: # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 # - macOS: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html # - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html __version_info__ = (1, 4, 0) __version__ = '.'.join(map(str, __version_info__)) import sys import os PY3 = sys.version_info[0] == 3 if PY3: unicode = str if sys.platform.startswith('java'): import platform os_name = platform.java_ver()[3][0] if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc. system = 'win32' elif os_name.startswith('Mac'): # "macOS", etc. system = 'darwin' else: # "Linux", "SunOS", "FreeBSD", etc. # Setting this to "linux2" is not ideal, but only Windows or Mac # are actually checked for and the rest of the module expects # *sys.platform* style strings. system = 'linux2' else: system = sys.platform def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: macOS: ~/Library/Application Support/<AppName> Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName> Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName> Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName> Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName> For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/<AppName>". """ if system == "win32": if appauthor is None: appauthor = appname const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" path = os.path.normpath(_get_win_folder(const)) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == 'darwin': path = os.path.expanduser('~/Library/Application Support/') if appname: path = os.path.join(path, appname) else: path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): """Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical user data directories are: macOS: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == 'darwin': path = os.path.expanduser('/Library/Application Support') if appname: path = os.path.join(path, appname) else: # XDG default for $XDG_DATA_DIRS # only first, if multipath is False path = os.getenv('XDG_DATA_DIRS', os.pathsep.join(['/usr/local/share', '/usr/share'])) pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path if appname and version: path = os.path.join(path, version) return path def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: macOS: same as user_data_dir Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by deafult "~/.config/<AppName>". """ if system in ["win32", "darwin"]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): """Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of config dirs should be returned. By default, the first item from XDG_CONFIG_DIRS is returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set Typical user data directories are: macOS: same as site_data_dir Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in $XDG_CONFIG_DIRS Win *: same as site_data_dir Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system in ["win32", "darwin"]: path = site_data_dir(appname, appauthor) if appname and version: path = os.path.join(path, version) else: # XDG default for $XDG_CONFIG_DIRS # only first, if multipath is False path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Cache" to the base app data dir for Windows. See discussion below. Typical user cache directories are: macOS: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir` above). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. This can be disabled with the `opinion=False` option. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) if opinion: path = os.path.join(path, "Cache") elif system == 'darwin': path = os.path.expanduser('~/Library/Caches') if appname: path = os.path.join(path, appname) else: path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user cache directories are: macOS: ~/Library/Logs/<AppName> Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option. """ if system == "darwin": path = os.path.join( os.path.expanduser('~/Library/Logs'), appname) elif system == "win32": path = user_data_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "Logs") else: path = user_cache_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "log") if appname and version: path = os.path.join(path, version) return path class AppDirs(object): """Convenience wrapper for getting application dirs.""" def __init__(self, appname, appauthor=None, version=None, roaming=False, multipath=False): self.appname = appname self.appauthor = appauthor self.version = version self.roaming = roaming self.multipath = multipath @property def user_data_dir(self): return user_data_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_data_dir(self): return site_data_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_config_dir(self): return user_config_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_config_dir(self): return site_config_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_cache_dir(self): return user_cache_dir(self.appname, self.appauthor, version=self.version) @property def user_log_dir(self): return user_log_dir(self.appname, self.appauthor, version=self.version) #---- internal support stuff def _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) dir, type = _winreg.QueryValueEx(key, shell_folder_name) return dir def _get_win_folder_with_pywin32(csidl_name): from win32com.shell import shellcon, shell dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) # Try to make this a unicode path because SHGetFolderPath does # not return unicode strings when there is unicode data in the # path. try: dir = unicode(dir) # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in dir: if ord(c) > 255: has_high_char = True break if has_high_char: try: import win32api dir = win32api.GetShortPathName(dir) except ImportError: pass except UnicodeError: pass return dir def _get_win_folder_with_ctypes(csidl_name): import ctypes csidl_const = { "CSIDL_APPDATA": 26, "CSIDL_COMMON_APPDATA": 35, "CSIDL_LOCAL_APPDATA": 28, }[csidl_name] buf = ctypes.create_unicode_buffer(1024) ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in buf: if ord(c) > 255: has_high_char = True break if has_high_char: buf2 = ctypes.create_unicode_buffer(1024) if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): buf = buf2 return buf.value def _get_win_folder_with_jna(csidl_name): import array from com.sun import jna from com.sun.jna.platform import win32 buf_size = win32.WinDef.MAX_PATH * 2 buf = array.zeros('c', buf_size) shell = win32.Shell32.INSTANCE shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf) dir = jna.Native.toString(buf.tostring()).rstrip("\0") # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in dir: if ord(c) > 255: has_high_char = True break if has_high_char: buf = array.zeros('c', buf_size) kernel = win32.Kernel32.INSTANCE if kernal.GetShortPathName(dir, buf, buf_size): dir = jna.Native.toString(buf.tostring()).rstrip("\0") return dir if system == "win32": try: import win32com.shell _get_win_folder = _get_win_folder_with_pywin32 except ImportError: try: from ctypes import windll _get_win_folder = _get_win_folder_with_ctypes except ImportError: try: import com.sun.jna _get_win_folder = _get_win_folder_with_jna except ImportError: _get_win_folder = _get_win_folder_from_registry #---- self test code if __name__ == "__main__": appname = "MyApp" appauthor = "MyCompany" props = ("user_data_dir", "site_data_dir", "user_config_dir", "site_config_dir", "user_cache_dir", "user_log_dir") print("-- app dirs (with optional 'version')") dirs = AppDirs(appname, appauthor, version="1.0") for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (without optional 'version')") dirs = AppDirs(appname, appauthor) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (without optional 'appauthor')") dirs = AppDirs(appname) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (with disabled 'appauthor')") dirs = AppDirs(appname, appauthor=False) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop)))
gpl-3.0
0k/OpenUpgrade
addons/hr_timesheet/report/hr_timesheet_report.py
51
2704
from openerp import tools from openerp.osv import fields,osv from openerp.addons.decimal_precision import decimal_precision as dp class hr_timesheet_report(osv.osv): _name = "hr.timesheet.report" _description = "Timesheet" _auto = False _columns = { 'date': fields.date('Date', readonly=True), 'name': fields.char('Description', size=64,readonly=True), 'product_id' : fields.many2one('product.product', 'Product',readonly=True), 'journal_id' : fields.many2one('account.analytic.journal', 'Journal',readonly=True), 'general_account_id' : fields.many2one('account.account', 'General Account', readonly=True), 'user_id': fields.many2one('res.users', 'User',readonly=True), 'account_id': fields.many2one('account.analytic.account', 'Analytic Account',readonly=True), 'company_id': fields.many2one('res.company', 'Company',readonly=True), 'cost': fields.float('Cost', readonly=True, digits_compute=dp.get_precision('Account')), 'quantity': fields.float('Time', readonly=True), # TDE FIXME master: rename into time } def _select(self): select_str = """ SELECT min(hat.id) as id, aal.date as date, sum(aal.amount) as cost, sum(aal.unit_amount) as quantity, aal.account_id as account_id, aal.journal_id as journal_id, aal.product_id as product_id, aal.general_account_id as general_account_id, aal.user_id as user_id, aal.company_id as company_id, aal.currency_id as currency_id """ return select_str def _from(self): from_str = """ account_analytic_line as aal left join hr_analytic_timesheet as hat ON (hat.line_id=aal.id) """ return from_str def _group_by(self): group_by_str = """ GROUP BY aal.date, aal.account_id, aal.product_id, aal.general_account_id, aal.journal_id, aal.user_id, aal.company_id, aal.currency_id """ return group_by_str def init(self, cr): # self._table = hr_timesheet_report tools.drop_view_if_exists(cr, self._table) cr.execute("""CREATE or REPLACE VIEW %s as ( %s FROM ( %s ) %s )""" % (self._table, self._select(), self._from(), self._group_by())) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
draugiskisprendimai/odoo
addons/mrp/report/price.py
56
11687
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time import openerp from openerp.report.interface import report_rml from openerp.tools import to_xml from openerp.report import report_sxw from datetime import datetime from openerp.tools.translate import _ class report_custom(report_rml): def create_xml(self, cr, uid, ids, datas, context=None): number = (datas.get('form', False) and datas['form']['number']) or 1 registry = openerp.registry(cr.dbname) product_pool = registry.get('product.product') product_uom_pool = registry.get('product.uom') workcenter_pool = registry.get('mrp.workcenter') user_pool = registry.get('res.users') bom_pool = registry.get('mrp.bom') pricelist_pool = registry.get('product.pricelist') rml_obj=report_sxw.rml_parse(cr, uid, product_pool._name,context) rml_obj.localcontext.update({'lang':context.get('lang',False)}) company_currency = user_pool.browse(cr, uid, uid).company_id.currency_id company_currency_symbol = company_currency.symbol or company_currency.name product_uom_digits = rml_obj.get_digits(dp='Product Unit of Measure') purchase_price_digits = rml_obj.get_digits(dp='Product Price') def process_bom(bom, currency_id, factor=1): xml = '<row>' sum = 0 sum_strd = 0 prod = product_pool.browse(cr, uid, bom['product_id']) prod_name = to_xml(bom['name']) prod_qtty = factor * bom['product_qty'] product_uom = product_uom_pool.browse(cr, uid, bom['product_uom'], context=context) product_uom_name = to_xml(product_uom.name) main_sp_price, main_sp_name , main_strd_price = '','','' sellers, sellers_price = '','' if prod.seller_id: main_sp_name = '- <b>'+ to_xml(prod.seller_id.name) +'</b>\r\n' pricelist = prod.seller_id.property_product_pricelist_purchase price = pricelist_pool.price_get(cr,uid,[pricelist.id], prod.id, number*prod_qtty or 1.0, prod.seller_id.id, { 'uom': prod.uom_po_id.id, 'date': time.strftime('%Y-%m-%d'), })[pricelist.id] main_sp_price = """<b>"""+rml_obj.formatLang(price, digits=purchase_price_digits)+' '+ (company_currency_symbol)+"""</b>\r\n""" sum += prod_qtty*price std_price = product_uom_pool._compute_price(cr, uid, prod.uom_id.id, prod.standard_price, to_uom_id=product_uom.id) main_strd_price = str(std_price) + '\r\n' sum_strd = prod_qtty*std_price for seller_id in prod.seller_ids: if seller_id.name.id == prod.seller_id.id: continue sellers += '- <i>'+ to_xml(seller_id.name.name) +'</i>\r\n' pricelist = seller_id.name.property_product_pricelist_purchase price = pricelist_pool.price_get(cr,uid,[pricelist.id], prod.id, number*prod_qtty or 1.0, seller_id.name.id, { 'uom': prod.uom_po_id.id, 'date': time.strftime('%Y-%m-%d'), })[pricelist.id] sellers_price += """<i>"""+rml_obj.formatLang(price, digits=purchase_price_digits) +' '+ (company_currency_symbol) +"""</i>\r\n""" xml += """<col para='yes'> """+ prod_name +""" </col> <col para='yes'> """+ main_sp_name + sellers + """ </col> <col f='yes'>"""+ rml_obj.formatLang(prod_qtty, digits=product_uom_digits) +' '+ product_uom_name +"""</col> <col f='yes'>"""+ rml_obj.formatLang(float(main_strd_price), digits=purchase_price_digits) +' '+ (company_currency_symbol) +"""</col> <col f='yes'>""" + main_sp_price + sellers_price + """</col>'""" xml += '</row>' return xml, sum, sum_strd def process_workcenter(wrk): workcenter = workcenter_pool.browse(cr, uid, wrk['workcenter_id']) cost_cycle = wrk['cycle']*workcenter.costs_cycle cost_hour = wrk['hour']*workcenter.costs_hour total = cost_cycle + cost_hour xml = '<row>' xml += "<col para='yes'>" + to_xml(workcenter.name) + '</col>' xml += "<col/>" xml += """<col f='yes'>"""+rml_obj.formatLang(cost_cycle)+' '+ (company_currency_symbol) + """</col>""" xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour)+' '+ (company_currency_symbol) + """</col>""" xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour + cost_cycle)+' '+ (company_currency_symbol) + """</col>""" xml += '</row>' return xml, total xml = '' config_start = """ <config> <date>""" + to_xml(rml_obj.formatLang(datetime.now().strftime('%Y-%m-%d %H:%M:%S'),date_time=True)) + """</date> <company>%s</company> <PageSize>210.00mm,297.00mm</PageSize> <PageWidth>595.27</PageWidth> <PageHeight>841.88</PageHeight> <tableSize>55.00mm,58.00mm,29.00mm,29.00mm,29.00mm</tableSize> """ % to_xml(user_pool.browse(cr, uid, uid).company_id.name) config_stop = """ <report-footer>Generated by Odoo</report-footer> </config> """ workcenter_header = """ <lines style='header'> <row> <col>%s</col> <col t='yes'/> <col t='yes'>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row> </lines> """ % (_('Work Center name'), _('Cycles Cost'), _('Hourly Cost'),_('Work Cost')) prod_header = """ <row> <col>%s</col> <col>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row> """ % (_('Components'), _('Components suppliers'), _('Quantity'),_('Cost Price per Unit of Measure'), _('Supplier Price per Unit of Measure')) for product in product_pool.browse(cr, uid, ids, context=context): product_uom_name = to_xml(product.uom_id.name) bom_id = bom_pool._bom_find(cr, uid, product_id=product.id, context=context) title = "<title>%s</title>" %(_("Cost Structure")) title += "<title>%s</title>" % (to_xml(product.name)) xml += "<lines style='header'>" + title + prod_header + "</lines>" if not bom_id: total_strd = number * product.standard_price total = number * product_pool.price_get(cr, uid, [product.id], 'standard_price')[product.id] xml += """<lines style='lines'><row> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> </row></lines>""" xml += """<lines style='total'> <row> <col> """ + _('Total Cost of %s %s') % (str(number), product_uom_name) + """: </col> <col/> <col f='yes'/> <col t='yes'>"""+ rml_obj.formatLang(total_strd, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col> <col t='yes'>"""+ rml_obj.formatLang(total, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col> </row></lines>'""" else: bom = bom_pool.browse(cr, uid, bom_id, context=context) factor = number * product.uom_id.factor / bom.product_uom.factor sub_boms = bom_pool._bom_explode(cr, uid, bom, product, factor / bom.product_qty, context=context) total = 0 total_strd = 0 parent_bom = { 'product_qty': bom.product_qty, 'name': bom.product_id.name, 'product_uom': bom.product_uom.id, 'product_id': bom.product_id.id } xml_tmp = '' for sub_bom in (sub_boms and sub_boms[0]) or [parent_bom]: txt, sum, sum_strd = process_bom(sub_bom, company_currency.id) xml_tmp += txt total += sum total_strd += sum_strd xml += "<lines style='lines'>" + xml_tmp + '</lines>' xml += """<lines style='sub_total'> <row> <col> """ + _('Components Cost of %s %s') % (str(number), product_uom_name) + """: </col> <col/> <col t='yes'/> <col t='yes'>"""+ rml_obj.formatLang(total_strd, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col> <col t='yes'></col> </row></lines>'""" total2 = 0 xml_tmp = '' for wrk in (sub_boms and sub_boms[1]): txt, sum = process_workcenter(wrk) xml_tmp += txt total2 += sum if xml_tmp: xml += workcenter_header xml += "<lines style='lines'>" + xml_tmp + '</lines>' xml += """<lines style='sub_total'> <row> <col> """ + _('Work Cost of %s %s') % (str(number), product_uom_name) +""": </col> <col/> <col/> <col/> <col t='yes'>"""+ rml_obj.formatLang(total2, digits=purchase_price_digits) +' '+ (company_currency_symbol) +"""</col> </row></lines>'""" xml += """<lines style='total'> <row> <col> """ + _('Total Cost of %s %s') % (str(number), product_uom_name) + """: </col> <col/> <col t='yes'/> <col t='yes'>"""+ rml_obj.formatLang(total_strd+total2, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col> <col t='yes'></col> </row></lines>'""" xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + '</report>' return xml report_custom('report.product.price', 'product.product', '', 'addons/mrp/report/price.xsl') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ismailsunni/inasafe
safe/utilities/default_values.py
11
2237
# coding=utf-8 """Helpers to get/set default values.""" from safe.definitions import GLOBAL, zero_default_value from safe.definitions.utilities import definition __copyright__ = "Copyright 2016, The InaSAFE Project" __license__ = "GPL version 3" __email__ = "info@inasafe.org" __revision__ = '$Format:%H$' def set_inasafe_default_value_qsetting( qsetting, category, inasafe_field_key, value): """Helper method to set inasafe default value to qsetting. :param qsetting: QSettings. :type qsetting: QSettings :param category: Category of the default value. It can be global or recent. Global means the global setting for default value. Recent means the last set custom for default value from the user. :type category: str :param inasafe_field_key: Key for the field. :type inasafe_field_key: str :param value: Value of the inasafe_default_value. :type value: float, int """ key = 'inasafe/default_value/%s/%s' % (category, inasafe_field_key) qsetting.setValue(key, value) def get_inasafe_default_value_qsetting( qsetting, category, inasafe_field_key): """Helper method to get the inasafe default value from qsetting. :param qsetting: QSetting. :type qsetting: QSetting :param category: Category of the default value. It can be global or recent. Global means the global setting for default value. Recent means the last set custom for default value from the user. :type category: str :param inasafe_field_key: Key for the field. :type inasafe_field_key: str :returns: Value of the inasafe_default_value. :rtype: float """ key = 'inasafe/default_value/%s/%s' % (category, inasafe_field_key) default_value = qsetting.value(key) if default_value is None: if category == GLOBAL: # If empty for global setting, use default one. inasafe_field = definition(inasafe_field_key) default_value = inasafe_field.get('default_value', {}) return default_value.get('default_value', zero_default_value) return zero_default_value try: return float(default_value) except ValueError: return zero_default_value
gpl-3.0
sagiss/sardana
src/sardana/macroserver/macros/examples/funcs.py
1
2397
############################################################################## ## ## This file is part of Sardana ## ## http://www.sardana-controls.org/ ## ## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## ## Sardana is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## Sardana 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 Sardana. If not, see <http://www.gnu.org/licenses/>. ## ############################################################################## """Examples of macro functions""" from __future__ import print_function __all__ = ["mfunc1", "mfunc2", "mfunc3", "mfunc4", "mfunc5"] __docformat__ = 'restructuredtext' from sardana.macroserver.macro import Type, Macro, macro @macro() def mfunc1(self): """First macro function. No parameters whatsoever""" self.output("Executing %s", self.getName()) self.print("Hello",1) self.wa() @macro() def mfunc2(self, p1): """Second macro function. One parameter of unknown type""" self.output("parameter: %s", p1) @macro([ ["moveable", Type.Moveable, None, "motor to watch"] ]) def mfunc3(self, moveable): """Third macro function. A proper moveable parameter""" self.output("Moveable %s is at %s", moveable.getName(), moveable.getPosition()) self.ascan(moveable, 0, 10, 10, 0.1) self.mfunc1() @macro() def mfunc4(self, *args): """Fourth macro function. A list of parameters of unknown type""" self.output("parameters %s", args) @macro() def mfunc5(self, *args): """Fifth macro function. A list of parameters of unknown type""" self.output("parameters %s", args) @macro([ ["moveable", Type.Moveable, None, "moveable to move"], ["position", Type.Float, None, "absolute position"] ]) def move(self, moveable, position): """This macro moves a motor to the specified position""" moveable.move(position) self.print("Motor ended at ", moveable.getPosition())
lgpl-3.0
DESHRAJ/fjord
vendor/packages/translate-toolkit/translate/storage/placeables/__init__.py
5
2036
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008-2009 Zuza Software Foundation # # This file is part of the Translate Toolkit. # # 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, see <http://www.gnu.org/licenses/>. """ This module implements basic functionality to support placeables. A placeable is used to represent things like: 1. Substitutions For example, in ODF, footnotes appear in the ODF XML where they are defined; so if we extract a paragraph with some footnotes, the translator will have a lot of additional XML to with; so we separate the footnotes out into separate translation units and mark their positions in the original text with placeables. 2. Hiding of inline formatting data The translator doesn't want to have to deal with all the weird formatting conventions of wherever the text came from. 3. Marking variables This is an old issue - translators translate variable names which should remain untranslated. We can wrap placeables around variable names to avoid this. The placeables model follows the XLIFF standard's list of placeables. Please refer to the XLIFF specification to get a better understanding. """ import base import interfaces import general import xliff from base import * from base import __all__ as all_your_base from strelem import StringElem from parse import parse __all__ = [ 'base', 'interfaces', 'general', 'parse', 'StringElem', 'xliff' ] + all_your_base
bsd-3-clause
joernhees/scikit-learn
examples/linear_model/plot_sgd_iris.py
58
2202
""" ======================================== Plot multi-class SGD on the iris dataset ======================================== Plot decision surface of multi-class SGD on iris dataset. The hyperplanes corresponding to the three one-versus-all (OVA) classifiers are represented by the dashed lines. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.linear_model import SGDClassifier # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. We could # avoid this ugly slicing by using a two-dim dataset y = iris.target colors = "bry" # shuffle idx = np.arange(X.shape[0]) np.random.seed(13) np.random.shuffle(idx) X = X[idx] y = y[idx] # standardize mean = X.mean(axis=0) std = X.std(axis=0) X = (X - mean) / std h = .02 # step size in the mesh clf = SGDClassifier(alpha=0.001, n_iter=100).fit(X, y) # create a mesh to plot in x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, x_max]x[y_min, y_max]. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) plt.axis('tight') # Plot also the training points for i, color in zip(clf.classes_, colors): idx = np.where(y == i) plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], cmap=plt.cm.Paired) plt.title("Decision surface of multi-class SGD") plt.axis('tight') # Plot the three one-against-all classifiers xmin, xmax = plt.xlim() ymin, ymax = plt.ylim() coef = clf.coef_ intercept = clf.intercept_ def plot_hyperplane(c, color): def line(x0): return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1] plt.plot([xmin, xmax], [line(xmin), line(xmax)], ls="--", color=color) for i, color in zip(clf.classes_, colors): plot_hyperplane(i, color) plt.legend() plt.show()
bsd-3-clause
username4gh/my-i3
vim/vim-denite-codesearch/rplugin/python3/denite/source/csearch.py
1
5026
import shlex import typing from os.path import relpath from denite import util, process from denite.base.source import Base from denite.util import Nvim, UserContext, Candidates, Candidate def _candidate(result: typing.List[typing.Any], path: str) -> Candidate: return { 'word': result[3], 'abbr': '{}:{}{} {}'.format( path, result[1], (':' + result[2] if result[2] != '0' else ''), result[3]), 'action__path': result[0], 'action__line': result[1], 'action__col': result[2], 'action__text': result[3], } class Source(Base): def __init__(self, vim: Nvim) -> None: super().__init__(vim) self.name = 'csearch'# this has to be same with file name self.kind = 'file' self.vars = { 'command': ['_csearch'], 'min_interactive_pattern': 3, } self.matchers = ['matcher/regexp'] self.is_volatile = True def on_init(self, context: UserContext) -> None: context['__proc'] = None args = dict(enumerate(context['args'])) # paths context['__paths'] = self._init_paths(context, args) # arguments context['__arguments'] = self._init_arguments(context, args) # patterns context['__patterns'] = self._init_patterns(context, args) def on_close(self, context: UserContext) -> None: if context['__proc']: context['__proc'].kill() context['__proc'] = None def gather_candidates(self, context: UserContext) -> Candidates: if context['event'] == 'interactive': # Update input self.on_close(context) if (not context['input'] or len(context['input']) < self.vars['min_interactive_pattern']): return [] context['__patterns'] = [ '.*'.join(util.split_input(context['input']))] if context['__proc']: return self._async_gather_candidates( context, context['async_timeout']) if not context['__patterns'] or not self.vars['command']: return [] args = [util.expand(self.vars['command'][0])] args += self.vars['command'][1:] args += context['__patterns'] self.print_message(context, args) context['__proc'] = process.Process(args, context, context['path']) return self._async_gather_candidates(context, 0.5) def _async_gather_candidates(self, context: UserContext, timeout: float) -> Candidates: outs, errs = context['__proc'].communicate(timeout=timeout) if errs: self.error_message(context, errs) context['is_async'] = not context['__proc'].eof() if context['__proc'].eof(): context['__proc'] = None candidates = [] for line in outs: result = util.parse_jump_line(context['path'], line) if not result: continue path = relpath(result[0], start=context['path']) candidates.append(_candidate(result, path)) return candidates def _init_paths(self, context: UserContext, args: typing.Dict[str, typing.Any]) -> typing.List[str]: paths = [] arg = args.get(0, []) if arg: if isinstance(arg, str): paths = [arg] elif not isinstance(arg, list): raise AttributeError( '`args[0]` needs to be a `str` or `list`') elif context['path']: paths = [context['path']] return [util.abspath(self.vim, x) for x in paths] def _init_arguments(self, context: UserContext, args: typing.Dict[str, typing.Any]) -> typing.List[str]: arguments = [] arg = args.get(1, []) if arg: if isinstance(arg, str): if arg == '!': arg = util.input(self.vim, context, 'Argument: ') arguments = shlex.split(arg) elif not isinstance(arg, list): raise AttributeError( '`args[1]` needs to be a `str` or `list`') return arguments def _init_patterns(self, context: UserContext, args: typing.Dict[str, typing.Any]) -> typing.List[str]: patterns = [] arg = args.get(2, []) if arg: if isinstance(arg, str): if arg == '!': # Interactive mode context['is_interactive'] = True patterns = [context['input']] else: patterns = [arg] elif not isinstance(arg, list): raise AttributeError( '`args[2]` needs to be a `str` or `list`') elif context['input']: patterns = [context['input']] else: patterns = [util.input(self.vim, context, '[denite] _csearch ')] return [x for x in patterns if x]
unlicense
fxfitz/ansible
test/units/modules/cloud/google/test_gcp_url_map.py
158
6086
import unittest from ansible.modules.cloud.google.gcp_url_map import _build_path_matchers, _build_url_map_dict class TestGCPUrlMap(unittest.TestCase): """Unit tests for gcp_url_map module.""" params_dict = { 'url_map_name': 'foo_url_map_name', 'description': 'foo_url_map description', 'host_rules': [ { 'description': 'host rules description', 'hosts': [ 'www.example.com', 'www2.example.com' ], 'path_matcher': 'host_rules_path_matcher' } ], 'path_matchers': [ { 'name': 'path_matcher_one', 'description': 'path matcher one', 'defaultService': 'bes-pathmatcher-one-default', 'pathRules': [ { 'service': 'my-one-bes', 'paths': [ '/', '/aboutus' ] } ] }, { 'name': 'path_matcher_two', 'description': 'path matcher two', 'defaultService': 'bes-pathmatcher-two-default', 'pathRules': [ { 'service': 'my-two-bes', 'paths': [ '/webapp', '/graphs' ] } ] } ] } def test__build_path_matchers(self): input_list = [ { 'defaultService': 'bes-pathmatcher-one-default', 'description': 'path matcher one', 'name': 'path_matcher_one', 'pathRules': [ { 'paths': [ '/', '/aboutus' ], 'service': 'my-one-bes' } ] }, { 'defaultService': 'bes-pathmatcher-two-default', 'description': 'path matcher two', 'name': 'path_matcher_two', 'pathRules': [ { 'paths': [ '/webapp', '/graphs' ], 'service': 'my-two-bes' } ] } ] expected = [ { 'defaultService': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/bes-pathmatcher-one-default', 'description': 'path matcher one', 'name': 'path_matcher_one', 'pathRules': [ { 'paths': [ '/', '/aboutus' ], 'service': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-one-bes' } ] }, { 'defaultService': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/bes-pathmatcher-two-default', 'description': 'path matcher two', 'name': 'path_matcher_two', 'pathRules': [ { 'paths': [ '/webapp', '/graphs' ], 'service': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-two-bes' } ] } ] actual = _build_path_matchers(input_list, 'my-project') self.assertEqual(expected, actual) def test__build_url_map_dict(self): expected = { 'description': 'foo_url_map description', 'hostRules': [ { 'description': 'host rules description', 'hosts': [ 'www.example.com', 'www2.example.com' ], 'pathMatcher': 'host_rules_path_matcher' } ], 'name': 'foo_url_map_name', 'pathMatchers': [ { 'defaultService': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/bes-pathmatcher-one-default', 'description': 'path matcher one', 'name': 'path_matcher_one', 'pathRules': [ { 'paths': [ '/', '/aboutus' ], 'service': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-one-bes' } ] }, { 'defaultService': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/bes-pathmatcher-two-default', 'description': 'path matcher two', 'name': 'path_matcher_two', 'pathRules': [ { 'paths': [ '/webapp', '/graphs' ], 'service': 'https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-two-bes' } ] } ] } actual = _build_url_map_dict(self.params_dict, 'my-project') self.assertEqual(expected, actual)
gpl-3.0
Samuc/Proyecto-IV
lib/python2.7/site-packages/setuptools/command/develop.py
477
6447
from setuptools.command.easy_install import easy_install from distutils.util import convert_path, subst_vars from pkg_resources import Distribution, PathMetadata, normalize_path from distutils import log from distutils.errors import DistutilsError, DistutilsOptionError import os, sys, setuptools, glob class develop(easy_install): """Set up package for development""" description = "install package in 'development mode'" user_options = easy_install.user_options + [ ("uninstall", "u", "Uninstall this source package"), ("egg-path=", None, "Set the path to be used in the .egg-link file"), ] boolean_options = easy_install.boolean_options + ['uninstall'] command_consumes_arguments = False # override base def run(self): if self.uninstall: self.multi_version = True self.uninstall_link() else: self.install_for_development() self.warn_deprecated_options() def initialize_options(self): self.uninstall = None self.egg_path = None easy_install.initialize_options(self) self.setup_path = None self.always_copy_from = '.' # always copy eggs installed in curdir def finalize_options(self): ei = self.get_finalized_command("egg_info") if ei.broken_egg_info: raise DistutilsError( "Please rename %r to %r before using 'develop'" % (ei.egg_info, ei.broken_egg_info) ) self.args = [ei.egg_name] easy_install.finalize_options(self) self.expand_basedirs() self.expand_dirs() # pick up setup-dir .egg files only: no .egg-info self.package_index.scan(glob.glob('*.egg')) self.egg_link = os.path.join(self.install_dir, ei.egg_name+'.egg-link') self.egg_base = ei.egg_base if self.egg_path is None: self.egg_path = os.path.abspath(ei.egg_base) target = normalize_path(self.egg_base) if normalize_path(os.path.join(self.install_dir, self.egg_path)) != target: raise DistutilsOptionError( "--egg-path must be a relative path from the install" " directory to "+target ) # Make a distribution for the package's source self.dist = Distribution( target, PathMetadata(target, os.path.abspath(ei.egg_info)), project_name = ei.egg_name ) p = self.egg_base.replace(os.sep,'/') if p!= os.curdir: p = '../' * (p.count('/')+1) self.setup_path = p p = normalize_path(os.path.join(self.install_dir, self.egg_path, p)) if p != normalize_path(os.curdir): raise DistutilsOptionError( "Can't get a consistent path to setup script from" " installation directory", p, normalize_path(os.curdir)) def install_for_development(self): if sys.version_info >= (3,) and getattr(self.distribution, 'use_2to3', False): # If we run 2to3 we can not do this inplace: # Ensure metadata is up-to-date self.reinitialize_command('build_py', inplace=0) self.run_command('build_py') bpy_cmd = self.get_finalized_command("build_py") build_path = normalize_path(bpy_cmd.build_lib) # Build extensions self.reinitialize_command('egg_info', egg_base=build_path) self.run_command('egg_info') self.reinitialize_command('build_ext', inplace=0) self.run_command('build_ext') # Fixup egg-link and easy-install.pth ei_cmd = self.get_finalized_command("egg_info") self.egg_path = build_path self.dist.location = build_path self.dist._provider = PathMetadata(build_path, ei_cmd.egg_info) # XXX else: # Without 2to3 inplace works fine: self.run_command('egg_info') # Build extensions in-place self.reinitialize_command('build_ext', inplace=1) self.run_command('build_ext') self.install_site_py() # ensure that target dir is site-safe if setuptools.bootstrap_install_from: self.easy_install(setuptools.bootstrap_install_from) setuptools.bootstrap_install_from = None # create an .egg-link in the installation dir, pointing to our egg log.info("Creating %s (link to %s)", self.egg_link, self.egg_base) if not self.dry_run: f = open(self.egg_link,"w") f.write(self.egg_path + "\n" + self.setup_path) f.close() # postprocess the installed distro, fixing up .pth, installing scripts, # and handling requirements self.process_distribution(None, self.dist, not self.no_deps) def uninstall_link(self): if os.path.exists(self.egg_link): log.info("Removing %s (link to %s)", self.egg_link, self.egg_base) egg_link_file = open(self.egg_link) contents = [line.rstrip() for line in egg_link_file] egg_link_file.close() if contents not in ([self.egg_path], [self.egg_path, self.setup_path]): log.warn("Link points to %s: uninstall aborted", contents) return if not self.dry_run: os.unlink(self.egg_link) if not self.dry_run: self.update_pth(self.dist) # remove any .pth link to us if self.distribution.scripts: # XXX should also check for entry point scripts! log.warn("Note: you must uninstall or replace scripts manually!") def install_egg_scripts(self, dist): if dist is not self.dist: # Installing a dependency, so fall back to normal behavior return easy_install.install_egg_scripts(self,dist) # create wrapper scripts in the script dir, pointing to dist.scripts # new-style... self.install_wrapper_scripts(dist) # ...and old-style for script_name in self.distribution.scripts or []: script_path = os.path.abspath(convert_path(script_name)) script_name = os.path.basename(script_path) f = open(script_path,'rU') script_text = f.read() f.close() self.install_script(dist, script_name, script_text, script_path)
gpl-2.0
40223139/203739test
static/Brython3.1.0-20150301-090019/Lib/sre_constants.py
692
7172
# # Secret Labs' Regular Expression Engine # # various symbols used by the regular expression engine. # run this script to update the _sre include files! # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support module for sre""" # update when constants are added or removed MAGIC = 20031017 #MAXREPEAT = 2147483648 #from _sre import MAXREPEAT # SRE standard exception (access as sre.error) # should this really be here? class error(Exception): pass # operators FAILURE = "failure" SUCCESS = "success" ANY = "any" ANY_ALL = "any_all" ASSERT = "assert" ASSERT_NOT = "assert_not" AT = "at" BIGCHARSET = "bigcharset" BRANCH = "branch" CALL = "call" CATEGORY = "category" CHARSET = "charset" GROUPREF = "groupref" GROUPREF_IGNORE = "groupref_ignore" GROUPREF_EXISTS = "groupref_exists" IN = "in" IN_IGNORE = "in_ignore" INFO = "info" JUMP = "jump" LITERAL = "literal" LITERAL_IGNORE = "literal_ignore" MARK = "mark" MAX_REPEAT = "max_repeat" MAX_UNTIL = "max_until" MIN_REPEAT = "min_repeat" MIN_UNTIL = "min_until" NEGATE = "negate" NOT_LITERAL = "not_literal" NOT_LITERAL_IGNORE = "not_literal_ignore" RANGE = "range" REPEAT = "repeat" REPEAT_ONE = "repeat_one" SUBPATTERN = "subpattern" MIN_REPEAT_ONE = "min_repeat_one" # positions AT_BEGINNING = "at_beginning" AT_BEGINNING_LINE = "at_beginning_line" AT_BEGINNING_STRING = "at_beginning_string" AT_BOUNDARY = "at_boundary" AT_NON_BOUNDARY = "at_non_boundary" AT_END = "at_end" AT_END_LINE = "at_end_line" AT_END_STRING = "at_end_string" AT_LOC_BOUNDARY = "at_loc_boundary" AT_LOC_NON_BOUNDARY = "at_loc_non_boundary" AT_UNI_BOUNDARY = "at_uni_boundary" AT_UNI_NON_BOUNDARY = "at_uni_non_boundary" # categories CATEGORY_DIGIT = "category_digit" CATEGORY_NOT_DIGIT = "category_not_digit" CATEGORY_SPACE = "category_space" CATEGORY_NOT_SPACE = "category_not_space" CATEGORY_WORD = "category_word" CATEGORY_NOT_WORD = "category_not_word" CATEGORY_LINEBREAK = "category_linebreak" CATEGORY_NOT_LINEBREAK = "category_not_linebreak" CATEGORY_LOC_WORD = "category_loc_word" CATEGORY_LOC_NOT_WORD = "category_loc_not_word" CATEGORY_UNI_DIGIT = "category_uni_digit" CATEGORY_UNI_NOT_DIGIT = "category_uni_not_digit" CATEGORY_UNI_SPACE = "category_uni_space" CATEGORY_UNI_NOT_SPACE = "category_uni_not_space" CATEGORY_UNI_WORD = "category_uni_word" CATEGORY_UNI_NOT_WORD = "category_uni_not_word" CATEGORY_UNI_LINEBREAK = "category_uni_linebreak" CATEGORY_UNI_NOT_LINEBREAK = "category_uni_not_linebreak" OPCODES = [ # failure=0 success=1 (just because it looks better that way :-) FAILURE, SUCCESS, ANY, ANY_ALL, ASSERT, ASSERT_NOT, AT, BRANCH, CALL, CATEGORY, CHARSET, BIGCHARSET, GROUPREF, GROUPREF_EXISTS, GROUPREF_IGNORE, IN, IN_IGNORE, INFO, JUMP, LITERAL, LITERAL_IGNORE, MARK, MAX_UNTIL, MIN_UNTIL, NOT_LITERAL, NOT_LITERAL_IGNORE, NEGATE, RANGE, REPEAT, REPEAT_ONE, SUBPATTERN, MIN_REPEAT_ONE ] ATCODES = [ AT_BEGINNING, AT_BEGINNING_LINE, AT_BEGINNING_STRING, AT_BOUNDARY, AT_NON_BOUNDARY, AT_END, AT_END_LINE, AT_END_STRING, AT_LOC_BOUNDARY, AT_LOC_NON_BOUNDARY, AT_UNI_BOUNDARY, AT_UNI_NON_BOUNDARY ] CHCODES = [ CATEGORY_DIGIT, CATEGORY_NOT_DIGIT, CATEGORY_SPACE, CATEGORY_NOT_SPACE, CATEGORY_WORD, CATEGORY_NOT_WORD, CATEGORY_LINEBREAK, CATEGORY_NOT_LINEBREAK, CATEGORY_LOC_WORD, CATEGORY_LOC_NOT_WORD, CATEGORY_UNI_DIGIT, CATEGORY_UNI_NOT_DIGIT, CATEGORY_UNI_SPACE, CATEGORY_UNI_NOT_SPACE, CATEGORY_UNI_WORD, CATEGORY_UNI_NOT_WORD, CATEGORY_UNI_LINEBREAK, CATEGORY_UNI_NOT_LINEBREAK ] def makedict(list): d = {} i = 0 for item in list: d[item] = i i = i + 1 return d OPCODES = makedict(OPCODES) ATCODES = makedict(ATCODES) CHCODES = makedict(CHCODES) # replacement operations for "ignore case" mode OP_IGNORE = { GROUPREF: GROUPREF_IGNORE, IN: IN_IGNORE, LITERAL: LITERAL_IGNORE, NOT_LITERAL: NOT_LITERAL_IGNORE } AT_MULTILINE = { AT_BEGINNING: AT_BEGINNING_LINE, AT_END: AT_END_LINE } AT_LOCALE = { AT_BOUNDARY: AT_LOC_BOUNDARY, AT_NON_BOUNDARY: AT_LOC_NON_BOUNDARY } AT_UNICODE = { AT_BOUNDARY: AT_UNI_BOUNDARY, AT_NON_BOUNDARY: AT_UNI_NON_BOUNDARY } CH_LOCALE = { CATEGORY_DIGIT: CATEGORY_DIGIT, CATEGORY_NOT_DIGIT: CATEGORY_NOT_DIGIT, CATEGORY_SPACE: CATEGORY_SPACE, CATEGORY_NOT_SPACE: CATEGORY_NOT_SPACE, CATEGORY_WORD: CATEGORY_LOC_WORD, CATEGORY_NOT_WORD: CATEGORY_LOC_NOT_WORD, CATEGORY_LINEBREAK: CATEGORY_LINEBREAK, CATEGORY_NOT_LINEBREAK: CATEGORY_NOT_LINEBREAK } CH_UNICODE = { CATEGORY_DIGIT: CATEGORY_UNI_DIGIT, CATEGORY_NOT_DIGIT: CATEGORY_UNI_NOT_DIGIT, CATEGORY_SPACE: CATEGORY_UNI_SPACE, CATEGORY_NOT_SPACE: CATEGORY_UNI_NOT_SPACE, CATEGORY_WORD: CATEGORY_UNI_WORD, CATEGORY_NOT_WORD: CATEGORY_UNI_NOT_WORD, CATEGORY_LINEBREAK: CATEGORY_UNI_LINEBREAK, CATEGORY_NOT_LINEBREAK: CATEGORY_UNI_NOT_LINEBREAK } # flags SRE_FLAG_TEMPLATE = 1 # template mode (disable backtracking) SRE_FLAG_IGNORECASE = 2 # case insensitive SRE_FLAG_LOCALE = 4 # honour system locale SRE_FLAG_MULTILINE = 8 # treat target as multiline string SRE_FLAG_DOTALL = 16 # treat target as a single string SRE_FLAG_UNICODE = 32 # use unicode "locale" SRE_FLAG_VERBOSE = 64 # ignore whitespace and comments SRE_FLAG_DEBUG = 128 # debugging SRE_FLAG_ASCII = 256 # use ascii "locale" # flags for INFO primitive SRE_INFO_PREFIX = 1 # has prefix SRE_INFO_LITERAL = 2 # entire pattern is literal (given by prefix) SRE_INFO_CHARSET = 4 # pattern starts with character from given set if __name__ == "__main__": def dump(f, d, prefix): items = sorted(d.items(), key=lambda a: a[1]) for k, v in items: f.write("#define %s_%s %s\n" % (prefix, k.upper(), v)) f = open("sre_constants.h", "w") f.write("""\ /* * Secret Labs' Regular Expression Engine * * regular expression matching engine * * NOTE: This file is generated by sre_constants.py. If you need * to change anything in here, edit sre_constants.py and run it. * * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. * * See the _sre.c file for information on usage and redistribution. */ """) f.write("#define SRE_MAGIC %d\n" % MAGIC) dump(f, OPCODES, "SRE_OP") dump(f, ATCODES, "SRE") dump(f, CHCODES, "SRE") f.write("#define SRE_FLAG_TEMPLATE %d\n" % SRE_FLAG_TEMPLATE) f.write("#define SRE_FLAG_IGNORECASE %d\n" % SRE_FLAG_IGNORECASE) f.write("#define SRE_FLAG_LOCALE %d\n" % SRE_FLAG_LOCALE) f.write("#define SRE_FLAG_MULTILINE %d\n" % SRE_FLAG_MULTILINE) f.write("#define SRE_FLAG_DOTALL %d\n" % SRE_FLAG_DOTALL) f.write("#define SRE_FLAG_UNICODE %d\n" % SRE_FLAG_UNICODE) f.write("#define SRE_FLAG_VERBOSE %d\n" % SRE_FLAG_VERBOSE) f.write("#define SRE_INFO_PREFIX %d\n" % SRE_INFO_PREFIX) f.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL) f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET) f.close() print("done")
gpl-3.0
blrm/openshift-tools
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/lib/base.py
7
21696
# pylint: skip-file # flake8: noqa # pylint: disable=too-many-lines # noqa: E301,E302,E303,T001 class OpenShiftCLIError(Exception): '''Exception class for openshiftcli''' pass ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')] def locate_oc_binary(): ''' Find and return oc binary file ''' # https://github.com/openshift/openshift-ansible/issues/3410 # oc can be in /usr/local/bin in some cases, but that may not # be in $PATH due to ansible/sudo paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS oc_binary = 'oc' # Use shutil.which if it is available, otherwise fallback to a naive path search try: which_result = shutil.which(oc_binary, path=os.pathsep.join(paths)) if which_result is not None: oc_binary = which_result except AttributeError: for path in paths: if os.path.exists(os.path.join(path, oc_binary)): oc_binary = os.path.join(path, oc_binary) break return oc_binary # pylint: disable=too-few-public-methods class OpenShiftCLI(object): ''' Class to wrap the command line tools ''' def __init__(self, namespace, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False, all_namespaces=False): ''' Constructor for OpenshiftCLI ''' self.namespace = namespace self.verbose = verbose self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig) self.all_namespaces = all_namespaces self.oc_binary = locate_oc_binary() # Pylint allows only 5 arguments to be passed. # pylint: disable=too-many-arguments def _replace_content(self, resource, rname, content, edits=None, force=False, sep='.'): ''' replace the current object with the content ''' res = self._get(resource, rname) if not res['results']: return res fname = Utils.create_tmpfile(rname + '-') yed = Yedit(fname, res['results'][0], separator=sep) updated = False if content is not None: changes = [] for key, value in content.items(): changes.append(yed.put(key, value)) if any([change[0] for change in changes]): updated = True elif edits is not None: results = Yedit.process_edits(edits, yed) if results['changed']: updated = True if updated: yed.write() atexit.register(Utils.cleanup, [fname]) return self._replace(fname, force) return {'returncode': 0, 'updated': False} def _replace(self, fname, force=False): '''replace the current object with oc replace''' # We are removing the 'resourceVersion' to handle # a race condition when modifying oc objects yed = Yedit(fname) results = yed.delete('metadata.resourceVersion') if results[0]: yed.write() cmd = ['replace', '-f', fname] if force: cmd.append('--force') return self.openshift_cmd(cmd) def _create_from_content(self, rname, content): '''create a temporary file and then call oc create on it''' fname = Utils.create_tmpfile(rname + '-') yed = Yedit(fname, content=content) yed.write() atexit.register(Utils.cleanup, [fname]) return self._create(fname) def _create(self, fname): '''call oc create on a filename''' return self.openshift_cmd(['create', '-f', fname]) def _delete(self, resource, name=None, selector=None): '''call oc delete on a resource''' cmd = ['delete', resource] if selector is not None: cmd.append('--selector={}'.format(selector)) elif name is not None: cmd.append(name) else: raise OpenShiftCLIError('Either name or selector is required when calling delete.') return self.openshift_cmd(cmd) def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501 '''process a template template_name: the name of the template to process create: whether to send to oc create after processing params: the parameters for the template template_data: the incoming template's data; instead of a file ''' cmd = ['process'] if template_data: cmd.extend(['-f', '-']) else: cmd.append(template_name) if params: param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()] cmd.append('-v') cmd.extend(param_str) results = self.openshift_cmd(cmd, output=True, input_data=template_data) if results['returncode'] != 0 or not create: return results fname = Utils.create_tmpfile(template_name + '-') yed = Yedit(fname, results['results']) yed.write() atexit.register(Utils.cleanup, [fname]) return self.openshift_cmd(['create', '-f', fname]) def _get(self, resource, name=None, selector=None, field_selector=None): '''return a resource by name ''' cmd = ['get', resource] if selector is not None: cmd.append('--selector={}'.format(selector)) if field_selector is not None: cmd.append('--field-selector={}'.format(field_selector)) # Name cannot be used with selector or field_selector. if selector is None and field_selector is None and name is not None: cmd.append(name) cmd.extend(['-o', 'json']) rval = self.openshift_cmd(cmd, output=True) # Ensure results are retuned in an array if 'items' in rval: rval['results'] = rval['items'] elif not isinstance(rval['results'], list): rval['results'] = [rval['results']] return rval def _schedulable(self, node=None, selector=None, schedulable=True): ''' perform oadm manage-node scheduable ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) cmd.append('--schedulable={}'.format(schedulable)) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501 def _list_pods(self, node=None, selector=None, pod_selector=None): ''' perform oadm list pods node: the node in which to list pods selector: the label selector filter if provided pod_selector: the pod selector filter if provided ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) if pod_selector: cmd.append('--pod-selector={}'.format(pod_selector)) cmd.extend(['--list-pods', '-o', 'json']) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # pylint: disable=too-many-arguments def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False): ''' perform oadm manage-node evacuate ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) if dry_run: cmd.append('--dry-run') if pod_selector: cmd.append('--pod-selector={}'.format(pod_selector)) if grace_period: cmd.append('--grace-period={}'.format(int(grace_period))) if force: cmd.append('--force') cmd.append('--evacuate') return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') def _version(self): ''' return the openshift version''' return self.openshift_cmd(['version'], output=True, output_type='raw') def _import_image(self, url=None, name=None, tag=None): ''' perform image import ''' cmd = ['import-image'] image = '{0}'.format(name) if tag: image += ':{0}'.format(tag) cmd.append(image) if url: cmd.append('--from={0}/{1}'.format(url, image)) cmd.append('-n{0}'.format(self.namespace)) cmd.append('--confirm') return self.openshift_cmd(cmd) def _run(self, cmds, input_data): ''' Actually executes the command. This makes mocking easier. ''' curr_env = os.environ.copy() curr_env.update({'KUBECONFIG': self.kubeconfig}) proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env) stdout, stderr = proc.communicate(input_data) return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8') # pylint: disable=too-many-arguments,too-many-branches def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None): '''Base command for oc ''' cmds = [self.oc_binary] if oadm: cmds.append('adm') cmds.extend(cmd) if self.all_namespaces: cmds.extend(['--all-namespaces']) elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501 cmds.extend(['-n', self.namespace]) if self.verbose: print(' '.join(cmds)) try: returncode, stdout, stderr = self._run(cmds, input_data) except OSError as ex: returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex) rval = {"returncode": returncode, "cmd": ' '.join(cmds)} if output_type == 'json': rval['results'] = {} if output and stdout: try: rval['results'] = json.loads(stdout) except ValueError as verr: if "No JSON object could be decoded" in verr.args: rval['err'] = verr.args elif output_type == 'raw': rval['results'] = stdout if output else '' if self.verbose: print("STDOUT: {0}".format(stdout)) print("STDERR: {0}".format(stderr)) if 'err' in rval or returncode != 0: rval.update({"stderr": stderr, "stdout": stdout}) return rval class Utils(object): ''' utilities for openshiftcli modules ''' @staticmethod def _write(filename, contents): ''' Actually write the file contents to disk. This helps with mocking. ''' with open(filename, 'w') as sfd: sfd.write(str(contents)) @staticmethod def create_tmp_file_from_contents(rname, data, ftype='yaml'): ''' create a file in tmp with name and contents''' tmp = Utils.create_tmpfile(prefix=rname) if ftype == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripDumper'): Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper)) else: Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False)) elif ftype == 'json': Utils._write(tmp, json.dumps(data)) else: Utils._write(tmp, data) # Register cleanup when module is done atexit.register(Utils.cleanup, [tmp]) return tmp @staticmethod def create_tmpfile_copy(inc_file): '''create a temporary copy of a file''' tmpfile = Utils.create_tmpfile('lib_openshift-') Utils._write(tmpfile, open(inc_file).read()) # Cleanup the tmpfile atexit.register(Utils.cleanup, [tmpfile]) return tmpfile @staticmethod def create_tmpfile(prefix='tmp'): ''' Generates and returns a temporary file name ''' with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp: return tmp.name @staticmethod def create_tmp_files_from_contents(content, content_type=None): '''Turn an array of dict: filename, content into a files array''' if not isinstance(content, list): content = [content] files = [] for item in content: path = Utils.create_tmp_file_from_contents(item['path'] + '-', item['data'], ftype=content_type) files.append({'name': os.path.basename(item['path']), 'path': path}) return files @staticmethod def cleanup(files): '''Clean up on exit ''' for sfile in files: if os.path.exists(sfile): if os.path.isdir(sfile): shutil.rmtree(sfile) elif os.path.isfile(sfile): os.remove(sfile) @staticmethod def exists(results, _name): ''' Check to see if the results include the name ''' if not results: return False if Utils.find_result(results, _name): return True return False @staticmethod def find_result(results, _name): ''' Find the specified result by name''' rval = None for result in results: if 'metadata' in result and result['metadata']['name'] == _name: rval = result break return rval @staticmethod def get_resource_file(sfile, sfile_type='yaml'): ''' return the service file ''' contents = None with open(sfile) as sfd: contents = sfd.read() if sfile_type == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripLoader'): contents = yaml.load(contents, yaml.RoundTripLoader) else: contents = yaml.safe_load(contents) elif sfile_type == 'json': contents = json.loads(contents) return contents @staticmethod def filter_versions(stdout): ''' filter the oc version output ''' version_dict = {} version_search = ['oc', 'openshift', 'kubernetes'] for line in stdout.strip().split('\n'): for term in version_search: if not line: continue if line.startswith(term): version_dict[term] = line.split()[-1] # horrible hack to get openshift version in Openshift 3.2 # By default "oc version in 3.2 does not return an "openshift" version if "openshift" not in version_dict: version_dict["openshift"] = version_dict["oc"] return version_dict @staticmethod def add_custom_versions(versions): ''' create custom versions strings ''' versions_dict = {} for tech, version in versions.items(): # clean up "-" from version if "-" in version: version = version.split("-")[0] if version.startswith('v'): versions_dict[tech + '_numeric'] = version[1:].split('+')[0] # "v3.3.0.33" is what we have, we want "3.3" versions_dict[tech + '_short'] = version[1:4] return versions_dict @staticmethod def openshift_installed(): ''' check if openshift is installed ''' import rpm transaction_set = rpm.TransactionSet() rpmquery = transaction_set.dbMatch("name", "atomic-openshift") return rpmquery.count() > 0 # Disabling too-many-branches. This is a yaml dictionary comparison function # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements @staticmethod def check_def_equal(user_def, result_def, skip_keys=None, debug=False): ''' Given a user defined definition, compare it with the results given back by our query. ''' # Currently these values are autogenerated and we do not need to check them skip = ['metadata', 'status'] if skip_keys: skip.extend(skip_keys) for key, value in result_def.items(): if key in skip: continue # Both are lists if isinstance(value, list): if key not in user_def: if debug: print('User data does not have key [%s]' % key) print('User data: %s' % user_def) return False if not isinstance(user_def[key], list): if debug: print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key])) return False if len(user_def[key]) != len(value): if debug: print("List lengths are not equal.") print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value))) print("user_def: %s" % user_def[key]) print("value: %s" % value) return False for values in zip(user_def[key], value): if isinstance(values[0], dict) and isinstance(values[1], dict): if debug: print('sending list - list') print(type(values[0])) print(type(values[1])) result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug) if not result: print('list compare returned false') return False elif value != user_def[key]: if debug: print('value should be identical') print(user_def[key]) print(value) return False # recurse on a dictionary elif isinstance(value, dict): if key not in user_def: if debug: print("user_def does not have key [%s]" % key) return False if not isinstance(user_def[key], dict): if debug: print("dict returned false: not instance of dict") return False # before passing ensure keys match api_values = set(value.keys()) - set(skip) user_values = set(user_def[key].keys()) - set(skip) if api_values != user_values: if debug: print("keys are not equal in dict") print(user_values) print(api_values) return False result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug) if not result: if debug: print("dict returned false") print(result) return False # Verify each key, value pair is the same else: if key not in user_def or value != user_def[key]: if debug: print("value not equal; user_def does not have key") print(key) print(value) if key in user_def: print(user_def[key]) return False if debug: print('returning true') return True class OpenShiftCLIConfig(object): '''Generic Config''' def __init__(self, rname, namespace, kubeconfig, options): self.kubeconfig = kubeconfig self.name = rname self.namespace = namespace self._options = options @property def config_options(self): ''' return config options ''' return self._options def to_option_list(self, ascommalist=''): '''return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs''' return self.stringify(ascommalist) def stringify(self, ascommalist=''): ''' return the options hash as cli params in a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs ''' rval = [] for key in sorted(self.config_options.keys()): data = self.config_options[key] if data['include'] \ and (data['value'] is not None or isinstance(data['value'], int)): if key == ascommalist: val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())]) else: val = data['value'] rval.append('--{}={}'.format(key.replace('_', '-'), val)) return rval
apache-2.0
rohitwaghchaure/erpnext_develop
erpnext/stock/doctype/stock_entry/stock_entry_utils.py
2
3215
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt import frappe, erpnext from frappe.utils import cint, flt @frappe.whitelist() def make_stock_entry(**args): '''Helper function to make a Stock Entry :item_code: Item to be moved :qty: Qty to be moved :from_warehouse: Optional :to_warehouse: Optional :rate: Optional :serial_no: Optional :batch_no: Optional :posting_date: Optional :posting_time: Optional :do_not_save: Optional flag :do_not_submit: Optional flag ''' def process_serial_numbers(serial_nos_list): serial_nos_list = [ '\n'.join(serial_num['serial_no'] for serial_num in serial_nos_list) ] uniques = list(set(serial_nos_list[0].split('\n'))) return '\n'.join(uniques) s = frappe.new_doc("Stock Entry") args = frappe._dict(args) if args.posting_date or args.posting_time: s.set_posting_time = 1 if args.posting_date: s.posting_date = args.posting_date if args.posting_time: s.posting_time = args.posting_time # map names if args.from_warehouse: args.source = args.from_warehouse if args.to_warehouse: args.target = args.to_warehouse if args.item_code: args.item = args.item_code if isinstance(args.qty, basestring): if '.' in args.qty: args.qty = flt(args.qty) else: args.qty = cint(args.qty) # purpose if not args.purpose: if args.source and args.target: s.purpose = "Material Transfer" elif args.source: s.purpose = "Material Issue" else: s.purpose = "Material Receipt" else: s.purpose = args.purpose # company if not args.company: if args.source: args.company = frappe.db.get_value('Warehouse', args.source, 'company') elif args.target: args.company = frappe.db.get_value('Warehouse', args.target, 'company') # set vales from test if frappe.flags.in_test: if not args.company: args.company = '_Test Company' if not args.item: args.item = '_Test Item' s.company = args.company or erpnext.get_default_company() s.purchase_receipt_no = args.purchase_receipt_no s.delivery_note_no = args.delivery_note_no s.sales_invoice_no = args.sales_invoice_no if not args.cost_center: args.cost_center = frappe.get_value('Company', s.company, 'cost_center') if not args.expense_account: args.expense_account = frappe.get_value('Company', s.company, 'stock_adjustment_account') # We can find out the serial number using the batch source document serial_number = args.serial_no if not args.serial_no and args.qty and args.batch_no: serial_number_list = frappe.get_list( doctype='Stock Ledger Entry', fields=['serial_no'], filters={ 'batch_no': args.batch_no, 'warehouse': args.from_warehouse } ) serial_number = process_serial_numbers(serial_number_list) args.serial_no = serial_number s.append("items", { "item_code": args.item, "s_warehouse": args.source, "t_warehouse": args.target, "qty": args.qty, "basic_rate": args.rate or args.basic_rate, "conversion_factor": 1.0, "serial_no": args.serial_no, 'batch_no': args.batch_no, 'cost_center': args.cost_center, 'expense_account': args.expense_account }) if not args.do_not_save: s.insert() if not args.do_not_submit: s.submit() return s
gpl-3.0
TiVoMaker/boto
boto/mws/response.py
152
23191
# Copyright (c) 2012-2014 Andy Davidoff http://www.disruptek.com/ # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, dis- tribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the fol- lowing conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- ITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from decimal import Decimal from boto.compat import filter, map class ComplexType(dict): _value = 'Value' def __repr__(self): return '{0}{1}'.format(getattr(self, self._value, None), self.copy()) def __str__(self): return str(getattr(self, self._value, '')) class DeclarativeType(object): def __init__(self, _hint=None, **kw): self._value = None if _hint is not None: self._hint = _hint return class JITResponse(ResponseElement): pass self._hint = JITResponse self._hint.__name__ = 'JIT_{0}/{1}'.format(self.__class__.__name__, hex(id(self._hint))[2:]) for name, value in kw.items(): setattr(self._hint, name, value) def __repr__(self): parent = getattr(self, '_parent', None) return '<{0}_{1}/{2}_{3}>'.format(self.__class__.__name__, parent and parent._name or '?', getattr(self, '_name', '?'), hex(id(self.__class__))) def setup(self, parent, name, *args, **kw): self._parent = parent self._name = name self._clone = self.__class__(_hint=self._hint) self._clone._parent = parent self._clone._name = name setattr(self._parent, self._name, self._clone) def start(self, *args, **kw): raise NotImplementedError def end(self, *args, **kw): raise NotImplementedError def teardown(self, *args, **kw): setattr(self._parent, self._name, self._value) class Element(DeclarativeType): def start(self, *args, **kw): self._value = self._hint(parent=self._parent, **kw) return self._value def end(self, *args, **kw): pass class SimpleList(DeclarativeType): def __init__(self, *args, **kw): super(SimpleList, self).__init__(*args, **kw) self._value = [] def start(self, *args, **kw): return None def end(self, name, value, *args, **kw): self._value.append(value) class ElementList(SimpleList): def start(self, *args, **kw): value = self._hint(parent=self._parent, **kw) self._value.append(value) return value def end(self, *args, **kw): pass class MemberList(Element): def __init__(self, _member=None, _hint=None, *args, **kw): message = 'Invalid `member` specification in {0}'.format(self.__class__.__name__) assert 'member' not in kw, message if _member is None: if _hint is None: super(MemberList, self).__init__(*args, member=ElementList(**kw)) else: super(MemberList, self).__init__(_hint=_hint) else: if _hint is None: if issubclass(_member, DeclarativeType): member = _member(**kw) else: member = ElementList(_member, **kw) super(MemberList, self).__init__(*args, member=member) else: message = 'Nonsensical {0} hint {1!r}'.format(self.__class__.__name__, _hint) raise AssertionError(message) def teardown(self, *args, **kw): if self._value is None: self._value = [] else: if isinstance(self._value.member, DeclarativeType): self._value.member = [] self._value = self._value.member super(MemberList, self).teardown(*args, **kw) class ResponseFactory(object): def __init__(self, scopes=None): self.scopes = [] if scopes is None else scopes def element_factory(self, name, parent): class DynamicElement(parent): _name = name setattr(DynamicElement, '__name__', str(name)) return DynamicElement def search_scopes(self, key): for scope in self.scopes: if hasattr(scope, key): return getattr(scope, key) if hasattr(scope, '__getitem__'): if key in scope: return scope[key] def find_element(self, action, suffix, parent): element = self.search_scopes(action + suffix) if element is not None: return element if action.endswith('ByNextToken'): element = self.search_scopes(action[:-len('ByNextToken')] + suffix) if element is not None: return self.element_factory(action + suffix, element) return self.element_factory(action + suffix, parent) def __call__(self, action, connection=None): response = self.find_element(action, 'Response', Response) if not hasattr(response, action + 'Result'): result = self.find_element(action, 'Result', ResponseElement) setattr(response, action + 'Result', Element(result)) return response(connection=connection) def strip_namespace(func): def wrapper(self, name, *args, **kw): if self._namespace is not None: if name.startswith(self._namespace + ':'): name = name[len(self._namespace + ':'):] return func(self, name, *args, **kw) return wrapper class ResponseElement(dict): _override = {} _name = None _namespace = None def __init__(self, connection=None, name=None, parent=None, attrs=None): if parent is not None and self._namespace is None: self._namespace = parent._namespace if connection is not None: self._connection = connection self._name = name or self._name or self.__class__.__name__ self._declared('setup', attrs=attrs) dict.__init__(self, attrs and attrs.copy() or {}) def _declared(self, op, **kw): def inherit(obj): result = {} for cls in getattr(obj, '__bases__', ()): result.update(inherit(cls)) result.update(obj.__dict__) return result scope = inherit(self.__class__) scope.update(self.__dict__) declared = lambda attr: isinstance(attr[1], DeclarativeType) for name, node in filter(declared, scope.items()): getattr(node, op)(self, name, parentname=self._name, **kw) @property def connection(self): return self._connection def __repr__(self): render = lambda pair: '{0!s}: {1!r}'.format(*pair) do_show = lambda pair: not pair[0].startswith('_') attrs = filter(do_show, self.__dict__.items()) name = self.__class__.__name__ if name.startswith('JIT_'): name = '^{0}^'.format(self._name or '') return '{0}{1!r}({2})'.format( name, self.copy(), ', '.join(map(render, attrs))) def _type_for(self, name, attrs): return self._override.get(name, globals().get(name, ResponseElement)) @strip_namespace def startElement(self, name, attrs, connection): attribute = getattr(self, name, None) if isinstance(attribute, DeclarativeType): return attribute.start(name=name, attrs=attrs, connection=connection) elif attrs.getLength(): setattr(self, name, ComplexType(attrs.copy())) else: return None @strip_namespace def endElement(self, name, value, connection): attribute = getattr(self, name, None) if name == self._name: self._declared('teardown') elif isinstance(attribute, DeclarativeType): attribute.end(name=name, value=value, connection=connection) elif isinstance(attribute, ComplexType): setattr(attribute, attribute._value, value) else: setattr(self, name, value) class Response(ResponseElement): ResponseMetadata = Element() @strip_namespace def startElement(self, name, attrs, connection): if name == self._name: self.update(attrs) else: return super(Response, self).startElement(name, attrs, connection) @property def _result(self): return getattr(self, self._action + 'Result', None) @property def _action(self): return (self._name or self.__class__.__name__)[:-len('Response')] class ResponseResultList(Response): _ResultClass = ResponseElement def __init__(self, *args, **kw): setattr(self, self._action + 'Result', ElementList(self._ResultClass)) super(ResponseResultList, self).__init__(*args, **kw) class FeedSubmissionInfo(ResponseElement): pass class SubmitFeedResult(ResponseElement): FeedSubmissionInfo = Element(FeedSubmissionInfo) class GetFeedSubmissionListResult(ResponseElement): FeedSubmissionInfo = ElementList(FeedSubmissionInfo) class GetFeedSubmissionCountResult(ResponseElement): pass class CancelFeedSubmissionsResult(GetFeedSubmissionListResult): pass class GetServiceStatusResult(ResponseElement): Messages = Element(Messages=ElementList()) class ReportRequestInfo(ResponseElement): pass class RequestReportResult(ResponseElement): ReportRequestInfo = Element() class GetReportRequestListResult(RequestReportResult): ReportRequestInfo = ElementList() class CancelReportRequestsResult(RequestReportResult): pass class GetReportListResult(ResponseElement): ReportInfo = ElementList() class ManageReportScheduleResult(ResponseElement): ReportSchedule = Element() class GetReportScheduleListResult(ManageReportScheduleResult): pass class UpdateReportAcknowledgementsResult(GetReportListResult): pass class CreateInboundShipmentPlanResult(ResponseElement): InboundShipmentPlans = MemberList(ShipToAddress=Element(), Items=MemberList()) class ListInboundShipmentsResult(ResponseElement): ShipmentData = MemberList(ShipFromAddress=Element()) class ListInboundShipmentItemsResult(ResponseElement): ItemData = MemberList() class ListInventorySupplyResult(ResponseElement): InventorySupplyList = MemberList( EarliestAvailability=Element(), SupplyDetail=MemberList( EarliestAvailableToPick=Element(), LatestAvailableToPick=Element(), ) ) class ComplexAmount(ResponseElement): _amount = 'Value' def __repr__(self): return '{0} {1}'.format(self.CurrencyCode, getattr(self, self._amount)) def __float__(self): return float(getattr(self, self._amount)) def __str__(self): return str(getattr(self, self._amount)) @strip_namespace def startElement(self, name, attrs, connection): if name not in ('CurrencyCode', self._amount): message = 'Unrecognized tag {0} in ComplexAmount'.format(name) raise AssertionError(message) return super(ComplexAmount, self).startElement(name, attrs, connection) @strip_namespace def endElement(self, name, value, connection): if name == self._amount: value = Decimal(value) super(ComplexAmount, self).endElement(name, value, connection) class ComplexMoney(ComplexAmount): _amount = 'Amount' class ComplexWeight(ResponseElement): def __repr__(self): return '{0} {1}'.format(self.Value, self.Unit) def __float__(self): return float(self.Value) def __str__(self): return str(self.Value) @strip_namespace def startElement(self, name, attrs, connection): if name not in ('Unit', 'Value'): message = 'Unrecognized tag {0} in ComplexWeight'.format(name) raise AssertionError(message) return super(ComplexWeight, self).startElement(name, attrs, connection) @strip_namespace def endElement(self, name, value, connection): if name == 'Value': value = Decimal(value) super(ComplexWeight, self).endElement(name, value, connection) class Dimension(ComplexType): _value = 'Value' class ComplexDimensions(ResponseElement): _dimensions = ('Height', 'Length', 'Width', 'Weight') def __repr__(self): values = [getattr(self, key, None) for key in self._dimensions] values = filter(None, values) return 'x'.join(map('{0.Value:0.2f}{0[Units]}'.format, values)) @strip_namespace def startElement(self, name, attrs, connection): if name not in self._dimensions: message = 'Unrecognized tag {0} in ComplexDimensions'.format(name) raise AssertionError(message) setattr(self, name, Dimension(attrs.copy())) @strip_namespace def endElement(self, name, value, connection): if name in self._dimensions: value = Decimal(value or '0') ResponseElement.endElement(self, name, value, connection) class FulfillmentPreviewItem(ResponseElement): EstimatedShippingWeight = Element(ComplexWeight) class FulfillmentPreview(ResponseElement): EstimatedShippingWeight = Element(ComplexWeight) EstimatedFees = MemberList(Amount=Element(ComplexAmount)) UnfulfillablePreviewItems = MemberList(FulfillmentPreviewItem) FulfillmentPreviewShipments = MemberList( FulfillmentPreviewItems=MemberList(FulfillmentPreviewItem), ) class GetFulfillmentPreviewResult(ResponseElement): FulfillmentPreviews = MemberList(FulfillmentPreview) class FulfillmentOrder(ResponseElement): DestinationAddress = Element() NotificationEmailList = MemberList(SimpleList) class GetFulfillmentOrderResult(ResponseElement): FulfillmentOrder = Element(FulfillmentOrder) FulfillmentShipment = MemberList( FulfillmentShipmentItem=MemberList(), FulfillmentShipmentPackage=MemberList(), ) FulfillmentOrderItem = MemberList() class ListAllFulfillmentOrdersResult(ResponseElement): FulfillmentOrders = MemberList(FulfillmentOrder) class GetPackageTrackingDetailsResult(ResponseElement): ShipToAddress = Element() TrackingEvents = MemberList(EventAddress=Element()) class Image(ResponseElement): pass class AttributeSet(ResponseElement): ItemDimensions = Element(ComplexDimensions) ListPrice = Element(ComplexMoney) PackageDimensions = Element(ComplexDimensions) SmallImage = Element(Image) class ItemAttributes(AttributeSet): Languages = Element(Language=ElementList()) def __init__(self, *args, **kw): names = ('Actor', 'Artist', 'Author', 'Creator', 'Director', 'Feature', 'Format', 'GemType', 'MaterialType', 'MediaType', 'OperatingSystem', 'Platform') for name in names: setattr(self, name, SimpleList()) super(ItemAttributes, self).__init__(*args, **kw) class VariationRelationship(ResponseElement): Identifiers = Element(MarketplaceASIN=Element(), SKUIdentifier=Element()) GemType = SimpleList() MaterialType = SimpleList() OperatingSystem = SimpleList() class Price(ResponseElement): LandedPrice = Element(ComplexMoney) ListingPrice = Element(ComplexMoney) Shipping = Element(ComplexMoney) class CompetitivePrice(ResponseElement): Price = Element(Price) class CompetitivePriceList(ResponseElement): CompetitivePrice = ElementList(CompetitivePrice) class CompetitivePricing(ResponseElement): CompetitivePrices = Element(CompetitivePriceList) NumberOfOfferListings = SimpleList() TradeInValue = Element(ComplexMoney) class SalesRank(ResponseElement): pass class LowestOfferListing(ResponseElement): Qualifiers = Element(ShippingTime=Element()) Price = Element(Price) class Offer(ResponseElement): BuyingPrice = Element(Price) RegularPrice = Element(ComplexMoney) class Product(ResponseElement): _namespace = 'ns2' Identifiers = Element(MarketplaceASIN=Element(), SKUIdentifier=Element()) AttributeSets = Element( ItemAttributes=ElementList(ItemAttributes), ) Relationships = Element( VariationParent=ElementList(VariationRelationship), ) CompetitivePricing = ElementList(CompetitivePricing) SalesRankings = Element( SalesRank=ElementList(SalesRank), ) LowestOfferListings = Element( LowestOfferListing=ElementList(LowestOfferListing), ) Offers = Element( Offer=ElementList(Offer), ) class ListMatchingProductsResult(ResponseElement): Products = Element(Product=ElementList(Product)) class ProductsBulkOperationResult(ResponseElement): Product = Element(Product) Error = Element() class ProductsBulkOperationResponse(ResponseResultList): _ResultClass = ProductsBulkOperationResult class GetMatchingProductResponse(ProductsBulkOperationResponse): pass class GetMatchingProductForIdResult(ListMatchingProductsResult): pass class GetMatchingProductForIdResponse(ResponseResultList): _ResultClass = GetMatchingProductForIdResult class GetCompetitivePricingForSKUResponse(ProductsBulkOperationResponse): pass class GetCompetitivePricingForASINResponse(ProductsBulkOperationResponse): pass class GetLowestOfferListingsForSKUResponse(ProductsBulkOperationResponse): pass class GetLowestOfferListingsForASINResponse(ProductsBulkOperationResponse): pass class GetMyPriceForSKUResponse(ProductsBulkOperationResponse): pass class GetMyPriceForASINResponse(ProductsBulkOperationResponse): pass class ProductCategory(ResponseElement): def __init__(self, *args, **kw): setattr(self, 'Parent', Element(ProductCategory)) super(ProductCategory, self).__init__(*args, **kw) class GetProductCategoriesResult(ResponseElement): Self = ElementList(ProductCategory) class GetProductCategoriesForSKUResult(GetProductCategoriesResult): pass class GetProductCategoriesForASINResult(GetProductCategoriesResult): pass class Order(ResponseElement): OrderTotal = Element(ComplexMoney) ShippingAddress = Element() PaymentExecutionDetail = Element( PaymentExecutionDetailItem=ElementList( PaymentExecutionDetailItem=Element( Payment=Element(ComplexMoney) ) ) ) class ListOrdersResult(ResponseElement): Orders = Element(Order=ElementList(Order)) class GetOrderResult(ListOrdersResult): pass class OrderItem(ResponseElement): ItemPrice = Element(ComplexMoney) ShippingPrice = Element(ComplexMoney) GiftWrapPrice = Element(ComplexMoney) ItemTax = Element(ComplexMoney) ShippingTax = Element(ComplexMoney) GiftWrapTax = Element(ComplexMoney) ShippingDiscount = Element(ComplexMoney) PromotionDiscount = Element(ComplexMoney) PromotionIds = SimpleList() CODFee = Element(ComplexMoney) CODFeeDiscount = Element(ComplexMoney) class ListOrderItemsResult(ResponseElement): OrderItems = Element(OrderItem=ElementList(OrderItem)) class ListMarketplaceParticipationsResult(ResponseElement): ListParticipations = Element(Participation=ElementList()) ListMarketplaces = Element(Marketplace=ElementList()) class ListRecommendationsResult(ResponseElement): ListingQualityRecommendations = MemberList(ItemIdentifier=Element()) class Customer(ResponseElement): PrimaryContactInfo = Element() ShippingAddressList = Element(ShippingAddress=ElementList()) AssociatedMarketplaces = Element(MarketplaceDomain=ElementList()) class ListCustomersResult(ResponseElement): CustomerList = Element(Customer=ElementList(Customer)) class GetCustomersForCustomerIdResult(ListCustomersResult): pass class CartItem(ResponseElement): CurrentPrice = Element(ComplexMoney) SalePrice = Element(ComplexMoney) class Cart(ResponseElement): ActiveCartItemList = Element(CartItem=ElementList(CartItem)) SavedCartItemList = Element(CartItem=ElementList(CartItem)) class ListCartsResult(ResponseElement): CartList = Element(Cart=ElementList(Cart)) class GetCartsResult(ListCartsResult): pass class Destination(ResponseElement): AttributeList = MemberList() class ListRegisteredDestinationsResult(ResponseElement): DestinationList = MemberList(Destination) class Subscription(ResponseElement): Destination = Element(Destination) class GetSubscriptionResult(ResponseElement): Subscription = Element(Subscription) class ListSubscriptionsResult(ResponseElement): SubscriptionList = MemberList(Subscription) class OrderReferenceDetails(ResponseElement): Buyer = Element() OrderTotal = Element(ComplexMoney) Destination = Element(PhysicalDestination=Element()) SellerOrderAttributes = Element() OrderReferenceStatus = Element() Constraints = ElementList() class SetOrderReferenceDetailsResult(ResponseElement): OrderReferenceDetails = Element(OrderReferenceDetails) class GetOrderReferenceDetailsResult(SetOrderReferenceDetailsResult): pass class AuthorizationDetails(ResponseElement): AuthorizationAmount = Element(ComplexMoney) CapturedAmount = Element(ComplexMoney) AuthorizationFee = Element(ComplexMoney) AuthorizationStatus = Element() class AuthorizeResult(ResponseElement): AuthorizationDetails = Element(AuthorizationDetails) class GetAuthorizationDetailsResult(AuthorizeResult): pass class CaptureDetails(ResponseElement): CaptureAmount = Element(ComplexMoney) RefundedAmount = Element(ComplexMoney) CaptureFee = Element(ComplexMoney) CaptureStatus = Element() class CaptureResult(ResponseElement): CaptureDetails = Element(CaptureDetails) class GetCaptureDetailsResult(CaptureResult): pass class RefundDetails(ResponseElement): RefundAmount = Element(ComplexMoney) FeeRefunded = Element(ComplexMoney) RefundStatus = Element() class RefundResult(ResponseElement): RefundDetails = Element(RefundDetails) class GetRefundDetails(RefundResult): pass
mit
weaver-viii/subuser
logic/subuserlib/resolve.py
2
5115
#!/usr/bin/env python # This file should be compatible with both Python 2 and 3. # If it is not, please file a bug report. """ This module is used to parse the image source identifiers used to identify image sources during instalation. For more information see the image-source-identifiers section of the subuser standard. """ #external imports #import ... #internal imports from subuserlib.classes.repository import Repository def resolveImageSource(user,imageSourcePath,contextRepository=None,allowRefferingToRepositoriesByName=True): """ From a image source identifier path return a ImageSource object. >>> from subuserlib.classes.user import User >>> user = User() Usually, the syntax is image-name@repository-name. >>> print(resolveImageSource(user,"foo@default").getName()) foo If there is no @, then we assume that the repository is the contextRepository. The default contextRepository is the "default" repository. >>> print(resolveImageSource(user,"foo").getName()) foo If the repository identifier is a URI and a repository with the same URI already exists, then the URI is resolved to the name of the existing repository. Otherwise, a temporary repository is created. >>> print(resolveImageSource(user,"bar@file:///home/travis/remote-test-repo").getName()) Adding new temporary repository file:///home/travis/remote-test-repo bar If the repository identifier is a path to a folder on the local machine and a repository pointing to this folder already exists, then the identifier is resolved to the name of the existing repository. Otherwise, a temporary repository is created. >>> print(resolveImageSource(user,"bar@/home/travis/remote-test-repo").getName()) Adding new temporary repository /home/travis/remote-test-repo bar Throws an Key error: - If the repository does not exist - If the image is not in the repository >>> try: ... resolveImageSource(user,"non-existant@default") ... except KeyError: ... print("KeyError") KeyError """ if not contextRepository: contextRepository = user.getRegistry().getRepositories()["default"] splitImageIdentifier = imageSourcePath.split("@",1) imageName = splitImageIdentifier[0] # For identifiers of the format: # "foo" if len(splitImageIdentifier)==1: repository = contextRepository # "foo@bar" elif not ":" in splitImageIdentifier[1] and not splitImageIdentifier[1].startswith("/"): if allowRefferingToRepositoriesByName or splitImageIdentifier[1] == "default": repository = user.getRegistry().getRepositories()[splitImageIdentifier[1]] else: raise Exception("Error when resolving ImageSource "+imageSourcePath+". Refering to repositories by name is forbidden in this context.") # "foo@https://github.com/subuser-security/some-repo.git" else: repository = getRepositoryFromURIOrPath(user,splitImageIdentifier[1]) try: return repository[imageName] except KeyError: raise KeyError(imageName + " could not be found in the repository. The following images exist in the repository: \"" + "\" \"".join(repository.keys())+"\"") def lookupRepositoryByURI(user,uri): """ If a repository with this URI exists, return that repository. Otherwise, return None. """ for _,repository in user.getRegistry().getRepositories().items(): if uri == repository.getURI(): return repository return None def lookupRepositoryByPath(user,path): """ If a repository with this path exists, return that repository. Otherwise, return None. """ for _,repository in user.getRegistry().getRepositories().items(): if repository.isLocal() and path == repository.getRepoPath(): return repository return None def lookupRepositoryByURIOrPath(user,uriOrPath): if uriOrPath.startswith("/"): return lookupRepositoryByPath(user,uriOrPath) else: return lookupRepositoryByURI(user,uriOrPath) def getRepositoryFromURI(user,uri): """ Either return the repository who's URI is equal to the given URI or return a new temporary repository with that URI. """ #First check if a repository with this URI already exists repository = lookupRepositoryByURI(user,uri) if repository: return repository # If it doesn't, create a new repo and return it. newTempRepo = Repository(user=user,name=user.getRegistry().getRepositories().getNewUniqueTempRepoId(),gitOriginURI=uri,gitCommitHash="master",temporary=True) user.getRegistry().getRepositories().addRepository(newTempRepo) return newTempRepo def getRepositoryFromPath(user,path): repository = lookupRepositoryByPath(user,path) if repository: return repository else: # If it doesn't, create a new repo and return it. newTempRepo = Repository(user=user,name=user.getRegistry().getRepositories().getNewUniqueTempRepoId(),temporary=True,sourceDir=path) user.getRegistry().getRepositories().addRepository(newTempRepo) return newTempRepo def getRepositoryFromURIOrPath(user,uriOrPath): if uriOrPath.startswith("/"): return getRepositoryFromPath(user,uriOrPath) else: return getRepositoryFromURI(user,uriOrPath)
lgpl-3.0
Code4SA/mma-dexter
dexter/processing/extractors/calais.py
1
5007
import requests import json from .base import BaseExtractor from ...models import DocumentEntity, Entity, Utterance, DocumentTaxonomy import logging log = logging.getLogger(__name__) class CalaisExtractor(BaseExtractor): """ Use the OpenCalais API to extract entities and other useful goodies from a document. """ API_KEY = None def __init__(self): pass def extract(self, doc): if doc.text: log.info("Extracting things for %s" % doc) calais = self.fetch_data(doc) log.debug("Raw calais extractions: %s" % calais) self.extract_entities(doc, calais) self.extract_utterances(doc, calais) self.extract_topics(doc, calais) def extract_entities(self, doc, calais): entities_added = 0 for group, group_ents in calais.get('entities', {}).iteritems(): group = self.normalise_name(group) for ent in group_ents.itervalues(): if 'name' not in ent or len(ent['name']) < 2: continue e = Entity.get_or_create(group, ent['name']) de = DocumentEntity() de.entity = e de.relevance = float(ent['relevance']) de.count = len(ent['instances']) for occurrence in ent['instances'][:100]: de.add_offset((occurrence['offset'], occurrence['length'])) if doc.add_entity(de): entities_added += 1 log.info("Added %d entities for %s" % (entities_added, doc)) def extract_utterances(self, doc, calais): utterances_added = 0 for quote in calais.get('relations', {}).get('Quotation', {}).itervalues(): u = Utterance() u.quote = quote['quotation'].strip() if quote.get('instances', []): u.offset = quote['instances'][0]['offset'] u.length = quote['instances'][0]['length'] # uttering entity u.entity = Entity.get_or_create( self.normalise_name(quote['speaker']['_type']), quote['speaker']['name']) if doc.add_utterance(u): utterances_added += 1 log.info("Added %d utterances for %s" % (utterances_added, doc)) def extract_topics(self, doc, calais): added = 0 for topicpairs in calais.get('topics', {}).itervalues(): for topic in topicpairs.itervalues(): dt = DocumentTaxonomy() dt.document = doc dt.label = topic['name'].replace('_', ' ') dt.score = topic['score'] added += 1 log.info("Added %d topics for %s" % (added, doc)) def fetch_data(self, doc): if not doc.raw_calais: # fetch it # NOTE: set the ENV variable CALAIS_API_KEY before running the process if not self.API_KEY: raise ValueError('%s.%s.API_KEY must be defined.' % (self.__module__, self.__class__.__name__)) res = requests.post( 'https://api-eit.refinitiv.com/permid/calais', doc.text.encode('utf-8'), headers={ 'x-ag-access-token': self.API_KEY, 'Content-Type': 'text/raw', 'outputFormat': 'application/json', }, verify=False) if res.status_code != 200: log.error(res.text) res.raise_for_status() res = res.json() doc.raw_calais = json.dumps(res) else: log.info("Using cached Calais data") res = json.loads(doc.raw_calais) # make the JSON decent and usable res = self.normalise(res) return res.get('extractions', {}) def normalise(self, js): """ Change the JSON OpenCalais gives back into a nicer layout, keying extractions by their type. """ # resolve references for key, val in js.iteritems(): if isinstance(val, dict): for attr, attr_val in val.iteritems(): if isinstance(attr_val, basestring): if attr_val in js: val[attr] = js[attr_val] n = {} things = {} n['extractions'] = things # produces: # # extractions: # entities: # City: [ ... ] # Person: [ ... ] # relations: # Quotation: [ ... ] for key, val in js.iteritems(): grp = val.get('_typeGroup') if grp: if grp not in things: things[grp] = {} grp = things[grp] typ = val.get('_type') if typ not in grp: grp[typ] = {} grp[typ][key] = val else: n[key] = val return n
apache-2.0
Sing-Li/go-buildpack
builds/runtimes/python-2.7.6/lib/python2.7/mimetypes.py
11
20981
"""Guess the MIME type of a file. This module defines two useful functions: guess_type(url, strict=1) -- guess the MIME type and encoding of a URL. guess_extension(type, strict=1) -- guess the extension for a given MIME type. It also contains the following, for tuning the behavior: Data: knownfiles -- list of files to parse inited -- flag set when init() has been called suffix_map -- dictionary mapping suffixes to suffixes encodings_map -- dictionary mapping suffixes to encodings types_map -- dictionary mapping suffixes to types Functions: init([files]) -- parse a list of files, default knownfiles (on Windows, the default values are taken from the registry) read_mime_types(file) -- parse one file, return a dictionary or None """ import os import sys import posixpath import urllib try: import _winreg except ImportError: _winreg = None __all__ = [ "guess_type","guess_extension","guess_all_extensions", "add_type","read_mime_types","init" ] knownfiles = [ "/etc/mime.types", "/etc/httpd/mime.types", # Mac OS X "/etc/httpd/conf/mime.types", # Apache "/etc/apache/mime.types", # Apache 1 "/etc/apache2/mime.types", # Apache 2 "/usr/local/etc/httpd/conf/mime.types", "/usr/local/lib/netscape/mime.types", "/usr/local/etc/httpd/conf/mime.types", # Apache 1.2 "/usr/local/etc/mime.types", # Apache 1.3 ] inited = False _db = None class MimeTypes: """MIME-types datastore. This datastore can handle information from mime.types-style files and supports basic determination of MIME type from a filename or URL, and can guess a reasonable extension given a MIME type. """ def __init__(self, filenames=(), strict=True): if not inited: init() self.encodings_map = encodings_map.copy() self.suffix_map = suffix_map.copy() self.types_map = ({}, {}) # dict for (non-strict, strict) self.types_map_inv = ({}, {}) for (ext, type) in types_map.items(): self.add_type(type, ext, True) for (ext, type) in common_types.items(): self.add_type(type, ext, False) for name in filenames: self.read(name, strict) def add_type(self, type, ext, strict=True): """Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ self.types_map[strict][ext] = type exts = self.types_map_inv[strict].setdefault(type, []) if ext not in exts: exts.append(ext) def guess_type(self, url, strict=True): """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to '.tar.gz'. (This is table-driven too, using the dictionary suffix_map.) Optional `strict' argument when False adds a bunch of commonly found, but non-standard types. """ scheme, url = urllib.splittype(url) if scheme == 'data': # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value # type/subtype defaults to "text/plain" comma = url.find(',') if comma < 0: # bad data URL return None, None semi = url.find(';', 0, comma) if semi >= 0: type = url[:semi] else: type = url[:comma] if '=' in type or '/' not in type: type = 'text/plain' return type, None # never compressed, so encoding is None base, ext = posixpath.splitext(url) while ext in self.suffix_map: base, ext = posixpath.splitext(base + self.suffix_map[ext]) if ext in self.encodings_map: encoding = self.encodings_map[ext] base, ext = posixpath.splitext(base) else: encoding = None types_map = self.types_map[True] if ext in types_map: return types_map[ext], encoding elif ext.lower() in types_map: return types_map[ext.lower()], encoding elif strict: return None, encoding types_map = self.types_map[False] if ext in types_map: return types_map[ext], encoding elif ext.lower() in types_map: return types_map[ext.lower()], encoding else: return None, encoding def guess_all_extensions(self, type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ type = type.lower() extensions = self.types_map_inv[True].get(type, []) if not strict: for ext in self.types_map_inv[False].get(type, []): if ext not in extensions: extensions.append(ext) return extensions def guess_extension(self, type, strict=True): """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ extensions = self.guess_all_extensions(type, strict) if not extensions: return None return extensions[0] def read(self, filename, strict=True): """ Read a single mime.types-format file, specified by pathname. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ with open(filename) as fp: self.readfp(fp, strict) def readfp(self, fp, strict=True): """ Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ while 1: line = fp.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: self.add_type(type, '.' + suff, strict) def read_windows_registry(self, strict=True): """ Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ # Windows only if not _winreg: return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break try: ctype = ctype.encode(default_encoding) # omit in 3.x! except UnicodeEncodeError: pass else: yield ctype i += 1 default_encoding = sys.getdefaultencoding() with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr: for subkeyname in enum_types(hkcr): try: with _winreg.OpenKey(hkcr, subkeyname) as subkey: # Only check file extensions if not subkeyname.startswith("."): continue # raises EnvironmentError if no 'Content Type' value mimetype, datatype = _winreg.QueryValueEx( subkey, 'Content Type') if datatype != _winreg.REG_SZ: continue try: mimetype = mimetype.encode(default_encoding) subkeyname = subkeyname.encode(default_encoding) except UnicodeEncodeError: continue self.add_type(mimetype, subkeyname, strict) except EnvironmentError: continue def guess_type(url, strict=True): """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffix_map). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_type(url, strict) def guess_all_extensions(type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_all_extensions(type, strict) def guess_extension(type, strict=True): """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_extension(type, strict) def add_type(type, ext, strict=True): """Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ if _db is None: init() return _db.add_type(type, ext, strict) def init(files=None): global suffix_map, types_map, encodings_map, common_types global inited, _db inited = True # so that MimeTypes.__init__() doesn't call us again db = MimeTypes() if files is None: if _winreg: db.read_windows_registry() files = knownfiles for file in files: if os.path.isfile(file): db.read(file) encodings_map = db.encodings_map suffix_map = db.suffix_map types_map = db.types_map[True] common_types = db.types_map[False] # Make the DB a global variable now that it is fully initialized _db = db def read_mime_types(file): try: f = open(file) except IOError: return None db = MimeTypes() db.readfp(f, True) return db.types_map[True] def _default_mime_types(): global suffix_map global encodings_map global types_map global common_types suffix_map = { '.tgz': '.tar.gz', '.taz': '.tar.gz', '.tz': '.tar.gz', '.tbz2': '.tar.bz2', '.txz': '.tar.xz', } encodings_map = { '.gz': 'gzip', '.Z': 'compress', '.bz2': 'bzip2', '.xz': 'xz', } # Before adding new types, make sure they are either registered with IANA, # at http://www.isi.edu/in-notes/iana/assignments/media-types # or extensions, i.e. using the x- prefix # If you add to these, please keep them sorted! types_map = { '.a' : 'application/octet-stream', '.ai' : 'application/postscript', '.aif' : 'audio/x-aiff', '.aifc' : 'audio/x-aiff', '.aiff' : 'audio/x-aiff', '.au' : 'audio/basic', '.avi' : 'video/x-msvideo', '.bat' : 'text/plain', '.bcpio' : 'application/x-bcpio', '.bin' : 'application/octet-stream', '.bmp' : 'image/x-ms-bmp', '.c' : 'text/plain', # Duplicates :( '.cdf' : 'application/x-cdf', '.cdf' : 'application/x-netcdf', '.cpio' : 'application/x-cpio', '.csh' : 'application/x-csh', '.css' : 'text/css', '.dll' : 'application/octet-stream', '.doc' : 'application/msword', '.dot' : 'application/msword', '.dvi' : 'application/x-dvi', '.eml' : 'message/rfc822', '.eps' : 'application/postscript', '.etx' : 'text/x-setext', '.exe' : 'application/octet-stream', '.gif' : 'image/gif', '.gtar' : 'application/x-gtar', '.h' : 'text/plain', '.hdf' : 'application/x-hdf', '.htm' : 'text/html', '.html' : 'text/html', '.ico' : 'image/vnd.microsoft.icon', '.ief' : 'image/ief', '.jpe' : 'image/jpeg', '.jpeg' : 'image/jpeg', '.jpg' : 'image/jpeg', '.js' : 'application/javascript', '.ksh' : 'text/plain', '.latex' : 'application/x-latex', '.m1v' : 'video/mpeg', '.man' : 'application/x-troff-man', '.me' : 'application/x-troff-me', '.mht' : 'message/rfc822', '.mhtml' : 'message/rfc822', '.mif' : 'application/x-mif', '.mov' : 'video/quicktime', '.movie' : 'video/x-sgi-movie', '.mp2' : 'audio/mpeg', '.mp3' : 'audio/mpeg', '.mp4' : 'video/mp4', '.mpa' : 'video/mpeg', '.mpe' : 'video/mpeg', '.mpeg' : 'video/mpeg', '.mpg' : 'video/mpeg', '.ms' : 'application/x-troff-ms', '.nc' : 'application/x-netcdf', '.nws' : 'message/rfc822', '.o' : 'application/octet-stream', '.obj' : 'application/octet-stream', '.oda' : 'application/oda', '.p12' : 'application/x-pkcs12', '.p7c' : 'application/pkcs7-mime', '.pbm' : 'image/x-portable-bitmap', '.pdf' : 'application/pdf', '.pfx' : 'application/x-pkcs12', '.pgm' : 'image/x-portable-graymap', '.pl' : 'text/plain', '.png' : 'image/png', '.pnm' : 'image/x-portable-anymap', '.pot' : 'application/vnd.ms-powerpoint', '.ppa' : 'application/vnd.ms-powerpoint', '.ppm' : 'image/x-portable-pixmap', '.pps' : 'application/vnd.ms-powerpoint', '.ppt' : 'application/vnd.ms-powerpoint', '.ps' : 'application/postscript', '.pwz' : 'application/vnd.ms-powerpoint', '.py' : 'text/x-python', '.pyc' : 'application/x-python-code', '.pyo' : 'application/x-python-code', '.qt' : 'video/quicktime', '.ra' : 'audio/x-pn-realaudio', '.ram' : 'application/x-pn-realaudio', '.ras' : 'image/x-cmu-raster', '.rdf' : 'application/xml', '.rgb' : 'image/x-rgb', '.roff' : 'application/x-troff', '.rtx' : 'text/richtext', '.sgm' : 'text/x-sgml', '.sgml' : 'text/x-sgml', '.sh' : 'application/x-sh', '.shar' : 'application/x-shar', '.snd' : 'audio/basic', '.so' : 'application/octet-stream', '.src' : 'application/x-wais-source', '.sv4cpio': 'application/x-sv4cpio', '.sv4crc' : 'application/x-sv4crc', '.swf' : 'application/x-shockwave-flash', '.t' : 'application/x-troff', '.tar' : 'application/x-tar', '.tcl' : 'application/x-tcl', '.tex' : 'application/x-tex', '.texi' : 'application/x-texinfo', '.texinfo': 'application/x-texinfo', '.tif' : 'image/tiff', '.tiff' : 'image/tiff', '.tr' : 'application/x-troff', '.tsv' : 'text/tab-separated-values', '.txt' : 'text/plain', '.ustar' : 'application/x-ustar', '.vcf' : 'text/x-vcard', '.wav' : 'audio/x-wav', '.wiz' : 'application/msword', '.wsdl' : 'application/xml', '.xbm' : 'image/x-xbitmap', '.xlb' : 'application/vnd.ms-excel', # Duplicates :( '.xls' : 'application/excel', '.xls' : 'application/vnd.ms-excel', '.xml' : 'text/xml', '.xpdl' : 'application/xml', '.xpm' : 'image/x-xpixmap', '.xsl' : 'application/xml', '.xwd' : 'image/x-xwindowdump', '.zip' : 'application/zip', } # These are non-standard types, commonly found in the wild. They will # only match if strict=0 flag is given to the API methods. # Please sort these too common_types = { '.jpg' : 'image/jpg', '.mid' : 'audio/midi', '.midi': 'audio/midi', '.pct' : 'image/pict', '.pic' : 'image/pict', '.pict': 'image/pict', '.rtf' : 'application/rtf', '.xul' : 'text/xul' } _default_mime_types() if __name__ == '__main__': import getopt USAGE = """\ Usage: mimetypes.py [options] type Options: --help / -h -- print this message and exit --lenient / -l -- additionally search of some common, but non-standard types. --extension / -e -- guess extension instead of type More than one type argument may be given. """ def usage(code, msg=''): print USAGE if msg: print msg sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], 'hle', ['help', 'lenient', 'extension']) except getopt.error, msg: usage(1, msg) strict = 1 extension = 0 for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-l', '--lenient'): strict = 0 elif opt in ('-e', '--extension'): extension = 1 for gtype in args: if extension: guess = guess_extension(gtype, strict) if not guess: print "I don't know anything about type", gtype else: print guess else: guess, encoding = guess_type(gtype, strict) if not guess: print "I don't know anything about type", gtype else: print 'type:', guess, 'encoding:', encoding
mit
micmn/shogun
applications/asp/genomic.py
31
5794
# # 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. # # Written (W) 2006-2009 Soeren Sonnenburg # Written (W) 2006-2007 Mikio Braun # Copyright (C) 2007 Fraunhofer Institute FIRST and Max-Planck-Society import time from string import maketrans class ordered_dict(dict): """ Provide an ordered dictionary with chromosome identifiers. """ def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self._order = self.keys() def __setitem__(self, key, value): dict.__setitem__(self, key, value) if key in self._order: self._order.remove(key) self._order.append(key) def __delitem__(self, key): dict.__delitem__(self, key) self._order.remove(key) def ordered_items(self): return [(key,self[key]) for key in self._order] """ read a table browser ascii output file (http://genome.ucsc.edu/cgi-bin/hgTables) """ def read_table_browser(f): table=dict(); for l in f.readlines(): if not l.startswith('#'): (name,chrom,strand,txStart,txEnd,cdsStart,cdsEnd,exonCount,exonStarts,exonEnds,proteinID,alignID)=l.split('\t') exonStarts=[ int(i) for i in exonStarts.split(',')[:-1] ] exonEnds=[ int(i) for i in exonEnds.split(',')[:-1] ] table[name]={ 'chrom': chrom, 'strand': strand, 'txStart': int(txStart), 'txEnd': int(txEnd), 'cdsStart': int(cdsStart), 'cdsEnd': int(cdsEnd), 'exonCount': int(exonCount), 'exonStarts': exonStarts, 'exonEnds': exonEnds, 'proteinID': proteinID, 'alignID': alignID[:-1] } return table """ get promoter region """ def get_promoter_region(chromosome, strand, gene_start, gene_end, genome, length): if strand == '+': return load_genomic(chromosome, strand, gene_start, gene_start+length, genome, one_based=False) elif strand == '-': return load_genomic(chromosome, strand, gene_end, gene_end+length, genome, one_based=False) else: print 'unknown strand' return None """ reverse + complement a DNA sequence (only letters ACGT are translated!) FIXME won't work with all the rest like y... """ def reverse_complement(str): t=maketrans('acgtACGT','tgcaTGCA') return str[len(str)::-1].translate(t) """ works only with .fa files that contain a single entry """ def read_single_fasta(fname): str=file(fname).read() str=str[str.index('\n')+1:].replace('\n','') return str """ writes only single enty .fa files """ def write_single_fasta(fname, name, str, linelen=60): header= '>' + name + '\n' f=file(fname,'a') f.write(header) for i in xrange(0,len(str),linelen): f.write(str[i:i+linelen]+'\n') f.close() """ read fasta as dictionary """ def read_fasta(f): fasta=ordered_dict() fa="" key=None for s in f.readlines(): if s.startswith('>'): if fa and key: fasta[key]=fa key=s[1:-1] fasta[key]="" fa="" else: fa+=s[:-1] if fa and key: fasta[key]=fa return fasta def write_fasta(f, d, linelen=60): """ write dictionary fasta """ for k in sorted(d): f.write('>%s\n' % k); s = d[k] for i in xrange(0, len(s), linelen): f.write(s[i:i+linelen] + '\n') def write_gff_header(f, (source, version), (seqtype, seqname)): """ writes a gff version 2 file descrlist is a list of dictionaries, each of which contain these fields: <seqname> <source> <feature> <start> <end> <score> <strand> <frame> [attributes] [comments] """ f.write('##gff-version 2\n') f.write('##source-version %s %s\n' % (source, version) ) t=time.localtime() f.write("##date %d-%d-%d %d:%d:%d\n" % t[0:6]) f.write('##Type %s %s\n' % (seqtype, seqname) ) def write_gff_line(f, descr): d=descr f.write('%s\t%s\t%s\t%d\t%d\t%f\t%s\t%d' % (d['seqname'], d['source'], d['feature'], d['start'], d['end'], d['score'], d['strand'], d['frame'])) if d.has_key('attributes'): f.write('\t' + d['attributes']) if d.has_key('comments'): f.write('\t' + d['comments']) f.write('\n') def write_spf_header(f, (source, version), (seqtype, seqname)): """ writes a gff version 2 file descrlist is a list of dictionaries, each of which contain these fields: <seqname> <source> <feature> <start> <end> <score> <strand> <frame> [attributes] [comments] """ f.write('##spf-version 1\n') f.write('##source-version %s %s\n' % (source, version) ) t=time.localtime() f.write("##date %d-%d-%d %d:%d:%d\n" % t[0:6]) f.write('##Type %s %s\n' % (seqtype, seqname) ) def write_spf_line(f, descr): d=descr f.write('%s\t%s\t%s\t%d\t%s\t%f' % (d['seqname'], d['source'], d['feature'], d['position'], d['strand'], d['score'])) if d.has_key('attributes'): f.write('\t' + d['attributes']) if d.has_key('comments'): f.write('\t' + d['comments']) f.write('\n') def write_gff(f, (source, version), (seqtype, seqname), descrlist, skipheader=False): """ writes a gff version 2 file descrlist is a list of dictionaries, each of which contain these fields: <seqname> <source> <feature> <start> <end> <score> <strand> <frame> [attributes] [comments] """ if not skipheader: f.write('##gff-version 2\n') f.write('##source-version %s %s\n' % (source, version) ) t=time.localtime() f.write("##date %d-%d-%d %d:%d:%d\n" % t[0:6]) f.write('##Type %s %s\n' % (seqtype, seqname) ) for d in descrlist: f.write('%s\t%s\t%s\t%d\t%d\t%f\t%s\t%d' % (d['seqname'], d['source'], d['feature'], d['start'], d['end'], d['score'], d['strand'], d['frame'])) if d.has_key('attributes'): f.write('\t' + d['attributes']) if d.has_key('comments'): f.write('\t' + d['comments']) f.write('\n')
gpl-3.0
wy65701436/harbor
tests/apitests/python/test_verify_metrics_enabled.py
2
2029
# coding: utf-8 from __future__ import absolute_import import unittest import requests import testutils class TestMetricsExist(unittest.TestCase): golang_basic_metrics = ["go_gc_duration_seconds", "go_goroutines", "go_info", "go_memstats_alloc_bytes"] metrics = { 'core': golang_basic_metrics + [ "harbor_core_http_request_total", "harbor_core_http_request_duration_seconds", "harbor_core_http_inflight_requests"], 'registry': golang_basic_metrics + ["registry_http_in_flight_requests"], 'exporter': golang_basic_metrics + [ "artifact_pulled", "harbor_project_artifact_total", "harbor_project_member_total", "harbor_project_quota_byte", "harbor_project_repo_total", "harbor_project_total", "project_quota_usage_byte", "harbor_task_concurrency", "harbor_task_queue_latency", "harbor_task_queue_size", "harbor_task_scheduled_total"], 'jobservice': golang_basic_metrics + [ "harbor_jobservice_info", "harbor_jobservice_task_process_time_seconds", "harbor_jobservice_task_total"] } def get_metrics(self): metrics_url = testutils.METRIC_URL+'/metrics' exporter_res = requests.get(metrics_url) core_res = requests.get(metrics_url, params={'comp': 'core'}) reg_res = requests.get(metrics_url, params={'comp': 'registry'}) js_res = requests.get(metrics_url, params={'comp': 'jobservice'}) return [('exporter', exporter_res.text), ('core', core_res.text), ('registry', reg_res.text), ('jobservice', js_res.text)] def testMetricsExist(self): for k, metric_text in self.get_metrics(): for metric_name in self.metrics[k]: print("Metric {} should exist in {} ".format(metric_name, k)) self.assertTrue(metric_name in metric_text) if __name__ == '__main__': unittest.main()
apache-2.0
eaplatanios/tensorflow
tensorflow/python/kernel_tests/array_ops_test.py
2
48609
# Copyright 2015 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 array_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import unittest import numpy as np from tensorflow.python.client import session 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 errors_impl from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import test_ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import gradients_impl 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 as test_lib class BatchMatrixTransposeTest(test_util.TensorFlowTestCase): def testNonBatchMatrix(self): matrix = [[1, 2, 3], [4, 5, 6]] # Shape (2, 3) expected_transposed = [[1, 4], [2, 5], [3, 6]] # Shape (3, 2) with self.test_session(): transposed = array_ops.matrix_transpose(matrix) self.assertEqual((3, 2), transposed.get_shape()) self.assertAllEqual(expected_transposed, transposed.eval()) def testConjugate(self): m = [[1 + 1j, 2 + 2j, 3 + 3j], [4 + 4j, 5 + 5j, 6 + 6j]] expected_transposed = [[1 - 1j, 4 - 4j], [2 - 2j, 5 - 5j], [3 - 3j, 6 - 6j]] with self.test_session(): matrix = ops.convert_to_tensor(m) transposed = array_ops.matrix_transpose(matrix, conjugate=True) self.assertEqual((3, 2), transposed.get_shape()) self.assertAllEqual(expected_transposed, transposed.eval()) def testBatchMatrix(self): matrix_0 = [[1, 2, 3], [4, 5, 6]] matrix_0_t = [[1, 4], [2, 5], [3, 6]] matrix_1 = [[11, 22, 33], [44, 55, 66]] matrix_1_t = [[11, 44], [22, 55], [33, 66]] batch_matrix = [matrix_0, matrix_1] # Shape (2, 2, 3) expected_transposed = [matrix_0_t, matrix_1_t] # Shape (2, 3, 2) with self.test_session(): transposed = array_ops.matrix_transpose(batch_matrix) self.assertEqual((2, 3, 2), transposed.get_shape()) self.assertAllEqual(expected_transposed, transposed.eval()) def testNonBatchMatrixDynamicallyDefined(self): matrix = [[1, 2, 3], [4, 5, 6]] # Shape (2, 3) expected_transposed = [[1, 4], [2, 5], [3, 6]] # Shape (3, 2) with self.test_session(): matrix_ph = array_ops.placeholder(dtypes.int32) transposed = array_ops.matrix_transpose(matrix_ph) self.assertAllEqual( expected_transposed, transposed.eval(feed_dict={ matrix_ph: matrix })) def testBatchMatrixDynamicallyDefined(self): matrix_0 = [[1, 2, 3], [4, 5, 6]] matrix_0_t = [[1, 4], [2, 5], [3, 6]] matrix_1 = [[11, 22, 33], [44, 55, 66]] matrix_1_t = [[11, 44], [22, 55], [33, 66]] batch_matrix = [matrix_0, matrix_1] # Shape (2, 2, 3) expected_transposed = [matrix_0_t, matrix_1_t] # Shape (2, 3, 2) with self.test_session(): batch_matrix_ph = array_ops.placeholder(dtypes.int32) transposed = array_ops.matrix_transpose(batch_matrix_ph) self.assertAllEqual( expected_transposed, transposed.eval(feed_dict={ batch_matrix_ph: batch_matrix })) def testTensorWithStaticRankLessThanTwoRaisesBecauseNotAMatrix(self): vector = [1, 2, 3] with self.test_session(): with self.assertRaisesRegexp(ValueError, "should be a "): array_ops.matrix_transpose(vector) class BooleanMaskTest(test_util.TensorFlowTestCase): def setUp(self): self.rng = np.random.RandomState(42) def CheckVersusNumpy(self, ndims_mask, arr_shape, make_mask=None, axis=None): """Check equivalence between boolean_mask and numpy masking.""" if make_mask is None: make_mask = lambda shape: self.rng.randint(0, 2, size=shape).astype(bool) arr = np.random.rand(*arr_shape) mask = make_mask(arr_shape[:ndims_mask]) if axis is not None: mask = make_mask(arr_shape[axis:ndims_mask + axis]) if axis is None or axis == 0: masked_arr = arr[mask] elif axis == 1: masked_arr = arr[:, mask] elif axis == 2: masked_arr = arr[:, :, mask] with self.test_session(): masked_tensor = array_ops.boolean_mask(arr, mask, axis=axis) # Leading dimension size of masked_tensor is always unknown until runtime # since we don't how many elements will be kept. leading = 1 if axis is None else axis + 1 self.assertAllEqual(masked_tensor.get_shape()[leading:], masked_arr.shape[leading:]) self.assertAllClose(masked_arr, masked_tensor.eval()) def testMaskDim1ArrDim2Axis1(self): ndims_mask = 1 for arr_shape in [(1, 1), (2, 2), (2, 5)]: self.CheckVersusNumpy(ndims_mask, arr_shape, axis=1) def testMaskDim2ArrDim2Axis1(self): ndims_mask = 2 for arr_shape in [(1, 1), (2, 2), (2, 5)]: self.CheckVersusNumpy(ndims_mask, arr_shape, axis=1) def testMaskDim1ArrDim1(self): ndims_mask = 1 for arr_shape in [(1,), (2,), (3,), (10,)]: self.CheckVersusNumpy(ndims_mask, arr_shape) def testMaskDim1ArrDim2(self): ndims_mask = 1 for arr_shape in [(1, 1), (2, 2), (2, 5)]: self.CheckVersusNumpy(ndims_mask, arr_shape) def testMaskDim2ArrDim2(self): ndims_mask = 2 for arr_shape in [(1, 1), (2, 2), (2, 5)]: self.CheckVersusNumpy(ndims_mask, arr_shape) def testMaskDim2ArrDim3(self): ndims_mask = 2 for arr_shape in [(1, 1, 1), (1, 2, 2), (2, 2, 1)]: self.CheckVersusNumpy(ndims_mask, arr_shape) def testEmptyInput2D(self): mask = np.array([True, False]) arr = np.array([[], []]).astype(np.float32) numpy_result = arr[mask] tf_result = array_ops.boolean_mask(arr, mask) self.assertAllEqual(numpy_result.shape[1:], tf_result.get_shape()[1:]) with self.test_session(): self.assertAllClose(numpy_result, tf_result.eval()) def testEmptyInput1D(self): mask = np.array([]).astype(bool) arr = np.array([]).astype(np.float32) numpy_result = arr[mask] tf_result = array_ops.boolean_mask(arr, mask) self.assertAllEqual(numpy_result.shape[1:], tf_result.get_shape()[1:]) with self.test_session(): self.assertAllClose(numpy_result, tf_result.eval()) def testEmptyOutput(self): make_mask = lambda shape: np.zeros(shape, dtype=bool) for ndims_mask in range(1, 4): for ndims_arr in range(ndims_mask, ndims_mask + 3): for _ in range(3): arr_shape = np.random.randint(1, 5, size=ndims_arr) self.CheckVersusNumpy(ndims_mask, arr_shape, make_mask=make_mask) def testWorksWithDimensionsEqualToNoneDuringGraphBuild(self): # The rank of the mask tensor must be specified. This is explained # in the docstring as well. with self.test_session() as sess: ph_tensor = array_ops.placeholder(dtypes.int32, shape=None) ph_mask = array_ops.placeholder(dtypes.bool, shape=[None]) arr = np.array([[1, 2], [3, 4]]) mask = np.array([False, True]) masked_tensor = sess.run( array_ops.boolean_mask(ph_tensor, ph_mask), feed_dict={ ph_tensor: arr, ph_mask: mask }) np.testing.assert_allclose(masked_tensor, arr[mask]) def testMaskDimensionsSetToNoneRaises(self): # The rank of the mask tensor must be specified. This is explained # in the docstring as well. with self.test_session(): tensor = array_ops.placeholder(dtypes.int32, shape=[None, 2]) mask = array_ops.placeholder(dtypes.bool, shape=None) with self.assertRaisesRegexp(ValueError, "dimensions must be specified"): array_ops.boolean_mask(tensor, mask) def testMaskHasMoreDimsThanTensorRaises(self): mask = [[True, True], [False, False]] tensor = [1, 2, 3, 4] with self.test_session(): with self.assertRaisesRegexp(ValueError, "incompatible"): array_ops.boolean_mask(tensor, mask).eval() def testMaskIsScalarRaises(self): mask = True tensor = 1 with self.test_session(): with self.assertRaisesRegexp(ValueError, "mask.*scalar"): array_ops.boolean_mask(tensor, mask).eval() def testMaskShapeDifferentThanFirstPartOfTensorShapeRaises(self): mask = [True, True, True] tensor = [[1, 2], [3, 4]] with self.test_session(): with self.assertRaisesRegexp(ValueError, "incompatible"): array_ops.boolean_mask(tensor, mask).eval() class OperatorShapeTest(test_util.TensorFlowTestCase): def testExpandScalar(self): scalar = "hello" scalar_expanded = array_ops.expand_dims(scalar, [0]) self.assertEqual(scalar_expanded.get_shape(), (1,)) def testSqueezeScalar(self): scalar = "hello" scalar_squeezed = array_ops.squeeze(scalar, ()) self.assertEqual(scalar_squeezed.get_shape(), ()) def testSqueezeMatrix(self): matrix = [[1, 2, 3]] matrix_squeezed = array_ops.squeeze(matrix, [0]) self.assertEqual(matrix_squeezed.get_shape(), (3)) with self.assertRaises(ValueError): matrix_squeezed = array_ops.squeeze(matrix, [1]) def testSqueezeScalarDim(self): matrix = [[1, 2, 3]] matrix_squeezed = array_ops.squeeze(matrix, 0) self.assertEqual(matrix_squeezed.get_shape(), (3)) class ReverseV2Test(test_util.TensorFlowTestCase): def testReverse0DimAuto(self): x_np = 4 for use_gpu in [False, True]: with self.test_session(use_gpu=use_gpu): x_tf = array_ops.reverse_v2(x_np, []).eval() self.assertAllEqual(x_tf, x_np) def _reverse1DimAuto(self, np_dtype): x_np = np.array([1, 200, 3, 40, 5], dtype=np_dtype) for use_gpu in [False, True]: for axis_dtype in [dtypes.int32, dtypes.int64]: with self.test_session(use_gpu=use_gpu): x_tf = array_ops.reverse_v2(x_np, constant_op.constant( [0], dtype=axis_dtype)).eval() self.assertAllEqual(x_tf, np.asarray(x_np)[::-1]) def _reverse2DimAuto(self, np_dtype): x_np = np.array([[1, 200, 3], [4, 5, 60]], dtype=np_dtype) for reverse_f in [array_ops.reverse_v2, array_ops.reverse]: for use_gpu in [False, True]: for axis_dtype in [dtypes.int32, dtypes.int64]: with self.test_session(use_gpu=use_gpu): x_tf_1 = reverse_f(x_np, constant_op.constant( [0], dtype=axis_dtype)).eval() x_tf_2 = reverse_f(x_np, constant_op.constant( [-2], dtype=axis_dtype)).eval() x_tf_3 = reverse_f(x_np, constant_op.constant( [1], dtype=axis_dtype)).eval() x_tf_4 = reverse_f(x_np, constant_op.constant( [-1], dtype=axis_dtype)).eval() x_tf_5 = reverse_f(x_np, constant_op.constant([1, 0], dtype=axis_dtype)).eval() self.assertAllEqual(x_tf_1, np.asarray(x_np)[::-1, :]) self.assertAllEqual(x_tf_2, np.asarray(x_np)[::-1, :]) self.assertAllEqual(x_tf_3, np.asarray(x_np)[:, ::-1]) self.assertAllEqual(x_tf_4, np.asarray(x_np)[:, ::-1]) self.assertAllEqual(x_tf_5, np.asarray(x_np)[::-1, ::-1]) # This test covers the axis validation in the shape function # (no eval()) def testInvalidAxis(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32) with self.assertRaisesRegexp(ValueError, "is out of valid range"): array_ops.reverse_v2(x_np, [-30]) with self.assertRaisesRegexp(ValueError, "is out of valid range"): array_ops.reverse_v2(x_np, [2]) with self.assertRaisesRegexp(ValueError, "axis 0 specified more than once"): array_ops.reverse_v2(x_np, [0, -2]) # This is the version of reverse that uses axis indices rather than # bool tensors # TODO(b/32254538): Change this test to use array_ops.reverse # # Note: this test passes placeholder as constant axis is validated # in shape function (see testInvalidAxis) def testInvalid(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32) axis = array_ops.placeholder(dtypes.int32) with self.test_session(): with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, "is out of valid range"): array_ops.reverse_v2(x_np, axis).eval(feed_dict={axis: [-30]}) with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, "is out of valid range"): array_ops.reverse_v2(x_np, axis).eval(feed_dict={axis: [2]}) with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, "axis 0 specified more than once"): array_ops.reverse_v2(x_np, axis).eval(feed_dict={axis: [0, -2]}) def testReverse1DimAuto(self): for dtype in [ np.uint8, np.int8, np.uint16, np.int16, np.int32, np.int64, np.bool, np.float16, np.float32, np.float64, np.complex64, np.complex128, np.array(b"").dtype.type ]: self._reverse1DimAuto(dtype) def testReverse2DimAuto(self): for dtype in [ np.uint8, np.int8, np.uint16, np.int16, np.int32, np.int64, np.bool, np.float16, np.float32, np.float64, np.complex64, np.complex128, np.array(b"").dtype.type ]: self._reverse2DimAuto(dtype) def testUnknownDims(self): reverse_v2 = array_ops.reverse_v2 data_t = array_ops.placeholder(dtypes.float32) axis_known_t = array_ops.placeholder(dtypes.int32, shape=[3]) reverse_known_t = reverse_v2(data_t, axis_known_t) # Unlike V1 we cannot know this anymore self.assertEqual(None, reverse_known_t.get_shape().ndims) axis_unknown_t = array_ops.placeholder(dtypes.int32) reverse_unknown_t = reverse_v2(data_t, axis_unknown_t) self.assertIs(None, reverse_unknown_t.get_shape().ndims) data_2d_t = array_ops.placeholder(dtypes.float32, shape=[None, None]) axis_2d_t = array_ops.placeholder(dtypes.int32, shape=[3]) reverse_2d_t = reverse_v2(data_2d_t, axis_2d_t) self.assertEqual(2, reverse_2d_t.get_shape().ndims) def testReverseRowsOf3Channels(self): """Tests optimized code for reversing rows with last dim size = 3.""" with self.test_session(use_gpu=True): for reverse_f in [array_ops.reverse_v2, array_ops.reverse]: for outer_size in (1, 2): for middle_size in list(range(50)) + [100000]: x_np = np.reshape( np.arange(outer_size * middle_size * 3, dtype=np.float32), newshape=(outer_size, middle_size, 3)) x_tf = reverse_f(x_np, [1]).eval() np_answer = x_np[:, ::-1, :] self.assertAllEqual(x_tf, np_answer) def testReverseRowsOf4Channels(self): with self.test_session(use_gpu=True): for reverse_f in [array_ops.reverse_v2, array_ops.reverse]: for outer_size in (1, 2): for middle_size in list(range(50)) + [100000]: x_np = np.reshape( np.arange(outer_size * middle_size * 4, dtype=np.float32), newshape=(outer_size, middle_size, 4)) x_tf = reverse_f(x_np, [1]).eval() np_answer = x_np[:, ::-1, :] self.assertAllEqual(x_tf, np_answer) def testReverseColumnsOf3Channels(self): with self.test_session(use_gpu=True): for reverse_f in [array_ops.reverse_v2, array_ops.reverse]: for outer_size in list(range(50)) + [100000]: for middle_size in (1, 2): x_np = np.reshape( np.arange(outer_size * middle_size * 3, dtype=np.float32), newshape=(outer_size, middle_size, 3)) x_tf = reverse_f(x_np, [0]).eval() np_answer = x_np[::-1, :, :] self.assertAllEqual(x_tf, np_answer) class MeshgridTest(test_util.TensorFlowTestCase): def _compareDiff(self, x, y, use_gpu): for index in ("ij", "xy"): numpy_out = np.meshgrid(x, y, indexing=index) tf_out = array_ops.meshgrid(x, y, indexing=index) with self.test_session(use_gpu=use_gpu): for xx, yy in zip(numpy_out, tf_out): self.assertAllEqual(xx, yy.eval()) def _compareDiffType(self, n, np_dtype, use_gpu): inputs = [] for index in ("ij", "xy"): for _ in range(n): x = np.linspace(-10, 10, 5).astype(np_dtype) if np_dtype in (np.complex64, np.complex128): x += 1j inputs.append(x) numpy_out = np.meshgrid(*inputs, indexing=index) with self.test_session(use_gpu=use_gpu): tf_out = array_ops.meshgrid(*inputs, indexing=index) for x_np, x_tf in zip(numpy_out, tf_out): self.assertAllEqual(x_np, x_tf.eval()) def testCompare(self): for t in (np.float16, np.float32, np.float64, np.int32, np.int64, np.complex64, np.complex128): self._compareDiffType(2, t, False) self._compareDiffType(3, t, False) x = [1, 2, 3] y = [4, 5] a = [[1, 1], [1, 1]] self._compareDiff(x, y, False) self._compareDiff(x, a, False) class StridedSliceChecker(object): """Check a given tensor against the numpy result.""" REF_TENSOR = np.arange(1, 19, dtype=np.float32).reshape(3, 2, 3) REF_TENSOR_ALIGNED = np.arange(1, 97, dtype=np.float32).reshape(3, 4, 8) def __init__(self, test, x, tensor_type=dtypes.int32, check_type_infer=True): self.x_np = np.array(x).astype(tensor_type.as_numpy_dtype) # Give the value a non-zero imaginary component for complex types. if tensor_type.is_complex: self.x_np -= 1j * self.x_np self.test = test self.x = constant_op.constant(self.x_np, dtype=tensor_type) self.check_type_infer = check_type_infer def __getitem__(self, spec): op = self.x.__getitem__(spec) if not isinstance(spec, (list, tuple)): spec = [spec] tensor = op.eval() # Make a numpy spec that pre-evals the tensors np_specs = [] def eval_if_tensor(x): try: return x.eval() except AttributeError: return x for s in spec: if isinstance(s, slice): start = eval_if_tensor(s.start) stop = eval_if_tensor(s.stop) step = eval_if_tensor(s.step) np_specs.append(slice(start, stop, step)) else: np_specs.append(eval_if_tensor(s)) self.test.assertAllEqual(self.x_np[tuple(np_specs)], tensor) if self.check_type_infer: self.test.assertAllEqual(tensor.shape, op.get_shape()) return tensor STRIDED_SLICE_TYPES = [ dtypes.int32, dtypes.int64, dtypes.int16, dtypes.int8, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128 ] class StridedSliceTest(test_util.TensorFlowTestCase): """Test the strided slice operation with variants of slices.""" def test_basic_slice(self): for tensor_type in STRIDED_SLICE_TYPES: with self.test_session(use_gpu=not tensor_type.is_integer): checker = StridedSliceChecker( self, StridedSliceChecker.REF_TENSOR, tensor_type=tensor_type) _ = checker[:, :, :] # Various ways of representing identity slice _ = checker[:, :, :] _ = checker[::, ::, ::] _ = checker[::1, ::1, ::1] # Not zero slice _ = checker[::1, ::5, ::2] # Reverse in each dimension independently _ = checker[::-1, :, :] _ = checker[:, ::-1, :] _ = checker[:, :, ::-1] ## negative index tests i.e. n-2 in first component _ = checker[-2::-1, :, ::1] # negative index tests i.e. n-2 in first component, non-unit stride _ = checker[-2::-1, :, ::2] # Check rank-0 examples checker2 = StridedSliceChecker(self, 5, tensor_type=tensor_type) _ = checker2[None] _ = checker2[...] _ = checker2[tuple()] def testInt64GPU(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") with self.test_session(use_gpu=True, force_gpu=True): x = constant_op.constant([1., 2., 3.]) begin = constant_op.constant([2], dtype=dtypes.int64) end = constant_op.constant([3], dtype=dtypes.int64) strides = constant_op.constant([1], dtype=dtypes.int64) s = array_ops.strided_slice(x, begin, end, strides) self.assertAllEqual([3.], self.evaluate(s)) def testDegenerateSlices(self): with self.test_session(use_gpu=True): checker = StridedSliceChecker(self, StridedSliceChecker.REF_TENSOR) # degenerate by offering a forward interval with a negative stride _ = checker[0:-1:-1, :, :] # degenerate with a reverse interval with a positive stride _ = checker[-1:0, :, :] # empty interval in every dimension _ = checker[-1:0, 2:2, 2:3:-1] def testEllipsis(self): with self.test_session(use_gpu=True): raw = [[[[[1, 2], [3, 4], [5, 6]]], [[[7, 8], [9, 10], [11, 12]]]]] checker = StridedSliceChecker(self, raw) _ = checker[0:] # implicit ellipsis _ = checker[0:, ...] # ellipsis alone _ = checker[...] # ellipsis at end _ = checker[0:1, ...] # ellipsis at begin _ = checker[..., 0:1] # ellipsis at middle _ = checker[0:1, ..., 0:1] # multiple ellipses not allowed with self.assertRaisesRegexp(ValueError, "Multiple ellipses"): _ = checker[..., :, ...].eval() def testShrink(self): with self.test_session(use_gpu=True): raw = [[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]], [[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]]] checker = StridedSliceChecker(self, raw) _ = checker[:, :, :, :, 3] _ = checker[..., 3] _ = checker[:, 0] _ = checker[:, :, 0] def testTensorIndexing(self): with self.test_session(use_gpu=True): raw = [[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]], [[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]]] checker = StridedSliceChecker(self, raw, check_type_infer=False) bar = constant_op.constant(2) bar2 = constant_op.constant(3) _ = checker[..., bar:bar2] _ = checker[..., bar] with self.assertRaisesRegexp( TypeError, "Value passed to parameter 'begin' has DataType float32 not in " "list of allowed values"): _ = checker[..., 3.0] _ = checker[..., 3] def testExpand(self): with self.test_session(use_gpu=True): raw = [[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]], [[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]]] checker = StridedSliceChecker(self, raw) # new axis (followed by implicit ellipsis) _ = checker[np.newaxis] # newaxis after ellipsis _ = checker[..., np.newaxis] # newaxis in between ellipsis and explicit range _ = checker[..., np.newaxis, :] _ = checker[:, ..., np.newaxis, :, :] # Reverse final dimension with new axis _ = checker[:, :, np.newaxis, :, 2::-1] # Ellipsis in middle of two newaxis _ = checker[np.newaxis, ..., np.newaxis] def testExpandVariable(self): with self.test_session(use_gpu=True): x = variables.Variable(7, dtype=dtypes.int32) x.initializer.run() y = x[None].eval() self.assertEqual(y.shape, (1,)) self.assertAllEqual(y, (7,)) def testOptimizedCases(self): with self.test_session(use_gpu=True): checker = StridedSliceChecker(self, StridedSliceChecker.REF_TENSOR_ALIGNED) # Identity _ = checker[:] # Identity _ = checker[...] # Identity _ = checker[np.newaxis, ..., np.newaxis] # First axis slice _ = checker[1:] # First axis slice _ = checker[np.newaxis, 1:] class StridedSliceShapeChecker(object): def __init__(self, x): self.x = x def __getitem__(self, spec): op = self.x.__getitem__(spec) return op.get_shape() class StridedSliceShapeTest(test_util.TensorFlowTestCase): """Test the shape inference of StridedSliceShapes.""" def testUnknown(self): with self.test_session(use_gpu=True): uncertain_tensor = array_ops.placeholder(dtypes.float32) a = StridedSliceShapeChecker(uncertain_tensor) a_slice_shape = a[...] self.assertAllEqual(a_slice_shape.ndims, None) def tensorShapeEqual(self, x, y): self.assertTrue(x is not None and y is not None or x is None and y is None) self.assertEqual(x.as_list(), y.as_list()) def testTensorShapeUncertain(self): with self.test_session(use_gpu=True): uncertain_tensor = array_ops.placeholder( dtypes.float32, shape=(5, None, 7)) a = StridedSliceShapeChecker(uncertain_tensor) self.tensorShapeEqual(a[3:5], tensor_shape.TensorShape([2, None, 7])) self.tensorShapeEqual(a[3:5, :, 4], tensor_shape.TensorShape([2, None])) self.tensorShapeEqual(a[3:5, 3:4, 4], tensor_shape.TensorShape([2, None])) self.tensorShapeEqual(a[3:5, :, 5:10], tensor_shape.TensorShape([2, None, 2])) self.tensorShapeEqual(a[3:5, :, 50:3], tensor_shape.TensorShape([2, None, 0])) self.tensorShapeEqual(a[3:5, :, array_ops.newaxis, 50:3,], tensor_shape.TensorShape([2, None, 1, 0])) self.tensorShapeEqual(a[1:5:2, :, array_ops.newaxis, 50:3,], tensor_shape.TensorShape([2, None, 1, 0])) self.tensorShapeEqual(a[:5:3, :, array_ops.newaxis, 50:3,], tensor_shape.TensorShape([2, None, 1, 0])) self.tensorShapeEqual(a[:2:3, :, array_ops.newaxis, 50:3,], tensor_shape.TensorShape([1, None, 1, 0])) self.tensorShapeEqual(a[::-1, :, array_ops.newaxis, ::-2], tensor_shape.TensorShape([5, None, 1, 4])) def testTensorValuedIndexShape(self): with self.test_session(use_gpu=True): defined_shape_tensor = array_ops.placeholder( dtypes.float32, shape=(5, 3, 7)) index_value = array_ops.placeholder(dtypes.int32, shape=()) a = StridedSliceShapeChecker(defined_shape_tensor) self.tensorShapeEqual(a[index_value], tensor_shape.TensorShape([3, 7])) self.tensorShapeEqual(a[index_value, ::-1], tensor_shape.TensorShape([3, 7])) self.tensorShapeEqual(a[index_value, ::-2], tensor_shape.TensorShape([2, 7])) other_scalar = array_ops.placeholder(dtypes.int32, shape=()) self.tensorShapeEqual(a[index_value, other_scalar:2], tensor_shape.TensorShape([None, 7])) class GradSliceChecker(object): """Tests that we can compute a gradient for var^2.""" def __init__(self, test, sess, var, varnp): self.test = test self.sess = sess self.val = var * var self.var = var self.varnp = varnp def __getitem__(self, spec): slice_var = self.var[spec] slice_val = self.val[spec] # compute analytic 2nd derivative analytic_grad2 = 2 * slice_val dy = variables.Variable( array_ops.ones(shape=slice_var.get_shape(), dtype=dtypes.int32)) assign = dy.assign(slice_var) slice_val_grad, = gradients_impl.gradients(slice_val, self.var, grad_ys=dy) slice_val_grad2, = gradients_impl.gradients( slice_val_grad, dy, grad_ys=self.var) self.sess.run(assign) slice_val_grad_evaled, slice_val_grad2_evaled = ( self.sess.run([slice_val_grad, slice_val_grad2])) analytic_grad2_evaled = analytic_grad2.eval() self.test.assertAllEqual(slice_val_grad2_evaled, analytic_grad2_evaled) # compute analytic gradient for slice np_val_grad = (2 * self.varnp * self.varnp) np_sliceval_grad = np.zeros(self.var.get_shape()) np_sliceval_grad[spec] = np_val_grad[spec] # verify gradient self.test.assertAllEqual(slice_val_grad_evaled, np_sliceval_grad) class StridedSliceGradTest(test_util.TensorFlowTestCase): """Test that strided slice's custom gradient produces correct gradients.""" def testGradient(self): with self.test_session(use_gpu=True) as sess: var = variables.Variable( array_ops.reshape(math_ops.range(1, 97, 1), shape=(6, 4, 4))) init = variables.global_variables_initializer() sess.run(init) grad = GradSliceChecker(self, sess, var, np.array(range(1, 97, 1)).reshape((6, 4, 4))) _ = grad[2:6:2, 1:3, 1:3] _ = grad[3:0:-2, 1:3, 1:3] _ = grad[3:0:-2, array_ops.newaxis, 1:3, 2, array_ops.newaxis] _ = grad[3:0:-2, 1:3, 2] _ = grad[:, -1, :] _ = grad[:, -2, :] with self.assertRaisesRegexp(ValueError, "out of bounds"): _ = grad[:, -200, :] with self.assertRaisesRegexp(ValueError, "out of bounds"): _ = grad[:, 200, :] def testGradientZero(self): with self.test_session(use_gpu=True) as sess: var = variables.Variable(8) init = variables.global_variables_initializer() sess.run(init) grad = GradSliceChecker(self, sess, var, np.array(8)) _ = grad[tuple()] def testInt64Indices(self): with self.test_session(use_gpu=True) as sess: a = math_ops.range(3) index = constant_op.constant(1, dtype=dtypes.int64) b = 2 * a[index] grad, = gradients_impl.gradients(b, a) self.assertAllEqual(sess.run(grad), [0, 2, 0]) class StridedSliceGradTypeTest(test_util.TensorFlowTestCase): """Test varied index types and host located memory.""" def testHostVsDevice(self): with self.test_session(use_gpu=True) as sess: var2 = variables.Variable( array_ops.reshape( math_ops.cast(math_ops.range(1, 5, 1), dtypes.float32), shape=(4, 1, 1))) varshape = variables.Variable([6, 4, 4], dtype=dtypes.int32) sess.run(variables.global_variables_initializer()) begin = constant_op.constant([0, 0, 0]) end = constant_op.constant([4, 1, 1]) strides = constant_op.constant([1, 1, 1]) foo = array_ops.strided_slice_grad(varshape, begin, end, strides, var2) sess.run(foo) def testInt64Shape(self): with self.test_session(use_gpu=True) as sess: original_dy = array_ops.reshape( math_ops.cast(math_ops.range(1, 5, 1), dtypes.float32), shape=(4, 1, 1)) original_shape = constant_op.constant([6, 4, 4], dtype=dtypes.int64) sess.run(variables.global_variables_initializer()) begin = constant_op.constant([0, 0, 0], dtype=dtypes.int64) end = constant_op.constant([4, 1, 1], dtype=dtypes.int64) strides = constant_op.constant([1, 1, 1], dtype=dtypes.int64) dx = array_ops.strided_slice_grad(original_shape, begin, end, strides, original_dy) sess.run(dx) def testMixedIndexTypes(self): with self.test_session(use_gpu=True) as sess: original_dy = array_ops.reshape( math_ops.cast(math_ops.range(1, 5, 1), dtypes.float32), shape=(4, 1, 1)) original_shape = constant_op.constant([6, 4, 4], dtype=dtypes.int64) sess.run(variables.global_variables_initializer()) begin = constant_op.constant([0, 0, 0], dtype=dtypes.int32) end = constant_op.constant([4, 1, 1], dtype=dtypes.int64) strides = constant_op.constant([1, 1, 1], dtype=dtypes.int64) with self.assertRaisesRegexp( TypeError, "Input 'begin' of 'StridedSliceGrad' Op has type int32" " that does not match type int64 of argument 'shape'"): dx = array_ops.strided_slice_grad(original_shape, begin, end, strides, original_dy) sess.run(dx) class BenchmarkSlice(object): def __init__(self, tensor): self.tensor = tensor def __getitem__(self, x): return self.tensor[x] class StridedSliceBenchmark(test_lib.Benchmark): """Benchmark new strided slice operation on non-trivial case.""" def run_and_time(self, slice_op): variables.global_variables_initializer().run() for _ in range(10): _ = slice_op.eval() iters = 1000 t0 = time.time() for _ in range(iters): slice_op.eval() t1 = time.time() self.report_benchmark(iters=iters, wall_time=(t1 - t0) / 1000.0) def make_variable(self): n = 256 shape = (n, n, n) items = n**3 var = variables.Variable( array_ops.reshape(math_ops.linspace(1., float(items), items), shape), dtype=dtypes.float32) return var def benchmark_strided_slice_skip(self): with session.Session(): var = self.make_variable() helper = BenchmarkSlice(var) slice_op = helper[::2, ::1, ::2] self.run_and_time(slice_op) def benchmark_strided_slice_easy(self): with session.Session(): var = self.make_variable() helper = BenchmarkSlice(var) slice_op = helper[3::1, 3::1, 3::1] self.run_and_time(slice_op) def benchmark_slice_easy(self): with session.Session(): var = self.make_variable() slice_op = var[3::1, 3::1, 3::1] self.run_and_time(slice_op) class StridedSliceAssignChecker(object): def __init__(self, test, x, tensor_type=dtypes.float32, use_resource=False): self.tensor_type = tensor_type self.test = test self._use_resource = use_resource self.x_np = np.array(x).astype(tensor_type.as_numpy_dtype) # Give the value a non-zero imaginary component for complex types. if tensor_type.is_complex: self.x_np -= 1j * self.x_np self.x = constant_op.constant(self.x_np, dtype=tensor_type) def __setitem__(self, index, value): value = np.array(value).astype(self.tensor_type.as_numpy_dtype) # Give the value a non-zero imaginary component for complex types. if self.tensor_type.is_complex: value -= 1j * value with self.test.test_session( use_gpu=not self.tensor_type.is_integer) as sess: if self._use_resource: var = resource_variable_ops.ResourceVariable(self.x) else: var = variables.Variable(self.x) sess.run(variables.variables_initializer([var])) val = sess.run(var[index].assign(value)) # val_copy is used to check that tf.assign works equivalently to the # assign method above. val_copy = sess.run(state_ops.assign(var[index], value)) valnp = np.copy(self.x_np) valnp[index] = np.array(value) self.test.assertAllEqual(val, valnp) self.test.assertAllEqual(val_copy, valnp) class SliceAssignTest(test_util.TensorFlowTestCase): def testInvalidSlice(self): with self.test_session() as sess: foo = constant_op.constant([1, 2, 3]) with self.assertRaisesRegexp(ValueError, "Sliced assignment" " is only supported for variables"): bar = foo[:2].assign(constant_op.constant([1, 2])) sess.run(bar) def doTestSliceAssign(self, use_resource): for dtype in STRIDED_SLICE_TYPES: checker = StridedSliceAssignChecker( self, [[1, 2, 3], [4, 5, 6]], use_resource=use_resource, tensor_type=dtype) # Check if equal checker[:] = [[10, 20, 30], [40, 50, 60]] # Check trivial (1,1) shape tensor checker[1:2, 1:2] = [[66]] # shrinks shape changes checker[1:2, 1] = [66] checker[1, 1:2] = [66] checker[1, 1] = 66 # newaxis shape changes checker[:, None, :] = [[[10, 20, 30]], [[40, 50, 50]]] # shrink and newaxis checker[None, None, 0, 0:1] = [[[99]]] # Non unit strides checker[::1, ::-2] = [[3, 33], [4, 44]] # degenerate interval checker[8:10, 0] = [] checker[8:10, 8:10] = [[]] # Assign vector to scalar (rank-0) using newaxis checker2 = StridedSliceAssignChecker(self, 222) checker2[()] = 6 # no indices checker2[...] = 6 # ellipsis checker2[None] = [6] # new axis def testSliceAssign(self): self.doTestSliceAssign(use_resource=False) def testSliceAssignResource(self): self.doTestSliceAssign(use_resource=True) def testUninitialized(self): with self.assertRaisesRegexp( errors.FailedPreconditionError, "Attempting to use uninitialized value Variable"): with self.test_session() as sess: v = variables.Variable([1, 2]) sess.run(v[:].assign([1, 2])) def testTypeError(self): init_val = constant_op.constant([1, 2], dtype=dtypes.int32) too_small_val = constant_op.constant([3, 4], dtype=dtypes.int8) too_large_val = constant_op.constant([3, 4], dtype=dtypes.int64) v = variables.Variable(init_val) with self.assertRaises(TypeError): v[:].assign(too_small_val) with self.assertRaises(TypeError): v[:].assign(too_large_val) def testTypeErrorResource(self): init_val = constant_op.constant([1, 2], dtype=dtypes.int32) too_small_val = constant_op.constant([3, 4], dtype=dtypes.int8) too_large_val = constant_op.constant([3, 4], dtype=dtypes.int64) v = resource_variable_ops.ResourceVariable(init_val) with self.test_session() as sess: sess.run(v.initializer) with self.assertRaisesRegexp( errors.InvalidArgumentError, "l-value dtype int32 does not match r-value dtype int64"): sess.run(v[:].assign(too_large_val)) with self.assertRaises(errors.InvalidArgumentError): sess.run(v[:].assign(too_small_val)) class ShapeSizeRankTest(test_util.TensorFlowTestCase): @test_util.run_in_graph_and_eager_modes() def testDenseShape(self): t_value = [[0, 42], [24, 0]] self.assertAllEqual((2, 2), self.evaluate(array_ops.shape(t_value))) self.assertEqual(4, self.evaluate(array_ops.size(t_value))) self.assertEqual(2, self.evaluate(array_ops.rank(t_value))) t = constant_op.constant(t_value) self.assertAllEqual((2, 2), self.evaluate(array_ops.shape(t))) self.assertEqual(4, self.evaluate(array_ops.size(t))) self.assertEqual(2, self.evaluate(array_ops.rank(t))) @test_util.run_in_graph_and_eager_modes() def testSparseShape(self): sp_value = sparse_tensor.SparseTensorValue( indices=((0, 1), (1, 0)), values=(42, 24), dense_shape=(2, 2)) self.assertAllEqual((2, 2), self.evaluate(array_ops.shape(sp_value))) self.assertEqual(4, self.evaluate(array_ops.size(sp_value))) self.assertEqual(2, self.evaluate(array_ops.rank(sp_value))) sp = sparse_tensor.SparseTensor.from_value(sp_value) self.assertAllEqual((2, 2), self.evaluate(array_ops.shape(sp))) self.assertEqual(4, self.evaluate(array_ops.size(sp))) self.assertEqual(2, self.evaluate(array_ops.rank(sp))) @test_util.run_in_graph_and_eager_modes() def testSizeDtype(self): tensor = [1] self.assertEqual(dtypes.int32, self.evaluate(array_ops.size(tensor)).dtype) self.assertEqual( dtypes.int64, self.evaluate(array_ops.size(tensor, out_type=dtypes.int64)).dtype) @test_util.with_c_api class SequenceMaskTest(test_util.TensorFlowTestCase): def testExceptions(self): with self.test_session(): with self.assertRaisesRegexp(ValueError, "maxlen must be scalar"): array_ops.sequence_mask([10, 20], [10, 20]) def testOneDimensionalWithMaxlen(self): with self.test_session(): res = array_ops.sequence_mask(constant_op.constant([1, 3, 2]), 5) self.assertAllEqual(res.get_shape(), [3, 5]) self.assertAllEqual( res.eval(), [[True, False, False, False, False], [True, True, True, False, False], [True, True, False, False, False]]) @test_util.enable_c_shapes def testOneDimensionalDtypeWithoutMaxlen(self): with self.test_session(): # test dtype and default maxlen: res = array_ops.sequence_mask(constant_op.constant([0, 1, 4]), dtype=dtypes.float32) if ops._USE_C_API: self.assertAllEqual(res.get_shape().as_list(), [3, 4]) else: self.assertAllEqual(res.get_shape().as_list(), [3, None]) self.assertAllEqual( res.eval(), [[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0]]) @test_util.enable_c_shapes def testOneDimensionalWithoutMaxlen(self): with self.test_session(): res = array_ops.sequence_mask( constant_op.constant([0, 1, 4])) if ops._USE_C_API: self.assertAllEqual(res.get_shape().as_list(), [3, 4]) else: self.assertAllEqual(res.get_shape().as_list(), [3, None]) self.assertAllEqual( res.eval(), [[False, False, False, False], [True, False, False, False], [True, True, True, True]]) @test_util.enable_c_shapes def testTwoDimensional(self): with self.test_session(): res = array_ops.sequence_mask(constant_op.constant([[1, 3, 2]]), 5) self.assertAllEqual(res.get_shape(), [1, 3, 5]) self.assertAllEqual(res.eval(), [[[True, False, False, False, False], [ True, True, True, False, False ], [True, True, False, False, False]]]) # test dtype and default maxlen: res = array_ops.sequence_mask( constant_op.constant([[0, 1, 4], [1, 2, 3]]), dtype=dtypes.float32) if ops._USE_C_API: self.assertAllEqual(res.get_shape().as_list(), [2, 3, 4]) else: self.assertAllEqual(res.get_shape().as_list(), [2, 3, None]) self.assertAllEqual( res.eval(), [[[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0]], [[1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 1.0, 0.0]]]) def testUnknownShape(self): lengths = array_ops.placeholder(dtype=dtypes.int32) res = array_ops.sequence_mask(lengths) self.assertEqual(res.shape, None) def testDtypes(self): def check_dtypes(lengths_dtype, maxlen_dtype): res = array_ops.sequence_mask( constant_op.constant([1, 3, 2], dtype=lengths_dtype), constant_op.constant(5, dtype=maxlen_dtype)) self.assertAllEqual(res.get_shape(), [3, 5]) self.assertAllEqual( res.eval(), [[True, False, False, False, False], [True, True, True, False, False], [True, True, False, False, False]]) with self.test_session(): check_dtypes(dtypes.int32, dtypes.int32) check_dtypes(dtypes.int32, dtypes.int64) check_dtypes(dtypes.int64, dtypes.int32) check_dtypes(dtypes.int64, dtypes.int64) class ConcatSliceResourceTest(test_util.TensorFlowTestCase): @test_util.run_in_graph_and_eager_modes() def testConcatSlice(self): r1 = test_ops.stub_resource_handle_op(container="a", shared_name="b") r2 = test_ops.stub_resource_handle_op(container="a", shared_name="c") c = array_ops.stack([r1, r2]) s = array_ops.strided_slice(c, [1], [2]) self.evaluate(test_ops.resource_create_op(s)) with self.assertRaises(errors.AlreadyExistsError): self.evaluate(test_ops.resource_create_op(r2)) class IdentityTest(test_util.TensorFlowTestCase): def testEagerIdentity(self): with context.eager_mode(): ctx = context.get_default_context() if not ctx.num_gpus(): self.skipTest("No GPUs found") def _test(x, y, device): self.assertAllEqual(x.numpy(), y.numpy()) self.assertTrue(device in y.device.lower()) with ops.device("gpu:0"): a = constant_op.constant([[2], [3]], dtype=dtypes.float32) with ops.device("gpu:0"): b = array_ops.identity(a) _test(a, b, "gpu") with ops.device("cpu:0"): c = array_ops.identity(b) _test(b, c, "cpu") with ops.device("cpu:0"): d = array_ops.identity(c) _test(c, d, "cpu") with ops.device("gpu:0"): e = array_ops.identity(d) _test(d, e, "gpu") class PadTest(test_util.TensorFlowTestCase): def testEager(self): with context.eager_mode(): t = constant_op.constant([[1, 2, 3], [4, 5, 6]]) paddings = constant_op.constant([[ 1, 1, ], [2, 2]]) padded = array_ops.pad(t, paddings, "CONSTANT") self.assertAllEqual(padded.numpy(), [[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 3, 0, 0], [0, 0, 4, 5, 6, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) class InvertPermutationTest(test_util.TensorFlowTestCase): def testInvertPermutation(self): for dtype in [dtypes.int32, dtypes.int64]: with self.test_session(use_gpu=True): x = constant_op.constant([3, 4, 0, 2, 1], dtype=dtype) y = array_ops.invert_permutation(x) self.assertAllEqual(y.get_shape(), [5]) self.assertAllEqual(y.eval(), [2, 4, 3, 0, 1]) class UnravelIndexTest(test_util.TensorFlowTestCase): # TODO(b/73086570): Reenable test. @unittest.skip("Test does not pass internally.") def testUnravelIndex(self): with self.test_session(): for dtype in [dtypes.int32, dtypes.int64]: indices_1 = constant_op.constant(1621, dtype=dtype) dims_1 = constant_op.constant([6, 7, 8, 9], dtype=dtype) out_1 = array_ops.unravel_index(indices_1, dims_1) self.assertAllEqual(out_1.eval(), [3, 1, 4, 1]) indices_2 = constant_op.constant([1621], dtype=dtype) dims_2 = constant_op.constant([6, 7, 8, 9], dtype=dtype) out_2 = array_ops.unravel_index(indices_2, dims_2) self.assertAllEqual(out_2.eval(), [[3], [1], [4], [1]]) indices_3 = constant_op.constant([22, 41, 37], dtype=dtype) dims_3 = constant_op.constant([7, 6], dtype=dtype) out_3 = array_ops.unravel_index(indices_3, dims_3) self.assertAllEqual(out_3.eval(), [[3, 6, 6], [4, 5, 1]]) class GuaranteeConstOpTest(test_util.TensorFlowTestCase): def testSimple(self): with self.test_session(): a = array_ops.constant(10) guarantee_a = array_ops.guarantee_const(a) self.assertEqual(10, guarantee_a.eval()) def testVariables(self): with self.test_session() as sess: for use_resource in [False, True]: a = variable_scope.get_variable( "var_{}".format(use_resource), [], initializer=init_ops.constant_initializer(10.0), use_resource=use_resource) guarantee_a = array_ops.guarantee_const(a) sess.run(variables.global_variables_initializer()) self.assertEqual(10.0, guarantee_a.eval()) def testResourceRejection(self): with self.test_session() as sess: a = variable_scope.get_variable( "resource_var", [], initializer=init_ops.constant_initializer(10.0), use_resource=True) guarantee_a = array_ops.guarantee_const(a.handle) sess.run(variables.global_variables_initializer()) with self.assertRaisesWithPredicateMatch(errors.InvalidArgumentError, "cannot be a resource variable"): guarantee_a.eval() class SnapshotOpTest(test_util.TensorFlowTestCase): def testInvertPermutation(self): for dtype in [dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64]: with self.test_session(use_gpu=True): x = constant_op.constant([0, 1, 2, 3], dtype=dtype) y = gen_array_ops.snapshot(x) self.assertAllEqual(y.eval(), [0, 1, 2, 3]) if __name__ == "__main__": test_lib.main()
apache-2.0
suriya/rasikapriya
rasikapriya/admin.py
1
1655
import autocomplete_light from django import forms from django.contrib import admin from .models import (Instrument, Artist, Venue, Organization, Festival, Concert, Performance) from .widgets import PlacesAutocompleteWidget class VenueForm(forms.ModelForm): class Meta: model = Venue widgets = { 'address': PlacesAutocompleteWidget(), } class VenueAdmin(admin.ModelAdmin): form = VenueForm admin.site.register(Venue, VenueAdmin) # admin.site.register(Instrument) # admin.site.register(Organization) # admin.site.register(Festival) # class ArtistAdmin(admin.ModelAdmin): # filter_horizontal = ('instruments', ) # admin.site.register(Artist, ArtistAdmin) # class ArtistInline(admin.TabularInline): # form = autocomplete_light.modelform_factory(Artist) # model = Artist class ArtistAdmin(admin.ModelAdmin): form = autocomplete_light.modelform_factory(Artist) # inlines = [ArtistInline] admin.site.register(Artist, ArtistAdmin) class OrganizationAdmin(admin.ModelAdmin): form = autocomplete_light.modelform_factory(Organization) admin.site.register(Organization, OrganizationAdmin) class FestivalAdmin(admin.ModelAdmin): form = autocomplete_light.modelform_factory(Festival) admin.site.register(Festival, FestivalAdmin) class PerformanceInline(admin.TabularInline): form = autocomplete_light.modelform_factory(Performance) model = Performance # extra = 4 class ConcertAdmin(admin.ModelAdmin): form = autocomplete_light.modelform_factory(Concert) inlines = (PerformanceInline,) admin.site.register(Concert, ConcertAdmin) # admin.site.register(Concert)
mit
jomolinare/kobocat
onadata/apps/api/tests/viewsets/test_xform_submission_api.py
5
16178
import os from django.core.files.uploadedfile import InMemoryUploadedFile from django.test import TransactionTestCase from django_digest.test import DigestAuth from django.contrib.auth.models import AnonymousUser import simplejson as json from onadata.apps.api.tests.viewsets.test_abstract_viewset import\ TestAbstractViewSet from onadata.apps.api.viewsets.xform_submission_api import XFormSubmissionApi from onadata.apps.logger.models import Attachment from onadata.libs.permissions import DataEntryRole class TestXFormSubmissionApi(TestAbstractViewSet, TransactionTestCase): def setUp(self): super(self.__class__, self).setUp() self.view = XFormSubmissionApi.as_view({ "head": "create", "post": "create" }) self._publish_xls_form_to_project() def test_post_submission_anonymous(self): s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) with open(path) as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) submission_path = os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') with open(submission_path) as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post( '%s/submission' % self.user.username, data) request.user = AnonymousUser() response = self.view(request, username=self.user.username) self.assertContains(response, 'Successful submission', status_code=201) self.assertTrue(response.has_header('X-OpenRosa-Version')) self.assertTrue( response.has_header('X-OpenRosa-Accept-Content-Length')) self.assertTrue(response.has_header('Date')) self.assertEqual(response['Content-Type'], 'text/xml; charset=utf-8') self.assertEqual(response['Location'], 'http://testserver/%s/submission' % self.user.username) def test_post_submission_authenticated(self): s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) with open(path) as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) submission_path = os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') with open(submission_path) as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post('/submission', data) response = self.view(request) self.assertEqual(response.status_code, 401) auth = DigestAuth('bob', 'bobbob') request.META.update(auth(request.META, response)) response = self.view(request, username=self.user.username) self.assertContains(response, 'Successful submission', status_code=201) self.assertTrue(response.has_header('X-OpenRosa-Version')) self.assertTrue( response.has_header('X-OpenRosa-Accept-Content-Length')) self.assertTrue(response.has_header('Date')) self.assertEqual(response['Content-Type'], 'text/xml; charset=utf-8') self.assertEqual(response['Location'], 'http://testserver/submission') def test_post_submission_uuid_other_user_username_not_provided(self): alice_data = {'username': 'alice', 'email': 'alice@localhost.com'} self._create_user_profile(alice_data) s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) with open(path) as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) path = os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') path = self._add_uuid_to_submission_xml(path, self.xform) with open(path) as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post('/submission', data) response = self.view(request) self.assertEqual(response.status_code, 401) auth = DigestAuth('alice', 'bobbob') request.META.update(auth(request.META, response)) response = self.view(request) self.assertEqual(response.status_code, 403) def test_post_submission_authenticated_json(self): path = os.path.join( os.path.dirname(os.path.abspath(__file__)), '..', 'fixtures', 'transport_submission.json') with open(path) as f: data = json.loads(f.read()) request = self.factory.post('/submission', data, format='json') response = self.view(request) self.assertEqual(response.status_code, 401) auth = DigestAuth('bob', 'bobbob') request.META.update(auth(request.META, response)) response = self.view(request) self.assertContains(response, 'Successful submission', status_code=201) self.assertTrue(response.has_header('X-OpenRosa-Version')) self.assertTrue( response.has_header('X-OpenRosa-Accept-Content-Length')) self.assertTrue(response.has_header('Date')) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(response['Location'], 'http://testserver/submission') def test_post_submission_authenticated_json_with_geo(self): path = os.path.join( os.path.dirname(os.path.abspath(__file__)), '..', 'fixtures', 'movie_form_submission.json') with open(path) as f: data = json.loads(f.read()) request = self.factory.post('/submission', data, format='json') response = self.view(request) self.assertEqual(response.status_code, 401) auth = DigestAuth('bob', 'bobbob') request.META.update(auth(request.META, response)) response = self.view(request) self.assertContains(response, 'error": "Improperly', status_code=400) self.assertTrue(response.has_header('X-OpenRosa-Version')) self.assertTrue( response.has_header('X-OpenRosa-Accept-Content-Length')) self.assertTrue(response.has_header('Date')) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(response['Location'], 'http://testserver/submission') def test_post_submission_authenticated_bad_json(self): path = os.path.join( os.path.dirname(os.path.abspath(__file__)), '..', 'fixtures', 'transport_submission_bad.json') with open(path) as f: data = json.loads(f.read()) request = self.factory.post('/submission', data, format='json') response = self.view(request) self.assertEqual(response.status_code, 401) request = self.factory.post('/submission', data, format='json') auth = DigestAuth('bob', 'bobbob') request.META.update(auth(request.META, response)) response = self.view(request) self.assertContains(response, 'error": "Received empty submission', status_code=400) self.assertTrue(response.has_header('X-OpenRosa-Version')) self.assertTrue( response.has_header('X-OpenRosa-Accept-Content-Length')) self.assertTrue(response.has_header('Date')) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(response['Location'], 'http://testserver/submission') def test_post_submission_require_auth(self): self.user.profile.require_auth = True self.user.profile.save() count = Attachment.objects.count() s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) with open(path) as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) submission_path = os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') with open(submission_path) as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post('/submission', data) response = self.view(request) self.assertEqual(response.status_code, 401) response = self.view(request, username=self.user.username) self.assertEqual(response.status_code, 401) auth = DigestAuth('bob', 'bobbob') request.META.update(auth(request.META, response)) response = self.view(request, username=self.user.username) self.assertContains(response, 'Successful submission', status_code=201) self.assertEqual(count + 1, Attachment.objects.count()) self.assertTrue(response.has_header('X-OpenRosa-Version')) self.assertTrue( response.has_header('X-OpenRosa-Accept-Content-Length')) self.assertTrue(response.has_header('Date')) self.assertEqual(response['Content-Type'], 'text/xml; charset=utf-8') self.assertEqual(response['Location'], 'http://testserver/submission') def test_post_submission_require_auth_anonymous_user(self): self.user.profile.require_auth = True self.user.profile.save() count = Attachment.objects.count() s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) with open(path) as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) submission_path = os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') with open(submission_path) as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post('/submission', data) response = self.view(request) self.assertEqual(response.status_code, 401) response = self.view(request, username=self.user.username) self.assertEqual(response.status_code, 401) self.assertEqual(count, Attachment.objects.count()) def test_post_submission_require_auth_other_user(self): self.user.profile.require_auth = True self.user.profile.save() alice_data = {'username': 'alice', 'email': 'alice@localhost.com'} self._create_user_profile(alice_data) count = Attachment.objects.count() s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) with open(path) as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) submission_path = os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') with open(submission_path) as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post('/submission', data) response = self.view(request) self.assertEqual(response.status_code, 401) response = self.view(request, username=self.user.username) self.assertEqual(response.status_code, 401) self.assertEqual(count, Attachment.objects.count()) auth = DigestAuth('alice', 'bobbob') request.META.update(auth(request.META, response)) response = self.view(request, username=self.user.username) self.assertContains( response, 'alice is not allowed to make submissions to bob', status_code=403) def test_post_submission_require_auth_data_entry_role(self): self.user.profile.require_auth = True self.user.profile.save() alice_data = {'username': 'alice', 'email': 'alice@localhost.com'} alice_profile = self._create_user_profile(alice_data) DataEntryRole.add(alice_profile.user, self.xform) count = Attachment.objects.count() s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) with open(path) as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) submission_path = os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') with open(submission_path) as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post('/submission', data) response = self.view(request) self.assertEqual(response.status_code, 401) response = self.view(request, username=self.user.username) self.assertEqual(response.status_code, 401) self.assertEqual(count, Attachment.objects.count()) auth = DigestAuth('alice', 'bobbob') request.META.update(auth(request.META, response)) response = self.view(request, username=self.user.username) self.assertContains(response, 'Successful submission', status_code=201) def test_post_submission_json_without_submission_key(self): data = {"id": "transportation_2011_07_25"} request = self.factory.post('/submission', data, format='json') response = self.view(request) self.assertEqual(response.status_code, 401) auth = DigestAuth('bob', 'bobbob') request.META.update(auth(request.META, response)) response = self.view(request) self.assertContains(response, 'No submission key provided.', status_code=400)
bsd-2-clause
TiaLuna/Nexus_S_kernel
tools/perf/scripts/python/syscall-counts-by-pid.py
11180
1927
# system call counts, by pid # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide system call totals, broken down by syscall. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os, sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import syscall_name usage = "perf script -s syscall-counts-by-pid.py [comm]\n"; for_comm = None for_pid = None if len(sys.argv) > 2: sys.exit(usage) if len(sys.argv) > 1: try: for_pid = int(sys.argv[1]) except: for_comm = sys.argv[1] syscalls = autodict() def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): print_syscall_totals() def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): if (for_comm and common_comm != for_comm) or \ (for_pid and common_pid != for_pid ): return try: syscalls[common_comm][common_pid][id] += 1 except TypeError: syscalls[common_comm][common_pid][id] = 1 def print_syscall_totals(): if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events by comm/pid:\n\n", print "%-40s %10s\n" % ("comm [pid]/syscalls", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "----------"), comm_keys = syscalls.keys() for comm in comm_keys: pid_keys = syscalls[comm].keys() for pid in pid_keys: print "\n%s [%d]\n" % (comm, pid), id_keys = syscalls[comm][pid].keys() for id, val in sorted(syscalls[comm][pid].iteritems(), \ key = lambda(k, v): (v, k), reverse = True): print " %-38s %10d\n" % (syscall_name(id), val),
gpl-2.0
aajtodd/zipline
zipline/sources/data_source.py
33
1611
from abc import ( ABCMeta, abstractproperty ) from six import with_metaclass from zipline.protocol import DATASOURCE_TYPE from zipline.protocol import Event class DataSource(with_metaclass(ABCMeta)): @property def event_type(self): return DATASOURCE_TYPE.TRADE @property def mapping(self): """ Mappings of the form: target_key: (mapping_function, source_key) """ return {} @abstractproperty def raw_data(self): """ An iterator that yields the raw datasource, in chronological order of data, one event at a time. """ NotImplemented @abstractproperty def instance_hash(self): """ A hash that represents the unique args to the source. """ pass def get_hash(self): return self.__class__.__name__ + "-" + self.instance_hash def apply_mapping(self, raw_row): """ Override this to hand craft conversion of row. """ row = {} row.update({'type': self.event_type}) row.update({target: mapping_func(raw_row[source_key]) for target, (mapping_func, source_key) in self.mapping.items()}) row.update({'source_id': self.get_hash()}) return row @property def mapped_data(self): for row in self.raw_data: yield Event(self.apply_mapping(row)) def __iter__(self): return self def next(self): return self.mapped_data.next() def __next__(self): return next(self.mapped_data)
apache-2.0
edbrannin/robotframework
atest/testresources/listeners/OldListenAll.py
28
1591
import os class OldListenAll: def __init__(self, *path): if not path: path = os.path.join(os.getenv('TEMPDIR'), 'listen_all.txt') else: path = ':'.join(path) self.outfile = open(path, 'w') def start_suite(self, name, doc): self.outfile.write("SUITE START: %s '%s'\n" % (name, doc)) def start_test(self, name, doc, tags): tags = [str(tag) for tag in tags] self.outfile.write("TEST START: %s '%s' %s\n" % (name, doc, tags)) def start_keyword(self, name, args): args = [str(arg) for arg in args] self.outfile.write("KW START: %s %s\n" % (name, args)) def end_keyword(self, status): self.outfile.write("KW END: %s\n" % (status)) def end_test(self, status, message): if status == 'PASS': self.outfile.write('TEST END: PASS\n') else: self.outfile.write("TEST END: %s %s\n" % (status, message)) def end_suite(self, status, message): self.outfile.write('SUITE END: %s %s\n' % (status, message)) def output_file(self, path): self._out_file('Output', path) def report_file(self, path): self._out_file('Report', path) def log_file(self, path): self._out_file('Log', path) def debug_file(self, path): self._out_file('Debug', path) def _out_file(self, name, path): assert os.path.isabs(path) self.outfile.write('%s: %s\n' % (name, os.path.basename(path))) def close(self): self.outfile.write('Closing...\n') self.outfile.close()
apache-2.0
pkilambi/ceilometer
ceilometer/tests/alarm/evaluator/test_threshold.py
2
27889
# # Copyright 2013 Red Hat, 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. """Tests for ceilometer/alarm/evaluator/threshold.py """ import datetime import uuid from ceilometerclient import exc from ceilometerclient.v2 import statistics import mock from oslo_config import cfg from oslo_utils import timeutils import pytz from six import moves from ceilometer.alarm.evaluator import threshold from ceilometer.alarm.storage import models from ceilometer.tests.alarm.evaluator import base from ceilometer.tests import constants class TestEvaluate(base.TestEvaluatorBase): EVALUATOR = threshold.ThresholdEvaluator def prepare_alarms(self): self.alarms = [ models.Alarm(name='instance_running_hot', description='instance_running_hot', type='threshold', enabled=True, user_id='foobar', project_id='snafu', alarm_id=str(uuid.uuid4()), state='insufficient data', state_timestamp=constants.MIN_DATETIME, timestamp=constants.MIN_DATETIME, insufficient_data_actions=[], ok_actions=[], alarm_actions=[], repeat_actions=False, time_constraints=[], rule=dict( comparison_operator='gt', threshold=80.0, evaluation_periods=5, statistic='avg', period=60, meter_name='cpu_util', query=[{'field': 'meter', 'op': 'eq', 'value': 'cpu_util'}, {'field': 'resource_id', 'op': 'eq', 'value': 'my_instance'}]), severity='critical' ), models.Alarm(name='group_running_idle', description='group_running_idle', type='threshold', enabled=True, user_id='foobar', project_id='snafu', state='insufficient data', state_timestamp=constants.MIN_DATETIME, timestamp=constants.MIN_DATETIME, insufficient_data_actions=[], ok_actions=[], alarm_actions=[], repeat_actions=False, alarm_id=str(uuid.uuid4()), time_constraints=[], rule=dict( comparison_operator='le', threshold=10.0, evaluation_periods=4, statistic='max', period=300, meter_name='cpu_util', query=[{'field': 'meter', 'op': 'eq', 'value': 'cpu_util'}, {'field': 'metadata.user_metadata.AS', 'op': 'eq', 'value': 'my_group'}]), severity='critical' ), ] @staticmethod def _get_stat(attr, value, count=1): return statistics.Statistics(None, {attr: value, 'count': count}) @staticmethod def _reason_data(disposition, count, most_recent): return {'type': 'threshold', 'disposition': disposition, 'count': count, 'most_recent': most_recent} def _set_all_rules(self, field, value): for alarm in self.alarms: alarm.rule[field] = value def test_retry_transient_api_failure(self): with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): broken = exc.CommunicationError(message='broken') avgs = [self._get_stat('avg', self.alarms[0].rule['threshold'] - v) for v in moves.xrange(5)] maxs = [self._get_stat('max', self.alarms[1].rule['threshold'] + v) for v in moves.xrange(1, 5)] self.api_client.statistics.list.side_effect = [broken, broken, avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('insufficient data') self._evaluate_all_alarms() self._assert_all_alarms('ok') def test_simple_insufficient(self): self._set_all_alarms('ok') with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): self.api_client.statistics.list.return_value = [] self._evaluate_all_alarms() self._assert_all_alarms('insufficient data') expected = [mock.call(alarm.alarm_id, state='insufficient data') for alarm in self.alarms] update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual(expected, update_calls) expected = [mock.call( alarm, 'ok', ('%d datapoints are unknown' % alarm.rule['evaluation_periods']), self._reason_data('unknown', alarm.rule['evaluation_periods'], None)) for alarm in self.alarms] self.assertEqual(expected, self.notifier.notify.call_args_list) def test_less_insufficient_data(self): self._set_all_alarms('ok') with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): avgs = [self._get_stat('avg', self.alarms[0].rule['threshold'] - v) for v in moves.xrange(4)] maxs = [self._get_stat('max', self.alarms[1].rule['threshold'] - v) for v in moves.xrange(1, 4)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('insufficient data') expected = [mock.call(alarm.alarm_id, state='insufficient data') for alarm in self.alarms] update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual(update_calls, expected) expected = [mock.call( alarm, 'ok', ('%d datapoints are unknown' % alarm.rule['evaluation_periods']), self._reason_data('unknown', alarm.rule['evaluation_periods'], alarm.rule['threshold'] - 3)) for alarm in self.alarms] self.assertEqual(expected, self.notifier.notify.call_args_list) def test_simple_alarm_trip(self): self._set_all_alarms('ok') with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): avgs = [self._get_stat('avg', self.alarms[0].rule['threshold'] + v) for v in moves.xrange(1, 6)] maxs = [self._get_stat('max', self.alarms[1].rule['threshold'] - v) for v in moves.xrange(4)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('alarm') expected = [mock.call(alarm.alarm_id, state='alarm') for alarm in self.alarms] update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual(expected, update_calls) reasons = ['Transition to alarm due to 5 samples outside' ' threshold, most recent: %s' % avgs[-1].avg, 'Transition to alarm due to 4 samples outside' ' threshold, most recent: %s' % maxs[-1].max] reason_datas = [self._reason_data('outside', 5, avgs[-1].avg), self._reason_data('outside', 4, maxs[-1].max)] expected = [mock.call(alarm, 'ok', reason, reason_data) for alarm, reason, reason_data in zip(self.alarms, reasons, reason_datas)] self.assertEqual(expected, self.notifier.notify.call_args_list) def test_simple_alarm_clear(self): self._set_all_alarms('alarm') with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): avgs = [self._get_stat('avg', self.alarms[0].rule['threshold'] - v) for v in moves.xrange(5)] maxs = [self._get_stat('max', self.alarms[1].rule['threshold'] + v) for v in moves.xrange(1, 5)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('ok') expected = [mock.call(alarm.alarm_id, state='ok') for alarm in self.alarms] update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual(expected, update_calls) reasons = ['Transition to ok due to 5 samples inside' ' threshold, most recent: %s' % avgs[-1].avg, 'Transition to ok due to 4 samples inside' ' threshold, most recent: %s' % maxs[-1].max] reason_datas = [self._reason_data('inside', 5, avgs[-1].avg), self._reason_data('inside', 4, maxs[-1].max)] expected = [mock.call(alarm, 'alarm', reason, reason_data) for alarm, reason, reason_data in zip(self.alarms, reasons, reason_datas)] self.assertEqual(expected, self.notifier.notify.call_args_list) def test_equivocal_from_known_state(self): self._set_all_alarms('ok') with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): avgs = [self._get_stat('avg', self.alarms[0].rule['threshold'] + v) for v in moves.xrange(5)] maxs = [self._get_stat('max', self.alarms[1].rule['threshold'] - v) for v in moves.xrange(-1, 3)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('ok') self.assertEqual( [], self.api_client.alarms.set_state.call_args_list) self.assertEqual([], self.notifier.notify.call_args_list) def test_equivocal_from_known_state_and_repeat_actions(self): self._set_all_alarms('ok') self.alarms[1].repeat_actions = True with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): avgs = [self._get_stat('avg', self.alarms[0].rule['threshold'] + v) for v in moves.xrange(5)] maxs = [self._get_stat('max', self.alarms[1].rule['threshold'] - v) for v in moves.xrange(-1, 3)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('ok') self.assertEqual([], self.api_client.alarms.set_state.call_args_list) reason = ('Remaining as ok due to 4 samples inside' ' threshold, most recent: 8.0') reason_datas = self._reason_data('inside', 4, 8.0) expected = [mock.call(self.alarms[1], 'ok', reason, reason_datas)] self.assertEqual(expected, self.notifier.notify.call_args_list) def test_unequivocal_from_known_state_and_repeat_actions(self): self._set_all_alarms('alarm') self.alarms[1].repeat_actions = True with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): avgs = [self._get_stat('avg', self.alarms[0].rule['threshold'] + v) for v in moves.xrange(1, 6)] maxs = [self._get_stat('max', self.alarms[1].rule['threshold'] - v) for v in moves.xrange(4)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('alarm') self.assertEqual([], self.api_client.alarms.set_state.call_args_list) reason = ('Remaining as alarm due to 4 samples outside' ' threshold, most recent: 7.0') reason_datas = self._reason_data('outside', 4, 7.0) expected = [mock.call(self.alarms[1], 'alarm', reason, reason_datas)] self.assertEqual(expected, self.notifier.notify.call_args_list) def test_state_change_and_repeat_actions(self): self._set_all_alarms('ok') self.alarms[0].repeat_actions = True self.alarms[1].repeat_actions = True with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): avgs = [self._get_stat('avg', self.alarms[0].rule['threshold'] + v) for v in moves.xrange(1, 6)] maxs = [self._get_stat('max', self.alarms[1].rule['threshold'] - v) for v in moves.xrange(4)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('alarm') expected = [mock.call(alarm.alarm_id, state='alarm') for alarm in self.alarms] update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual(expected, update_calls) reasons = ['Transition to alarm due to 5 samples outside' ' threshold, most recent: %s' % avgs[-1].avg, 'Transition to alarm due to 4 samples outside' ' threshold, most recent: %s' % maxs[-1].max] reason_datas = [self._reason_data('outside', 5, avgs[-1].avg), self._reason_data('outside', 4, maxs[-1].max)] expected = [mock.call(alarm, 'ok', reason, reason_data) for alarm, reason, reason_data in zip(self.alarms, reasons, reason_datas)] self.assertEqual(expected, self.notifier.notify.call_args_list) def test_equivocal_from_unknown(self): self._set_all_alarms('insufficient data') with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): avgs = [self._get_stat('avg', self.alarms[0].rule['threshold'] + v) for v in moves.xrange(1, 6)] maxs = [self._get_stat('max', self.alarms[1].rule['threshold'] - v) for v in moves.xrange(4)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('alarm') expected = [mock.call(alarm.alarm_id, state='alarm') for alarm in self.alarms] update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual(expected, update_calls) reasons = ['Transition to alarm due to 5 samples outside' ' threshold, most recent: %s' % avgs[-1].avg, 'Transition to alarm due to 4 samples outside' ' threshold, most recent: %s' % maxs[-1].max] reason_datas = [self._reason_data('outside', 5, avgs[-1].avg), self._reason_data('outside', 4, maxs[-1].max)] expected = [mock.call(alarm, 'insufficient data', reason, reason_data) for alarm, reason, reason_data in zip(self.alarms, reasons, reason_datas)] self.assertEqual(expected, self.notifier.notify.call_args_list) def _do_test_bound_duration(self, start, exclude_outliers=None): alarm = self.alarms[0] if exclude_outliers is not None: alarm.rule['exclude_outliers'] = exclude_outliers with mock.patch.object(timeutils, 'utcnow') as mock_utcnow: mock_utcnow.return_value = datetime.datetime(2012, 7, 2, 10, 45) constraint = self.evaluator._bound_duration(alarm, []) self.assertEqual([ {'field': 'timestamp', 'op': 'le', 'value': timeutils.utcnow().isoformat()}, {'field': 'timestamp', 'op': 'ge', 'value': start}, ], constraint) def test_bound_duration_outlier_exclusion_defaulted(self): self._do_test_bound_duration('2012-07-02T10:39:00') def test_bound_duration_outlier_exclusion_clear(self): self._do_test_bound_duration('2012-07-02T10:39:00', False) def test_bound_duration_outlier_exclusion_set(self): self._do_test_bound_duration('2012-07-02T10:35:00', True) def test_threshold_endpoint_types(self): endpoint_types = ["internalURL", "publicURL"] for endpoint_type in endpoint_types: cfg.CONF.set_override('os_endpoint_type', endpoint_type, group='service_credentials') with mock.patch('ceilometerclient.client.get_client') as client: self.evaluator.api_client = None self._evaluate_all_alarms() conf = cfg.CONF.service_credentials expected = [mock.call(2, os_auth_url=conf.os_auth_url, os_region_name=conf.os_region_name, os_tenant_name=conf.os_tenant_name, os_password=conf.os_password, os_username=conf.os_username, os_cacert=conf.os_cacert, os_endpoint_type=conf.os_endpoint_type, timeout=cfg.CONF.http_timeout, insecure=conf.insecure)] actual = client.call_args_list self.assertEqual(expected, actual) def _do_test_simple_alarm_trip_outlier_exclusion(self, exclude_outliers): self._set_all_rules('exclude_outliers', exclude_outliers) self._set_all_alarms('ok') with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): # most recent datapoints inside threshold but with # anomalously low sample count threshold = self.alarms[0].rule['threshold'] avgs = [self._get_stat('avg', threshold + (v if v < 10 else -v), count=20 if v < 10 else 1) for v in moves.xrange(1, 11)] threshold = self.alarms[1].rule['threshold'] maxs = [self._get_stat('max', threshold - (v if v < 7 else -v), count=20 if v < 7 else 1) for v in moves.xrange(8)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('alarm' if exclude_outliers else 'ok') if exclude_outliers: expected = [mock.call(alarm.alarm_id, state='alarm') for alarm in self.alarms] update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual(expected, update_calls) reasons = ['Transition to alarm due to 5 samples outside' ' threshold, most recent: %s' % avgs[-2].avg, 'Transition to alarm due to 4 samples outside' ' threshold, most recent: %s' % maxs[-2].max] reason_datas = [self._reason_data('outside', 5, avgs[-2].avg), self._reason_data('outside', 4, maxs[-2].max)] expected = [mock.call(alarm, 'ok', reason, reason_data) for alarm, reason, reason_data in zip(self.alarms, reasons, reason_datas)] self.assertEqual(expected, self.notifier.notify.call_args_list) def test_simple_alarm_trip_with_outlier_exclusion(self): self. _do_test_simple_alarm_trip_outlier_exclusion(True) def test_simple_alarm_no_trip_without_outlier_exclusion(self): self. _do_test_simple_alarm_trip_outlier_exclusion(False) def _do_test_simple_alarm_clear_outlier_exclusion(self, exclude_outliers): self._set_all_rules('exclude_outliers', exclude_outliers) self._set_all_alarms('alarm') with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): # most recent datapoints outside threshold but with # anomalously low sample count threshold = self.alarms[0].rule['threshold'] avgs = [self._get_stat('avg', threshold - (v if v < 9 else -v), count=20 if v < 9 else 1) for v in moves.xrange(10)] threshold = self.alarms[1].rule['threshold'] maxs = [self._get_stat('max', threshold + (v if v < 8 else -v), count=20 if v < 8 else 1) for v in moves.xrange(1, 9)] self.api_client.statistics.list.side_effect = [avgs, maxs] self._evaluate_all_alarms() self._assert_all_alarms('ok' if exclude_outliers else 'alarm') if exclude_outliers: expected = [mock.call(alarm.alarm_id, state='ok') for alarm in self.alarms] update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual(expected, update_calls) reasons = ['Transition to ok due to 5 samples inside' ' threshold, most recent: %s' % avgs[-2].avg, 'Transition to ok due to 4 samples inside' ' threshold, most recent: %s' % maxs[-2].max] reason_datas = [self._reason_data('inside', 5, avgs[-2].avg), self._reason_data('inside', 4, maxs[-2].max)] expected = [mock.call(alarm, 'alarm', reason, reason_data) for alarm, reason, reason_data in zip(self.alarms, reasons, reason_datas)] self.assertEqual(expected, self.notifier.notify.call_args_list) def test_simple_alarm_clear_with_outlier_exclusion(self): self. _do_test_simple_alarm_clear_outlier_exclusion(True) def test_simple_alarm_no_clear_without_outlier_exclusion(self): self. _do_test_simple_alarm_clear_outlier_exclusion(False) @mock.patch.object(timeutils, 'utcnow') def test_state_change_inside_time_constraint(self, mock_utcnow): self._set_all_alarms('ok') self.alarms[0].time_constraints = [ {'name': 'test', 'description': 'test', 'start': '0 11 * * *', # daily at 11:00 'duration': 10800, # 3 hours 'timezone': 'Europe/Ljubljana'} ] self.alarms[1].time_constraints = self.alarms[0].time_constraints dt = datetime.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('Europe/Ljubljana')) mock_utcnow.return_value = dt.astimezone(pytz.UTC) with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): # the following part based on test_simple_insufficient self.api_client.statistics.list.return_value = [] self._evaluate_all_alarms() self._assert_all_alarms('insufficient data') expected = [mock.call(alarm.alarm_id, state='insufficient data') for alarm in self.alarms] update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual(expected, update_calls, "Alarm should change state if the current " "time is inside its time constraint.") expected = [mock.call( alarm, 'ok', ('%d datapoints are unknown' % alarm.rule['evaluation_periods']), self._reason_data('unknown', alarm.rule['evaluation_periods'], None)) for alarm in self.alarms] self.assertEqual(expected, self.notifier.notify.call_args_list) @mock.patch.object(timeutils, 'utcnow') def test_no_state_change_outside_time_constraint(self, mock_utcnow): self._set_all_alarms('ok') self.alarms[0].time_constraints = [ {'name': 'test', 'description': 'test', 'start': '0 11 * * *', # daily at 11:00 'duration': 10800, # 3 hours 'timezone': 'Europe/Ljubljana'} ] self.alarms[1].time_constraints = self.alarms[0].time_constraints dt = datetime.datetime(2014, 1, 1, 15, 0, 0, tzinfo=pytz.timezone('Europe/Ljubljana')) mock_utcnow.return_value = dt.astimezone(pytz.UTC) with mock.patch('ceilometerclient.client.get_client', return_value=self.api_client): self.api_client.statistics.list.return_value = [] self._evaluate_all_alarms() self._assert_all_alarms('ok') update_calls = self.api_client.alarms.set_state.call_args_list self.assertEqual([], update_calls, "Alarm should not change state if the current " " time is outside its time constraint.") self.assertEqual([], self.notifier.notify.call_args_list)
apache-2.0
kubeflow/fairing
containerregistry/client/v1/save_.py
2
3111
# Copyright 2017 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 package provides tools for saving docker images.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import json import tarfile from containerregistry.client import docker_name from containerregistry.client.v1 import docker_image import six def multi_image_tarball( tag_to_image, tar): """Produce a "docker save" compatible tarball from the DockerImages. Args: tag_to_image: A dictionary of tags to the images they label. tar: the open tarfile into which we are writing the image tarball. """ def add_file(filename, contents): info = tarfile.TarInfo(filename) info.size = len(contents) tar.addfile(tarinfo=info, fileobj=io.BytesIO(contents)) seen = set() repositories = {} # Each layer is encoded as a directory in the larger tarball of the form: # {layer_id}\ # layer.tar # VERSION # json for (tag, image) in six.iteritems(tag_to_image): # Add this image's repositories entry. repo = str(tag.as_repository()) tags = repositories.get(repo, {}) tags[tag.tag] = image.top() repositories[repo] = tags for layer_id in image.ancestry(image.top()): # Add each layer_id exactly once. if layer_id in seen or json.loads(image.json(layer_id)).get('throwaway'): continue seen.add(layer_id) # VERSION generally seems to contain 1.0, not entirely sure # what the point of this is. add_file(layer_id + '/VERSION', b'1.0') # Add the unzipped layer tarball content = image.uncompressed_layer(layer_id) add_file(layer_id + '/layer.tar', content) # Now the json metadata add_file(layer_id + '/json', image.json(layer_id).encode('utf8')) # Add the metadata tagging the top layer. add_file('repositories', json.dumps(repositories, sort_keys=True).encode('utf8')) def tarball(name, image, tar): """Produce a "docker save" compatible tarball from the DockerImage. Args: name: The tag name to write into the repositories file. image: a docker image to save. tar: the open tarfile into which we are writing the image tarball. """ def add_file(filename, contents): info = tarfile.TarInfo(filename) info.size = len(contents) tar.addfile(tarinfo=info, fileobj=io.BytesIO(contents)) multi_image_tarball({name: image}, tar) # Add our convenience file with the top layer's ID. add_file('top', image.top().encode('utf8'))
apache-2.0
xen0l/ansible
lib/ansible/modules/network/protocol/net_lldp.py
104
1224
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = """ --- module: net_lldp version_added: "2.4" author: "Ricardo Carrillo Cruz (@rcarrillocruz)" short_description: Manage LLDP service configuration on network devices description: - This module provides declarative management of LLDP service configuration on network devices. options: state: description: - State of the LLDP service configuration. default: present choices: ['present', 'absent'] """ EXAMPLES = """ - name: Enable LLDP service net_lldp: state: present - name: Disable LLDP service net_lldp: state: lldp """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always, except for the platforms that use Netconf transport to manage the device. type: list sample: - set service lldp """
gpl-3.0
kenshay/ImageScripter
ProgramData/SystemFiles/Python/Lib/site-packages/setuptools/ssl_support.py
104
8220
import os import socket import atexit import re import functools from setuptools.extern.six.moves import urllib, http_client, map, filter from pkg_resources import ResolutionError, ExtractionError try: import ssl except ImportError: ssl = None __all__ = [ 'VerifyingHTTPSHandler', 'find_ca_bundle', 'is_available', 'cert_paths', 'opener_for' ] cert_paths = """ /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/certs/ca-certificates.crt /usr/share/ssl/certs/ca-bundle.crt /usr/local/share/certs/ca-root.crt /etc/ssl/cert.pem /System/Library/OpenSSL/certs/cert.pem /usr/local/share/certs/ca-root-nss.crt /etc/ssl/ca-bundle.pem """.strip().split() try: HTTPSHandler = urllib.request.HTTPSHandler HTTPSConnection = http_client.HTTPSConnection except AttributeError: HTTPSHandler = HTTPSConnection = object is_available = ssl is not None and object not in (HTTPSHandler, HTTPSConnection) try: from ssl import CertificateError, match_hostname except ImportError: try: from backports.ssl_match_hostname import CertificateError from backports.ssl_match_hostname import match_hostname except ImportError: CertificateError = None match_hostname = None if not CertificateError: class CertificateError(ValueError): pass if not match_hostname: def _dnsname_match(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False # Ported from python3-syntax: # leftmost, *remainder = dn.split(r'.') parts = dn.split(r'.') leftmost = parts[0] remainder = parts[1:] wildcards = leftmost.count('*') if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing more # than one wildcard per fragment. A survey of established # policy among SSL implementations showed it to be a # reasonable choice. raise CertificateError( "too many wildcards in certificate DNS name: " + repr(dn)) # speed up common case w/o wildcards if not wildcards: return dn.lower() == hostname.lower() # RFC 6125, section 6.4.3, subitem 1. # The client SHOULD NOT attempt to match a presented identifier in which # the wildcard character comprises a label other than the left-most label. if leftmost == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append('[^.]+') elif leftmost.startswith('xn--') or hostname.startswith('xn--'): # RFC 6125, section 6.4.3, subitem 3. # The client SHOULD NOT attempt to match a presented identifier # where the wildcard character is embedded within an A-label or # U-label of an internationalized domain name. pats.append(re.escape(leftmost)) else: # Otherwise, '*' matches any dotless string, e.g. www* pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) # add the remaining fragments, ignore any wildcards for frag in remainder: pats.append(re.escape(frag)) pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) return pat.match(hostname) def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError("empty or no certificate") dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if _dnsname_match(value, hostname): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get('subject', ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == 'commonName': if _dnsname_match(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError("hostname %r " "doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames)))) elif len(dnsnames) == 1: raise CertificateError("hostname %r " "doesn't match %r" % (hostname, dnsnames[0])) else: raise CertificateError("no appropriate commonName or " "subjectAltName fields were found") class VerifyingHTTPSHandler(HTTPSHandler): """Simple verifying handler: no auth, subclasses, timeouts, etc.""" def __init__(self, ca_bundle): self.ca_bundle = ca_bundle HTTPSHandler.__init__(self) def https_open(self, req): return self.do_open( lambda host, **kw: VerifyingHTTPSConn(host, self.ca_bundle, **kw), req ) class VerifyingHTTPSConn(HTTPSConnection): """Simple verifying connection: no auth, subclasses, timeouts, etc.""" def __init__(self, host, ca_bundle, **kw): HTTPSConnection.__init__(self, host, **kw) self.ca_bundle = ca_bundle def connect(self): sock = socket.create_connection( (self.host, self.port), getattr(self, 'source_address', None) ) # Handle the socket if a (proxy) tunnel is present if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None): self.sock = sock self._tunnel() # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7 # change self.host to mean the proxy server host when tunneling is # being used. Adapt, since we are interested in the destination # host for the match_hostname() comparison. actual_host = self._tunnel_host else: actual_host = self.host self.sock = ssl.wrap_socket( sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle ) try: match_hostname(self.sock.getpeercert(), actual_host) except CertificateError: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() raise def opener_for(ca_bundle=None): """Get a urlopen() replacement that uses ca_bundle for verification""" return urllib.request.build_opener( VerifyingHTTPSHandler(ca_bundle or find_ca_bundle()) ).open # from jaraco.functools def once(func): @functools.wraps(func) def wrapper(*args, **kwargs): if not hasattr(func, 'always_returns'): func.always_returns = func(*args, **kwargs) return func.always_returns return wrapper @once def get_win_certfile(): try: import wincertstore except ImportError: return None class CertFile(wincertstore.CertFile): def __init__(self): super(CertFile, self).__init__() atexit.register(self.close) def close(self): try: super(CertFile, self).close() except OSError: pass _wincerts = CertFile() _wincerts.addstore('CA') _wincerts.addstore('ROOT') return _wincerts.name def find_ca_bundle(): """Return an existing CA bundle path, or None""" extant_cert_paths = filter(os.path.isfile, cert_paths) return ( get_win_certfile() or next(extant_cert_paths, None) or _certifi_where() ) def _certifi_where(): try: return __import__('certifi').where() except (ImportError, ResolutionError, ExtractionError): pass
gpl-3.0
yland/mailman3
src/mailman/model/tests/test_member.py
7
4281
# Copyright (C) 2011-2015 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Test members.""" __all__ = [ 'TestMember', ] import unittest from mailman.app.lifecycle import create_list from mailman.interfaces.member import MemberRole, MembershipError from mailman.interfaces.user import UnverifiedAddressError from mailman.interfaces.usermanager import IUserManager from mailman.model.member import Member from mailman.testing.layers import ConfigLayer from mailman.utilities.datetime import now from zope.component import getUtility class TestMember(unittest.TestCase): layer = ConfigLayer def setUp(self): self._mlist = create_list('test@example.com') self._usermanager = getUtility(IUserManager) def test_cannot_set_address_with_preferred_address_subscription(self): # A user is subscribed to a mailing list with their preferred address. # You cannot set the `address` attribute on such IMembers. anne = self._usermanager.create_user('anne@example.com') preferred = list(anne.addresses)[0] preferred.verified_on = now() anne.preferred_address = preferred # Subscribe with the IUser object, not the address. This makes Anne a # member via her preferred address. member = self._mlist.subscribe(anne) new_address = anne.register('aperson@example.com') new_address.verified_on = now() self.assertRaises(MembershipError, setattr, member, 'address', new_address) def test_cannot_change_to_unverified_address(self): # A user is subscribed to a mailing list with an explicit address. # You cannot set the `address` attribute to an unverified address. anne = self._usermanager.create_user('anne@example.com') address = list(anne.addresses)[0] member = self._mlist.subscribe(address) new_address = anne.register('aperson@example.com') # The new address is not verified. self.assertRaises(UnverifiedAddressError, setattr, member, 'address', new_address) def test_cannot_change_to_address_uncontrolled_address(self): # A user tries to change their subscription to an address they do not # control. anne = self._usermanager.create_user('anne@example.com') address = list(anne.addresses)[0] member = self._mlist.subscribe(address) new_address = self._usermanager.create_address('nobody@example.com') new_address.verified_on = now() # The new address is not verified. self.assertRaises(MembershipError, setattr, member, 'address', new_address) def test_cannot_change_to_address_controlled_by_other_user(self): # A user tries to change their subscription to an address some other # user controls. anne = self._usermanager.create_user('anne@example.com') anne_address = list(anne.addresses)[0] bart = self._usermanager.create_user('bart@example.com') bart_address = list(bart.addresses)[0] bart_address.verified_on = now() member = self._mlist.subscribe(anne_address) # The new address is not verified. self.assertRaises(MembershipError, setattr, member, 'address', bart_address) def test_member_ctor_value_error(self): # ValueError when passing in anything but a user or address. self.assertRaises(ValueError, Member, MemberRole.member, self._mlist.list_id, 'aperson@example.com')
gpl-2.0
nilmini20s/gem5-2016-08-13
src/mem/slicc/ast/PairAST.py
92
1810
# Copyright (c) 2009 The Hewlett-Packard Development Company # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.AST import AST class PairAST(AST): def __init__(self, slicc, key, value): super(PairAST, self).__init__(slicc) self.key = key self.value = value def __repr__(self): return '[%s=%s]' % (self.key, self.value)
bsd-3-clause
georgemarshall/bigcouch
couchjs/scons/scons-local-2.0.1/SCons/Tool/CVS.py
61
2912
"""SCons.Tool.CVS.py Tool-specific initialization for CVS. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # 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. __revision__ = "src/engine/SCons/Tool/CVS.py 5134 2010/08/16 23:02:40 bdeegan" import SCons.Action import SCons.Builder import SCons.Util def generate(env): """Add a Builder factory function and construction variables for CVS to an Environment.""" def CVSFactory(repos, module='', env=env): """ """ import SCons.Warnings as W W.warn(W.DeprecatedSourceCodeWarning, """The CVS() factory is deprecated and there is no replacement.""") # fail if repos is not an absolute path name? if module != '': # Don't use os.path.join() because the name we fetch might # be across a network and must use POSIX slashes as separators. module = module + '/' env['CVSCOM'] = '$CVS $CVSFLAGS co $CVSCOFLAGS -d ${TARGET.dir} $CVSMODULE${TARGET.posix}' act = SCons.Action.Action('$CVSCOM', '$CVSCOMSTR') return SCons.Builder.Builder(action = act, env = env, CVSREPOSITORY = repos, CVSMODULE = module) #setattr(env, 'CVS', CVSFactory) env.CVS = CVSFactory env['CVS'] = 'cvs' env['CVSFLAGS'] = SCons.Util.CLVar('-d $CVSREPOSITORY') env['CVSCOFLAGS'] = SCons.Util.CLVar('') env['CVSCOM'] = '$CVS $CVSFLAGS co $CVSCOFLAGS ${TARGET.posix}' def exists(env): return env.Detect('cvs') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
apache-2.0
kevinr/750book-web
750book-web-env/lib/python2.7/site-packages/django/contrib/gis/gdal/layer.py
401
8489
# Needed ctypes routines from ctypes import c_double, byref # Other GDAL imports. from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope from django.contrib.gis.gdal.error import OGRException, OGRIndexError, SRSException from django.contrib.gis.gdal.feature import Feature from django.contrib.gis.gdal.field import OGRFieldTypes from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.geometries import OGRGeometry from django.contrib.gis.gdal.srs import SpatialReference # GDAL ctypes function prototypes. from django.contrib.gis.gdal.prototypes import ds as capi, geom as geom_api, srs as srs_api # For more information, see the OGR C API source code: # http://www.gdal.org/ogr/ogr__api_8h.html # # The OGR_L_* routines are relevant here. class Layer(GDALBase): "A class that wraps an OGR Layer, needs to be instantiated from a DataSource object." #### Python 'magic' routines #### def __init__(self, layer_ptr, ds): """ Initializes on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active. """ if not layer_ptr: raise OGRException('Cannot create Layer, invalid pointer given') self.ptr = layer_ptr self._ds = ds self._ldefn = capi.get_layer_defn(self._ptr) # Does the Layer support random reading? self._random_read = self.test_capability('RandomRead') def __getitem__(self, index): "Gets the Feature at the specified index." if isinstance(index, (int, long)): # An integer index was given -- we cannot do a check based on the # number of features because the beginning and ending feature IDs # are not guaranteed to be 0 and len(layer)-1, respectively. if index < 0: raise OGRIndexError('Negative indices are not allowed on OGR Layers.') return self._make_feature(index) elif isinstance(index, slice): # A slice was given start, stop, stride = index.indices(self.num_feat) return [self._make_feature(fid) for fid in xrange(start, stop, stride)] else: raise TypeError('Integers and slices may only be used when indexing OGR Layers.') def __iter__(self): "Iterates over each Feature in the Layer." # ResetReading() must be called before iteration is to begin. capi.reset_reading(self._ptr) for i in xrange(self.num_feat): yield Feature(capi.get_next_feature(self._ptr), self._ldefn) def __len__(self): "The length is the number of features." return self.num_feat def __str__(self): "The string name of the layer." return self.name def _make_feature(self, feat_id): """ Helper routine for __getitem__ that constructs a Feature from the given Feature ID. If the OGR Layer does not support random-access reading, then each feature of the layer will be incremented through until the a Feature is found matching the given feature ID. """ if self._random_read: # If the Layer supports random reading, return. try: return Feature(capi.get_feature(self.ptr, feat_id), self._ldefn) except OGRException: pass else: # Random access isn't supported, have to increment through # each feature until the given feature ID is encountered. for feat in self: if feat.fid == feat_id: return feat # Should have returned a Feature, raise an OGRIndexError. raise OGRIndexError('Invalid feature id: %s.' % feat_id) #### Layer properties #### @property def extent(self): "Returns the extent (an Envelope) of this layer." env = OGREnvelope() capi.get_extent(self.ptr, byref(env), 1) return Envelope(env) @property def name(self): "Returns the name of this layer in the Data Source." return capi.get_fd_name(self._ldefn) @property def num_feat(self, force=1): "Returns the number of features in the Layer." return capi.get_feature_count(self.ptr, force) @property def num_fields(self): "Returns the number of fields in the Layer." return capi.get_field_count(self._ldefn) @property def geom_type(self): "Returns the geometry type (OGRGeomType) of the Layer." return OGRGeomType(capi.get_fd_geom_type(self._ldefn)) @property def srs(self): "Returns the Spatial Reference used in this Layer." try: ptr = capi.get_layer_srs(self.ptr) return SpatialReference(srs_api.clone_srs(ptr)) except SRSException: return None @property def fields(self): """ Returns a list of string names corresponding to each of the Fields available in this Layer. """ return [capi.get_field_name(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields) ] @property def field_types(self): """ Returns a list of the types of fields in this Layer. For example, the list [OFTInteger, OFTReal, OFTString] would be returned for an OGR layer that had an integer, a floating-point, and string fields. """ return [OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))] for i in xrange(self.num_fields)] @property def field_widths(self): "Returns a list of the maximum field widths for the features." return [capi.get_field_width(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields)] @property def field_precisions(self): "Returns the field precisions for the features." return [capi.get_field_precision(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields)] def _get_spatial_filter(self): try: return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr))) except OGRException: return None def _set_spatial_filter(self, filter): if isinstance(filter, OGRGeometry): capi.set_spatial_filter(self.ptr, filter.ptr) elif isinstance(filter, (tuple, list)): if not len(filter) == 4: raise ValueError('Spatial filter list/tuple must have 4 elements.') # Map c_double onto params -- if a bad type is passed in it # will be caught here. xmin, ymin, xmax, ymax = map(c_double, filter) capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax) elif filter is None: capi.set_spatial_filter(self.ptr, None) else: raise TypeError('Spatial filter must be either an OGRGeometry instance, a 4-tuple, or None.') spatial_filter = property(_get_spatial_filter, _set_spatial_filter) #### Layer Methods #### def get_fields(self, field_name): """ Returns a list containing the given field name for every Feature in the Layer. """ if not field_name in self.fields: raise OGRException('invalid field name: %s' % field_name) return [feat.get(field_name) for feat in self] def get_geoms(self, geos=False): """ Returns a list containing the OGRGeometry for every Feature in the Layer. """ if geos: from django.contrib.gis.geos import GEOSGeometry return [GEOSGeometry(feat.geom.wkb) for feat in self] else: return [feat.geom for feat in self] def test_capability(self, capability): """ Returns a bool indicating whether the this Layer supports the given capability (a string). Valid capability strings include: 'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter', 'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions', 'DeleteFeature', and 'FastSetNextByIndex'. """ return bool(capi.test_capability(self.ptr, capability))
mit
indera/redi
redi/batch.py
1
9666
""" Functions related to the RediBatch database """ __author__ = "University of Florida CTS-IT Team" __copyright__ = "Copyright 2014, University of Florida" __license__ = "BSD 3-Clause" import datetime import hashlib import logging import os import sqlite3 as lite import stat import sys import time from lxml import etree from utils import redi_email from utils.rawxml import RawXml logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) """ @see #check_input_file() The first time we run the app there is no SQLite file where to store the md5 sums of the input file. This function creates an empty RediBatch in the SQLite file specified as `db_path` @return True if the database file was properly created with an empty table """ def create_empty_md5_database(db_path) : if os.path.exists(db_path) : logger.warn('The file with name ' + db_path + ' already exists') #return try : logger.info('Opening the file:' + db_path) fresh_file = open(db_path, 'w') fresh_file.close() os.chmod(db_path, stat.S_IRUSR | stat.S_IWUSR) time.sleep(5) except IOError as e: logger.error("I/O error: " + e.strerror + ' for file: ' + db_path) return False success = create_empty_table(db_path) return success """ Helper for #create_empty_md5_database() """ def create_empty_table(db_path) : logger.info('exec create_empty_table') db = None try: db = lite.connect(db_path) cur = db.cursor() sql = """CREATE TABLE RediBatch ( rbID INTEGER PRIMARY KEY AUTOINCREMENT, rbStartTime TEXT NOT NULL, rbEndTime TEXT, rbStatus TEXT, rbMd5Sum TEXT NOT NULL ) """ cur.execute(sql) except lite.Error as e: logger.error("SQLite error in create_empty_table(): " + e.args[0]) return False finally: if db: db.close() logger.info('success create_empty_table') return True """ Use this function to set the `row_factory` attribute of the database connection """ def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d """ @see bin/redi.py#main() @return a dictionary representation of the batch row for the current run Check the md5sum of the input file - if the sum *has changed* then continue the data processing and store a row in the SQLite database with `batch status= batch_started/ batch_completed` - if the sum *did not change* then check the config option `batch_warning_days`: - if limit = -1 then continue execution (ignore the limit) - if days_passed > limit then stop the process and email the `redi_admin` """ def check_input_file(batch_warning_days, db_path, email_settings, raw_xml_file, project): batch = None if not os.path.exists(db_path) : create_empty_md5_database(db_path) new_md5ive = get_md5_input_file(raw_xml_file) new_msg = 'Using SQLite file: %s to store input file: %s md5 sum: %s' % ( db_path, raw_xml_file, new_md5ive) logger.info(new_msg) old_batch = get_last_batch(db_path) old_md5ive = None if old_batch: old_md5ive = old_batch['rbMd5Sum'] logger.info('Old md5 sum for the input file is: ' + old_md5ive) else: # this is the first time the checksum feature is used logger.info( "There is no old md5 recorded yet for the input file. Continue data import...") batch = add_batch_entry(db_path, new_md5ive) record_msg = 'Added batch (rbID= %s, rbStartTime= %s, rbMd5Sum= %s' % ( batch['rbID'], batch['rbStartTime'], batch['rbMd5Sum']) logger.info(record_msg) return batch if old_md5ive != new_md5ive: # the data has changed... insert a new batch entry batch = add_batch_entry(db_path, new_md5ive) record_msg = 'Added batch (rbID= %s, rbStartTime= %s, rbMd5Sum= %s' % ( batch['rbID'], batch['rbStartTime'], batch['rbMd5Sum']) logger.info(record_msg) return batch else: days_since_today = get_days_since_today(old_batch['rbStartTime']) # TODO: refactor code to use ConfigParser.RawConfigParser in order to # preserve data types if (days_since_today > int(batch_warning_days)): raw_xml = RawXml(project, raw_xml_file) msg_file_details = "\nXML file details: " + raw_xml.get_info() logger.info('Last import was started on: %s which is more than the limit of %s' % (old_batch['rbStartTime'], batch_warning_days)) if (-1 == int(batch_warning_days)): msg_continue = """ The configuration `batch_warning_days = -1` indicates that we want to continue execution even if the input file did not change """ + msg_file_details logger.info(msg_continue) else: msg_quit = "The input file did not change in the past: %s days. Stop data import." % batch_warning_days logger.critical(msg_quit + msg_file_details) redi_email.send_email_input_data_unchanged(email_settings, raw_xml) sys.exit() else: logger.info('Reusing md5 entry: ' + str(old_batch['rbID'])) # return the old batch so we can update the status return old_batch """ Retrieve the row corresponding to the last REDI batch completed """ def get_last_batch(db_path): db = None try: db = lite.connect(db_path) db.row_factory = dict_factory cur = db.cursor() sql = """ SELECT rbID, rbStartTime, rbEndTime, rbMd5Sum FROM RediBatch ORDER BY rbID DESC LIMIT 1 """ cur.execute(sql) batch = cur.fetchone() except lite.Error as e: logger.error("SQLite error in get_last_batch() for file %s - %s" % (db_path, e.args[0])) return None finally: if db: db.close() return batch """ Retrieve the row corresponding to the specified primary key """ def get_batch_by_id(db_path, batch_id): db = None try: db = lite.connect(db_path) db.row_factory = dict_factory cur = db.cursor() sql = """ SELECT rbID, rbStartTime, rbEndTime, rbMd5Sum FROM RediBatch WHERE rbID = ? LIMIT 1 """ cur.execute(sql, (str(batch_id), )) batch = cur.fetchone() except lite.Error as e: logger.exception("SQLite error in get_batch_by_id(): %s:" % e.args[0]) raise # sys.exit(1) finally: if db: db.close() return batch """ @see #check_input_file() @see https://docs.python.org/2/library/hashlib.html @see https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.row_factory Returns the md5 sum for the redi input file """ def get_md5_input_file(input_file): if not os.path.exists(input_file): raise Exception('Input file not found at: ' + input_file) logger.info('Computing md5 sum for: ' + input_file) # open the file in binary mode f = open(input_file, 'rb') chunk_size = 2 ** 20 md5 = hashlib.md5() # read the input file in 1MB pieces while True: chunk = f.read(chunk_size) if not chunk: break md5.update(chunk) return md5.hexdigest() """ @see #check_input_file() @param db_path - the SQLite file @param md5 - the md5 sum to be inserted """ def add_batch_entry(db_path, md5): logger.info('Execute: add_batch_entry()') batch = None db = None try: db = lite.connect(db_path) db.row_factory = dict_factory cur = db.cursor() sql = """ INSERT INTO RediBatch (rbStartTime, rbEndTime, rbStatus, rbMd5Sum) VALUES ( ?, NULL, 'Started', ?) """ now = get_db_friendly_date_time() cur.execute(sql, (now, md5)) rbID = cur.lastrowid db.commit() batch = get_batch_by_id(db_path, rbID) except lite.Error as e: logger.error("SQLite error in add_batch_entry() for file %s - %s" % (db_path, e.args[0])) return None finally: if db: db.close() return batch """ Update the status and the finish time of a specified batch entry in the SQLite db @return True if update succeeded, False otherwise """ def update_batch_entry(db_path, id, status, timestamp): success = None db = None try: db = lite.connect(db_path) cur = db.cursor() sql = """ UPDATE RediBatch SET rbEndTime = ? , rbStatus = ? WHERE rbID = ? """ cur.execute(sql, (timestamp, status, id)) db.commit() scuccess = True except lite.Error as e: logger.exception("SQLite error in update_batch_entry(): %s:" % e.args[0]) success = False finally: if db: db.close() return success """ @return string in format: "2014-06-24 01:23:24" """ def get_db_friendly_date_time(): return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') """ @return string in format: 2014-06-24 """ def get_db_friendly_date(): return datetime.date.today() """ @return the number of days passed since the specified date """ def get_days_since_today(date_string): num = None other = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S') now = datetime.datetime.now() delta = now - other return delta.days """ Helper function for debugging xml content """ def printxml(tree): print etree.tostring(tree, pretty_print = True) return
bsd-3-clause
memtoko/django
django/views/decorators/debug.py
712
2627
import functools from django.http import HttpRequest def sensitive_variables(*variables): """ Indicates which variables used in the decorated function are sensitive, so that those variables can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Two forms are accepted: * with specified variable names: @sensitive_variables('user', 'password', 'credit_card') def my_function(user): password = user.pass_word credit_card = user.credit_card_number ... * without any specified variable names, in which case it is assumed that all variables are considered sensitive: @sensitive_variables() def my_function() ... """ def decorator(func): @functools.wraps(func) def sensitive_variables_wrapper(*func_args, **func_kwargs): if variables: sensitive_variables_wrapper.sensitive_variables = variables else: sensitive_variables_wrapper.sensitive_variables = '__ALL__' return func(*func_args, **func_kwargs) return sensitive_variables_wrapper return decorator def sensitive_post_parameters(*parameters): """ Indicates which POST parameters used in the decorated view are sensitive, so that those parameters can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Two forms are accepted: * with specified parameters: @sensitive_post_parameters('password', 'credit_card') def my_view(request): pw = request.POST['password'] cc = request.POST['credit_card'] ... * without any specified parameters, in which case it is assumed that all parameters are considered sensitive: @sensitive_post_parameters() def my_view(request) ... """ def decorator(view): @functools.wraps(view) def sensitive_post_parameters_wrapper(request, *args, **kwargs): assert isinstance(request, HttpRequest), ( "sensitive_post_parameters didn't receive an HttpRequest. " "If you are decorating a classmethod, be sure to use " "@method_decorator." ) if parameters: request.sensitive_post_parameters = parameters else: request.sensitive_post_parameters = '__ALL__' return view(request, *args, **kwargs) return sensitive_post_parameters_wrapper return decorator
bsd-3-clause
dojemooh/dojecoin
contrib/bitrpc/bitrpc.py
2348
7835
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:8332") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:8332") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a Bitcoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Enter an account name: ") print access.getaddressesbyaccount(acct) except: print "\n---An error occurred---\n" elif cmd == "getbalance": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getbalance(acct, mc) except: print access.getbalance() except: print "\n---An error occurred---\n" elif cmd == "getblockbycount": try: height = raw_input("Height: ") print access.getblockbycount(height) except: print "\n---An error occurred---\n" elif cmd == "getblockcount": try: print access.getblockcount() except: print "\n---An error occurred---\n" elif cmd == "getblocknumber": try: print access.getblocknumber() except: print "\n---An error occurred---\n" elif cmd == "getconnectioncount": try: print access.getconnectioncount() except: print "\n---An error occurred---\n" elif cmd == "getdifficulty": try: print access.getdifficulty() except: print "\n---An error occurred---\n" elif cmd == "getgenerate": try: print access.getgenerate() except: print "\n---An error occurred---\n" elif cmd == "gethashespersec": try: print access.gethashespersec() except: print "\n---An error occurred---\n" elif cmd == "getinfo": try: print access.getinfo() except: print "\n---An error occurred---\n" elif cmd == "getnewaddress": try: acct = raw_input("Enter an account name: ") try: print access.getnewaddress(acct) except: print access.getnewaddress() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaccount": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaccount(acct, mc) except: print access.getreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaddress": try: addr = raw_input("Enter a Bitcoin address (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input("Command (optional): ") try: print access.help(cmd) except: print access.help() except: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaccount(mc, incemp) except: print access.listreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaddress": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaddress(mc, incemp) except: print access.listreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "listtransactions": try: acct = raw_input("Account (optional): ") count = raw_input("Number of transactions (optional): ") frm = raw_input("Skip (optional):") try: print access.listtransactions(acct, count, frm) except: print access.listtransactions() except: print "\n---An error occurred---\n" elif cmd == "move": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.move(frm, to, amt, mc, comment) except: print access.move(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendfrom": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendfrom(frm, to, amt, mc, comment, commentto) except: print access.sendfrom(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendmany": try: frm = raw_input("From: ") to = raw_input("To (in format address1:amount1,address2:amount2,...): ") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.sendmany(frm,to,mc,comment) except: print access.sendmany(frm,to) except: print "\n---An error occurred---\n" elif cmd == "sendtoaddress": try: to = raw_input("To (in format address1:amount1,address2:amount2,...): ") amt = raw_input("Amount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited, optional):") try: print access.setgenerate(gen, cpus) except: print access.setgenerate(gen) except: print "\n---An error occurred---\n" elif cmd == "settxfee": try: amt = raw_input("Amount:") print access.settxfee(amt) except: print "\n---An error occurred---\n" elif cmd == "stop": try: print access.stop() except: print "\n---An error occurred---\n" elif cmd == "validateaddress": try: addr = raw_input("Address: ") print access.validateaddress(addr) except: print "\n---An error occurred---\n" elif cmd == "walletpassphrase": try: pwd = raw_input("Enter wallet passphrase: ") access.walletpassphrase(pwd, 60) print "\n---Wallet unlocked---\n" except: print "\n---An error occurred---\n" elif cmd == "walletpassphrasechange": try: pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2) print print "\n---Passphrase changed---\n" except: print print "\n---An error occurred---\n" print else: print "Command not found or not supported"
mit
aaltinisik/OCBAltinkaya
addons/account_analytic_default/account_analytic_default.py
57
9022
# -*- coding: utf-8 -*- ############################################################################### # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import fields, osv class account_analytic_default(osv.osv): _name = "account.analytic.default" _description = "Analytic Distribution" _rec_name = "analytic_id" _order = "sequence" _columns = { 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of analytic distribution"), 'analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'), 'product_id': fields.many2one('product.product', 'Product', ondelete='cascade', help="Select a product which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this product, it will automatically take this as an analytic account)"), 'partner_id': fields.many2one('res.partner', 'Partner', ondelete='cascade', help="Select a partner which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this partner, it will automatically take this as an analytic account)"), 'user_id': fields.many2one('res.users', 'User', ondelete='cascade', help="Select a user which will use analytic account specified in analytic default."), 'company_id': fields.many2one('res.company', 'Company', ondelete='cascade', help="Select a company which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this company, it will automatically take this as an analytic account)"), 'date_start': fields.date('Start Date', help="Default start date for this Analytic Account."), 'date_stop': fields.date('End Date', help="Default end date for this Analytic Account."), } def account_get(self, cr, uid, product_id=None, partner_id=None, user_id=None, date=None, company_id=None, context=None): domain = [] if product_id: domain += ['|', ('product_id', '=', product_id)] domain += [('product_id','=', False)] if partner_id: domain += ['|', ('partner_id', '=', partner_id)] domain += [('partner_id', '=', False)] if company_id: domain += ['|', ('company_id', '=', company_id)] domain += [('company_id', '=', False)] if user_id: domain += ['|',('user_id', '=', user_id)] domain += [('user_id','=', False)] if date: domain += ['|', ('date_start', '<=', date), ('date_start', '=', False)] domain += ['|', ('date_stop', '>=', date), ('date_stop', '=', False)] best_index = -1 res = False for rec in self.browse(cr, uid, self.search(cr, uid, domain, context=context), context=context): index = 0 if rec.product_id: index += 1 if rec.partner_id: index += 1 if rec.company_id: index += 1 if rec.user_id: index += 1 if rec.date_start: index += 1 if rec.date_stop: index += 1 if index > best_index: res = rec best_index = index return res class account_invoice_line(osv.osv): _inherit = "account.invoice.line" _description = "Invoice Line" def product_id_change(self, cr, uid, ids, product, uom_id, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, currency_id=False, company_id=None, context=None): res_prod = super(account_invoice_line, self).product_id_change(cr, uid, ids, product, uom_id, qty, name, type, partner_id, fposition_id, price_unit, currency_id=currency_id, company_id=company_id, context=context) rec = self.pool.get('account.analytic.default').account_get(cr, uid, product, partner_id, uid, time.strftime('%Y-%m-%d'), company_id=company_id, context=context) if rec: res_prod['value'].update({'account_analytic_id': rec.analytic_id.id}) else: res_prod['value'].update({'account_analytic_id': False}) return res_prod class stock_picking(osv.osv): _inherit = "stock.picking" def _get_account_analytic_invoice(self, cursor, user, picking, move_line): partner_id = picking.partner_id and picking.partner_id.id or False rec = self.pool.get('account.analytic.default').account_get(cursor, user, move_line.product_id.id, partner_id, user, time.strftime('%Y-%m-%d')) if rec: return rec.analytic_id.id return super(stock_picking, self)._get_account_analytic_invoice(cursor, user, picking, move_line) class sale_order_line(osv.osv): _inherit = "sale.order.line" # Method overridden to set the analytic account by default on criterion match def invoice_line_create(self, cr, uid, ids, context=None): create_ids = super(sale_order_line, self).invoice_line_create(cr, uid, ids, context=context) if not ids: return create_ids sale_line = self.browse(cr, uid, ids[0], context=context) inv_line_obj = self.pool.get('account.invoice.line') anal_def_obj = self.pool.get('account.analytic.default') for line in inv_line_obj.browse(cr, uid, create_ids, context=context): rec = anal_def_obj.account_get(cr, uid, line.product_id.id, sale_line.order_id.partner_id.id, sale_line.order_id.user_id.id, time.strftime('%Y-%m-%d'), context=context) if rec: inv_line_obj.write(cr, uid, [line.id], {'account_analytic_id': rec.analytic_id.id}, context=context) return create_ids class product_product(osv.Model): _inherit = 'product.product' def _rules_count(self, cr, uid, ids, field_name, arg, context=None): Analytic = self.pool['account.analytic.default'] return { product_id: Analytic.search_count(cr, uid, [('product_id', '=', product_id)], context=context) for product_id in ids } _columns = { 'rules_count': fields.function(_rules_count, string='# Analytic Rules', type='integer'), } class product_template(osv.Model): _inherit = 'product.template' def _rules_count(self, cr, uid, ids, field_name, arg, context=None): Analytic = self.pool['account.analytic.default'] res = {} for product_tmpl_id in self.browse(cr, uid, ids, context=context): res[product_tmpl_id.id] = sum([p.rules_count for p in product_tmpl_id.product_variant_ids]) return res _columns = { 'rules_count': fields.function(_rules_count, string='# Analytic Rules', type='integer'), } def action_view_rules(self, cr, uid, ids, context=None): products = self._get_products(cr, uid, ids, context=context) result = self._get_act_window_dict(cr, uid, 'account_analytic_default.action_product_default_list', context=context) result['domain'] = "[('product_id','in',[" + ','.join(map(str, products)) + "])]" # Remove context so it is not going to filter on product_id with active_id of template result['context'] = "{}" return result class stock_move(osv.Model): _inherit = 'stock.move' def _create_invoice_line_from_vals(self, cr, uid, move, invoice_line_vals, context=None): # It will set the default analtyic account on the invoice line partner_id = self.pool['account.invoice'].browse(cr, uid, invoice_line_vals.get('invoice_id'), context=context).partner_id.id if 'account_analytic_id' not in invoice_line_vals or not invoice_line_vals.get('account_analytic_id'): rec = self.pool['account.analytic.default'].account_get(cr, uid, move.product_id.id, partner_id, uid, time.strftime('%Y-%m-%d'), company_id=move.company_id.id, context=context) if rec: invoice_line_vals.update({'account_analytic_id': rec.analytic_id.id}) res = super(stock_move, self)._create_invoice_line_from_vals(cr, uid, move, invoice_line_vals, context=context) return res # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
wfxiang08/changes
tests/changes/api/test_command_details.py
2
5046
from __future__ import absolute_import from mock import Mock, patch from changes.buildsteps.base import BuildStep from changes.constants import Result, Status from changes.expanders.base import Expander from changes.models import ( Command, CommandType, FutureCommand, FutureJobStep, JobStep ) from changes.testutils import APITestCase class CommandDetailsTest(APITestCase): def test_simple(self): project = self.create_project() build = self.create_build(project) job = self.create_job(build) jobphase = self.create_jobphase(job) jobstep = self.create_jobstep(jobphase) command = self.create_command(jobstep) path = '/api/0/commands/{0}/'.format(command.id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert data['id'] == command.id.hex class UpdateCommandTest(APITestCase): def test_simple(self): project = self.create_project() build = self.create_build(project) job = self.create_job(build) jobphase = self.create_jobphase(job) jobstep = self.create_jobstep( jobphase, status=Status.queued, result=Result.unknown, date_started=None, date_finished=None) command = self.create_command(jobstep) path = '/api/0/commands/{0}/'.format(command.id.hex) resp = self.client.post(path, data={ 'status': 'in_progress' }) assert resp.status_code == 200 data = self.unserialize(resp) assert data['id'] == command.id.hex command = Command.query.get(command.id) assert command.status == Status.in_progress assert command.date_started is not None assert command.date_finished is None resp = self.client.post(path, data={ 'status': 'queued' }) assert resp.status_code == 200 data = self.unserialize(resp) assert data['id'] == command.id.hex command = Command.query.get(command.id) assert command.status == Status.queued assert command.date_started is None assert command.date_finished is None resp = self.client.post(path, data={ 'status': 'finished', }) assert resp.status_code == 200 data = self.unserialize(resp) assert data['id'] == command.id.hex command = Command.query.get(command.id) assert command.status == Status.finished assert command.date_started is not None assert command.date_finished is not None @patch('changes.models.JobPlan.get_build_step_for_job') @patch('changes.api.command_details.CommandDetailsAPIView.get_expander') def test_simple_expander(self, mock_get_expander, mock_get_build_step_for_job): project = self.create_project() build = self.create_build(project) job = self.create_job(build) jobphase = self.create_jobphase(job) jobstep = self.create_jobstep(jobphase, data={ 'max_executors': 10, }) plan = self.create_plan(project, label='test') self.create_step(plan) jobplan = self.create_job_plan(job, plan) command = self.create_command( jobstep, type=CommandType.collect_tests, status=Status.in_progress) def dummy_expand_jobstep(jobstep, new_jobphase, future_jobstep): return future_jobstep.as_jobstep(new_jobphase) dummy_expander = Mock(spec=Expander) dummy_expander.expand.return_value = [FutureJobStep( label='test', commands=[FutureCommand( script='echo 1', ), FutureCommand( script='echo "foo"\necho "bar"', )], )] mock_get_expander.return_value.return_value = dummy_expander mock_buildstep = Mock(spec=BuildStep) mock_buildstep.expand_jobstep.side_effect = dummy_expand_jobstep mock_get_build_step_for_job.return_value = jobplan, mock_buildstep path = '/api/0/commands/{0}/'.format(command.id.hex) # missing output resp = self.client.post(path, data={ 'status': 'finished', }) assert resp.status_code == 400, resp.data mock_get_expander.reset_mock() # valid params resp = self.client.post(path, data={ 'status': 'finished', 'output': '{"foo": "bar"}', }) assert resp.status_code == 200, resp.data mock_get_expander.assert_called_once_with(command.type) mock_get_expander.return_value.assert_called_once_with( project=project, data={'foo': 'bar'}, ) dummy_expander.validate.assert_called_once_with() dummy_expander.expand.assert_called_once_with(max_executors=10) new_jobstep = JobStep.query.filter( JobStep.job_id == job.id, JobStep.id != jobstep.id, ).first() assert new_jobstep.label == 'test'
apache-2.0
40023154/2015cd_midterm
static/Brython3.1.1-20150328-091302/Lib/atexit.py
743
1049
"""allow programmer to define multiple exit functions to be executedupon normal program termination. Two public functions, register and unregister, are defined. """ class __loader__(object): pass def _clear(*args,**kw): """_clear() -> None Clear the list of previously registered exit functions.""" pass def _run_exitfuncs(*args,**kw): """_run_exitfuncs() -> None Run all registered exit functions.""" pass def register(*args,**kw): """register(func, *args, **kwargs) -> func Register a function to be executed upon normal program termination func - function to be called at exit args - optional arguments to pass to func kwargs - optional keyword arguments to pass to func func is returned to facilitate usage as a decorator.""" pass def unregister(*args,**kw): """unregister(func) -> None Unregister a exit function which was previously registered using atexit.register func - function to be unregistered""" pass
gpl-2.0
morenopc/edx-platform
common/lib/xmodule/xmodule/tests/test_error_module.py
3
5975
""" Tests for ErrorModule and NonStaffErrorModule """ import unittest from xmodule.tests import get_test_system from xmodule.error_module import ErrorDescriptor, ErrorModule, NonStaffErrorDescriptor from xmodule.modulestore.xml import CourseLocationGenerator from xmodule.modulestore.locations import SlashSeparatedCourseKey, Location from xmodule.x_module import XModuleDescriptor, XModule from mock import MagicMock, Mock, patch from xblock.runtime import Runtime, IdReader from xblock.field_data import FieldData from xblock.fields import ScopeIds from xblock.test.tools import unabc class SetupTestErrorModules(): def setUp(self): self.system = get_test_system() self.course_id = SlashSeparatedCourseKey('org', 'course', 'run') self.location = self.course_id.make_usage_key('foo', 'bar') self.valid_xml = u"<problem>ABC \N{SNOWMAN}</problem>" self.error_msg = "Error" class TestErrorModule(unittest.TestCase, SetupTestErrorModules): """ Tests for ErrorModule and ErrorDescriptor """ def setUp(self): SetupTestErrorModules.setUp(self) def test_error_module_xml_rendering(self): descriptor = ErrorDescriptor.from_xml( self.valid_xml, self.system, CourseLocationGenerator(self.course_id), self.error_msg ) self.assertIsInstance(descriptor, ErrorDescriptor) descriptor.xmodule_runtime = self.system context_repr = self.system.render(descriptor, 'student_view').content self.assertIn(self.error_msg, context_repr) self.assertIn(repr(self.valid_xml), context_repr) def test_error_module_from_descriptor(self): descriptor = MagicMock([XModuleDescriptor], runtime=self.system, location=self.location, _field_data=self.valid_xml) error_descriptor = ErrorDescriptor.from_descriptor( descriptor, self.error_msg) self.assertIsInstance(error_descriptor, ErrorDescriptor) error_descriptor.xmodule_runtime = self.system context_repr = self.system.render(error_descriptor, 'student_view').content self.assertIn(self.error_msg, context_repr) self.assertIn(repr(descriptor), context_repr) class TestNonStaffErrorModule(unittest.TestCase, SetupTestErrorModules): """ Tests for NonStaffErrorModule and NonStaffErrorDescriptor """ def setUp(self): SetupTestErrorModules.setUp(self) def test_non_staff_error_module_create(self): descriptor = NonStaffErrorDescriptor.from_xml( self.valid_xml, self.system, CourseLocationGenerator(self.course_id) ) self.assertIsInstance(descriptor, NonStaffErrorDescriptor) def test_from_xml_render(self): descriptor = NonStaffErrorDescriptor.from_xml( self.valid_xml, self.system, CourseLocationGenerator(self.course_id) ) descriptor.xmodule_runtime = self.system context_repr = self.system.render(descriptor, 'student_view').content self.assertNotIn(self.error_msg, context_repr) self.assertNotIn(repr(self.valid_xml), context_repr) def test_error_module_from_descriptor(self): descriptor = MagicMock([XModuleDescriptor], runtime=self.system, location=self.location, _field_data=self.valid_xml) error_descriptor = NonStaffErrorDescriptor.from_descriptor( descriptor, self.error_msg) self.assertIsInstance(error_descriptor, ErrorDescriptor) error_descriptor.xmodule_runtime = self.system context_repr = self.system.render(error_descriptor, 'student_view').content self.assertNotIn(self.error_msg, context_repr) self.assertNotIn(str(descriptor), context_repr) class BrokenModule(XModule): def __init__(self, *args, **kwargs): super(BrokenModule, self).__init__(*args, **kwargs) raise Exception("This is a broken xmodule") class BrokenDescriptor(XModuleDescriptor): module_class = BrokenModule class TestException(Exception): """An exception type to use to verify raises in tests""" pass @unabc("Tests should not call {}") class TestRuntime(Runtime): pass class TestErrorModuleConstruction(unittest.TestCase): """ Test that error module construction happens correctly """ def setUp(self): field_data = Mock(spec=FieldData) self.descriptor = BrokenDescriptor( TestRuntime(Mock(spec=IdReader), field_data), field_data, ScopeIds(None, None, None, Location('org', 'course', 'run', 'broken', 'name', None)) ) self.descriptor.xmodule_runtime = TestRuntime(Mock(spec=IdReader), field_data) self.descriptor.xmodule_runtime.error_descriptor_class = ErrorDescriptor self.descriptor.xmodule_runtime.xmodule_instance = None def test_broken_module(self): """ Test that when an XModule throws an error during __init__, we get an ErrorModule back from XModuleDescriptor._xmodule """ module = self.descriptor._xmodule self.assertIsInstance(module, ErrorModule) @patch.object(ErrorDescriptor, '__init__', Mock(side_effect=TestException)) def test_broken_error_descriptor(self): """ Test that a broken error descriptor doesn't cause an infinite loop """ with self.assertRaises(TestException): module = self.descriptor._xmodule @patch.object(ErrorModule, '__init__', Mock(side_effect=TestException)) def test_broken_error_module(self): """ Test that a broken error module doesn't cause an infinite loop """ with self.assertRaises(TestException): module = self.descriptor._xmodule
agpl-3.0
UQ-UQx/edx-platform_lti
lms/djangoapps/bulk_email/tests/test_tasks.py
21
20659
""" Unit tests for LMS instructor-initiated background tasks. Runs tasks on answers to course problems to validate that code paths actually work. """ import json from uuid import uuid4 from itertools import cycle, chain, repeat from mock import patch, Mock from smtplib import SMTPServerDisconnected, SMTPDataError, SMTPConnectError, SMTPAuthenticationError from boto.ses.exceptions import ( SESAddressNotVerifiedError, SESIdentityNotVerifiedError, SESDomainNotConfirmedError, SESAddressBlacklistedError, SESDailyQuotaExceededError, SESMaxSendingRateExceededError, SESDomainEndsWithDotError, SESLocalAddressCharacterError, SESIllegalAddressError, ) from boto.exception import AWSConnectionError from celery.states import SUCCESS, FAILURE from django.conf import settings from django.core.management import call_command from bulk_email.models import CourseEmail, Optout, SEND_TO_ALL from instructor_task.tasks import send_bulk_course_email from instructor_task.subtasks import update_subtask_status, SubtaskStatus from instructor_task.models import InstructorTask from instructor_task.tests.test_base import InstructorTaskCourseTestCase from instructor_task.tests.factories import InstructorTaskFactory from opaque_keys.edx.locations import SlashSeparatedCourseKey class TestTaskFailure(Exception): """Dummy exception used for unit tests.""" pass def my_update_subtask_status(entry_id, current_task_id, new_subtask_status): """ Check whether a subtask has been updated before really updating. Check whether a subtask which has been retried has had the retry already write its results here before the code that was invoking the retry had a chance to update this status. This is the norm in "eager" mode (used by tests) where the retry is called and run to completion before control is returned to the code that invoked the retry. If the retries eventually end in failure (e.g. due to a maximum number of retries being attempted), the "eager" code will return the error for each retry as it is popped off the stack. We want to just ignore the later updates that are called as the result of the earlier retries. This should not be an issue in production, where status is updated before a task is retried, and is then updated afterwards if the retry fails. """ entry = InstructorTask.objects.get(pk=entry_id) subtask_dict = json.loads(entry.subtasks) subtask_status_info = subtask_dict['status'] current_subtask_status = SubtaskStatus.from_dict(subtask_status_info[current_task_id]) current_retry_count = current_subtask_status.get_retry_count() new_retry_count = new_subtask_status.get_retry_count() if current_retry_count <= new_retry_count: update_subtask_status(entry_id, current_task_id, new_subtask_status) @patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message')) class TestBulkEmailInstructorTask(InstructorTaskCourseTestCase): """Tests instructor task that send bulk email.""" def setUp(self): super(TestBulkEmailInstructorTask, self).setUp() self.initialize_course() self.instructor = self.create_instructor('instructor') # load initial content (since we don't run migrations as part of tests): call_command("loaddata", "course_email_template.json") def _create_input_entry(self, course_id=None): """ Creates a InstructorTask entry for testing. Overrides the base class version in that this creates CourseEmail. """ to_option = SEND_TO_ALL course_id = course_id or self.course.id course_email = CourseEmail.create(course_id, self.instructor, to_option, "Test Subject", "<p>This is a test message</p>") task_input = {'email_id': course_email.id} # pylint: disable=no-member task_id = str(uuid4()) instructor_task = InstructorTaskFactory.create( course_id=course_id, requester=self.instructor, task_input=json.dumps(task_input), task_key='dummy value', task_id=task_id, ) return instructor_task def _run_task_with_mock_celery(self, task_class, entry_id, task_id): """Submit a task and mock how celery provides a current_task.""" mock_current_task = Mock() mock_current_task.max_retries = settings.BULK_EMAIL_MAX_RETRIES mock_current_task.default_retry_delay = settings.BULK_EMAIL_DEFAULT_RETRY_DELAY task_args = [entry_id, {}] with patch('bulk_email.tasks._get_current_task') as mock_get_task: mock_get_task.return_value = mock_current_task return task_class.apply(task_args, task_id=task_id).get() def test_email_missing_current_task(self): task_entry = self._create_input_entry() with self.assertRaises(ValueError): send_bulk_course_email(task_entry.id, {}) def test_email_undefined_course(self): # Check that we fail when passing in a course that doesn't exist. task_entry = self._create_input_entry(course_id=SlashSeparatedCourseKey("bogus", "course", "id")) with self.assertRaises(ValueError): self._run_task_with_mock_celery(send_bulk_course_email, task_entry.id, task_entry.task_id) def test_bad_task_id_on_update(self): task_entry = self._create_input_entry() def dummy_update_subtask_status(entry_id, _current_task_id, new_subtask_status): """Passes a bad value for task_id to test update_subtask_status""" bogus_task_id = "this-is-bogus" update_subtask_status(entry_id, bogus_task_id, new_subtask_status) with self.assertRaises(ValueError): with patch('bulk_email.tasks.update_subtask_status', dummy_update_subtask_status): send_bulk_course_email(task_entry.id, {}) # pylint: disable=no-member def _create_students(self, num_students): """Create students for testing""" return [self.create_student('robot%d' % i) for i in xrange(num_students)] def _assert_single_subtask_status(self, entry, succeeded, failed=0, skipped=0, retried_nomax=0, retried_withmax=0): """Compare counts with 'subtasks' entry in InstructorTask table.""" subtask_info = json.loads(entry.subtasks) # verify subtask-level counts: self.assertEquals(subtask_info.get('total'), 1) self.assertEquals(subtask_info.get('succeeded'), 1 if succeeded > 0 else 0) self.assertEquals(subtask_info.get('failed'), 0 if succeeded > 0 else 1) # verify individual subtask status: subtask_status_info = subtask_info.get('status') task_id_list = subtask_status_info.keys() self.assertEquals(len(task_id_list), 1) task_id = task_id_list[0] subtask_status = subtask_status_info.get(task_id) print("Testing subtask status: {}".format(subtask_status)) self.assertEquals(subtask_status.get('task_id'), task_id) self.assertEquals(subtask_status.get('attempted'), succeeded + failed) self.assertEquals(subtask_status.get('succeeded'), succeeded) self.assertEquals(subtask_status.get('skipped'), skipped) self.assertEquals(subtask_status.get('failed'), failed) self.assertEquals(subtask_status.get('retried_nomax'), retried_nomax) self.assertEquals(subtask_status.get('retried_withmax'), retried_withmax) self.assertEquals(subtask_status.get('state'), SUCCESS if succeeded > 0 else FAILURE) def _test_run_with_task(self, task_class, action_name, total, succeeded, failed=0, skipped=0, retried_nomax=0, retried_withmax=0): """Run a task and check the number of emails processed.""" task_entry = self._create_input_entry() parent_status = self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id) # check return value self.assertEquals(parent_status.get('total'), total) self.assertEquals(parent_status.get('action_name'), action_name) # compare with task_output entry in InstructorTask table: entry = InstructorTask.objects.get(id=task_entry.id) status = json.loads(entry.task_output) self.assertEquals(status.get('attempted'), succeeded + failed) self.assertEquals(status.get('succeeded'), succeeded) self.assertEquals(status.get('skipped'), skipped) self.assertEquals(status.get('failed'), failed) self.assertEquals(status.get('total'), total) self.assertEquals(status.get('action_name'), action_name) self.assertGreater(status.get('duration_ms'), 0) self.assertEquals(entry.task_state, SUCCESS) self._assert_single_subtask_status(entry, succeeded, failed, skipped, retried_nomax, retried_withmax) return entry def test_successful(self): # Select number of emails to fit into a single subtask. num_emails = settings.BULK_EMAIL_EMAILS_PER_TASK # We also send email to the instructor: self._create_students(num_emails - 1) with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: get_conn.return_value.send_messages.side_effect = cycle([None]) self._test_run_with_task(send_bulk_course_email, 'emailed', num_emails, num_emails) def test_successful_twice(self): # Select number of emails to fit into a single subtask. num_emails = settings.BULK_EMAIL_EMAILS_PER_TASK # We also send email to the instructor: self._create_students(num_emails - 1) with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: get_conn.return_value.send_messages.side_effect = cycle([None]) task_entry = self._test_run_with_task(send_bulk_course_email, 'emailed', num_emails, num_emails) # submit the same task a second time, and confirm that it is not run again. with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: get_conn.return_value.send_messages.side_effect = cycle([Exception("This should not happen!")]) parent_status = self._run_task_with_mock_celery(send_bulk_course_email, task_entry.id, task_entry.task_id) self.assertEquals(parent_status.get('total'), num_emails) self.assertEquals(parent_status.get('succeeded'), num_emails) self.assertEquals(parent_status.get('failed'), 0) def test_unactivated_user(self): # Select number of emails to fit into a single subtask. num_emails = settings.BULK_EMAIL_EMAILS_PER_TASK # We also send email to the instructor: students = self._create_students(num_emails - 1) # mark a student as not yet having activated their email: student = students[0] student.is_active = False student.save() with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: get_conn.return_value.send_messages.side_effect = cycle([None]) self._test_run_with_task(send_bulk_course_email, 'emailed', num_emails - 1, num_emails - 1) def test_skipped(self): # Select number of emails to fit into a single subtask. num_emails = settings.BULK_EMAIL_EMAILS_PER_TASK # We also send email to the instructor: students = self._create_students(num_emails - 1) # have every fourth student optout: expected_skipped = int((num_emails + 3) / 4.0) expected_succeeds = num_emails - expected_skipped for index in range(0, num_emails, 4): Optout.objects.create(user=students[index], course_id=self.course.id) # mark some students as opting out with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: get_conn.return_value.send_messages.side_effect = cycle([None]) self._test_run_with_task(send_bulk_course_email, 'emailed', num_emails, expected_succeeds, skipped=expected_skipped) def _test_email_address_failures(self, exception): """Test that celery handles bad address errors by failing and not retrying.""" # Select number of emails to fit into a single subtask. num_emails = settings.BULK_EMAIL_EMAILS_PER_TASK # We also send email to the instructor: self._create_students(num_emails - 1) expected_fails = int((num_emails + 3) / 4.0) expected_succeeds = num_emails - expected_fails with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: # have every fourth email fail due to some address failure: get_conn.return_value.send_messages.side_effect = cycle([exception, None, None, None]) self._test_run_with_task(send_bulk_course_email, 'emailed', num_emails, expected_succeeds, failed=expected_fails) def test_smtp_blacklisted_user(self): # Test that celery handles permanent SMTPDataErrors by failing and not retrying. self._test_email_address_failures(SMTPDataError(554, "Email address is blacklisted")) def test_ses_blacklisted_user(self): # Test that celery handles permanent SMTPDataErrors by failing and not retrying. self._test_email_address_failures(SESAddressBlacklistedError(554, "Email address is blacklisted")) def test_ses_illegal_address(self): # Test that celery handles permanent SMTPDataErrors by failing and not retrying. self._test_email_address_failures(SESIllegalAddressError(554, "Email address is illegal")) def test_ses_local_address_character_error(self): # Test that celery handles permanent SMTPDataErrors by failing and not retrying. self._test_email_address_failures(SESLocalAddressCharacterError(554, "Email address contains a bad character")) def test_ses_domain_ends_with_dot(self): # Test that celery handles permanent SMTPDataErrors by failing and not retrying. self._test_email_address_failures(SESDomainEndsWithDotError(554, "Email address ends with a dot")) def _test_retry_after_limited_retry_error(self, exception): """Test that celery handles connection failures by retrying.""" # If we want the batch to succeed, we need to send fewer emails # than the max retries, so that the max is not triggered. num_emails = settings.BULK_EMAIL_MAX_RETRIES # We also send email to the instructor: self._create_students(num_emails - 1) expected_fails = 0 expected_succeeds = num_emails with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: # Have every other mail attempt fail due to disconnection. get_conn.return_value.send_messages.side_effect = cycle([exception, None]) self._test_run_with_task( send_bulk_course_email, 'emailed', num_emails, expected_succeeds, failed=expected_fails, retried_withmax=num_emails ) def _test_max_retry_limit_causes_failure(self, exception): """Test that celery can hit a maximum number of retries.""" # Doesn't really matter how many recipients, since we expect # to fail on the first. num_emails = 10 # We also send email to the instructor: self._create_students(num_emails - 1) expected_fails = num_emails expected_succeeds = 0 with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: # always fail to connect, triggering repeated retries until limit is hit: get_conn.return_value.send_messages.side_effect = cycle([exception]) with patch('bulk_email.tasks.update_subtask_status', my_update_subtask_status): self._test_run_with_task( send_bulk_course_email, 'emailed', num_emails, expected_succeeds, failed=expected_fails, retried_withmax=(settings.BULK_EMAIL_MAX_RETRIES + 1) ) def test_retry_after_smtp_disconnect(self): self._test_retry_after_limited_retry_error(SMTPServerDisconnected(425, "Disconnecting")) def test_max_retry_after_smtp_disconnect(self): self._test_max_retry_limit_causes_failure(SMTPServerDisconnected(425, "Disconnecting")) def test_retry_after_smtp_connect_error(self): self._test_retry_after_limited_retry_error(SMTPConnectError(424, "Bad Connection")) def test_max_retry_after_smtp_connect_error(self): self._test_max_retry_limit_causes_failure(SMTPConnectError(424, "Bad Connection")) def test_retry_after_aws_connect_error(self): self._test_retry_after_limited_retry_error(AWSConnectionError("Unable to provide secure connection through proxy")) def test_max_retry_after_aws_connect_error(self): self._test_max_retry_limit_causes_failure(AWSConnectionError("Unable to provide secure connection through proxy")) def test_retry_after_general_error(self): self._test_retry_after_limited_retry_error(Exception("This is some random exception.")) def test_max_retry_after_general_error(self): self._test_max_retry_limit_causes_failure(Exception("This is some random exception.")) def _test_retry_after_unlimited_retry_error(self, exception): """Test that celery handles throttling failures by retrying.""" num_emails = 8 # We also send email to the instructor: self._create_students(num_emails - 1) expected_fails = 0 expected_succeeds = num_emails # Note that because celery in eager mode will call retries synchronously, # each retry will increase the stack depth. It turns out that there is a # maximum depth at which a RuntimeError is raised ("maximum recursion depth # exceeded"). The maximum recursion depth is 90, so # num_emails * expected_retries < 90. expected_retries = 10 with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: # Cycle through N throttling errors followed by a success. get_conn.return_value.send_messages.side_effect = cycle( chain(repeat(exception, expected_retries), [None]) ) self._test_run_with_task( send_bulk_course_email, 'emailed', num_emails, expected_succeeds, failed=expected_fails, retried_nomax=(expected_retries * num_emails) ) def test_retry_after_smtp_throttling_error(self): self._test_retry_after_unlimited_retry_error(SMTPDataError(455, "Throttling: Sending rate exceeded")) def test_retry_after_ses_throttling_error(self): self._test_retry_after_unlimited_retry_error(SESMaxSendingRateExceededError(455, "Throttling: Sending rate exceeded")) def _test_immediate_failure(self, exception): """Test that celery can hit a maximum number of retries.""" # Doesn't really matter how many recipients, since we expect # to fail on the first. num_emails = 10 # We also send email to the instructor: self._create_students(num_emails - 1) expected_fails = num_emails expected_succeeds = 0 with patch('bulk_email.tasks.get_connection', autospec=True) as get_conn: # always fail to connect, triggering repeated retries until limit is hit: get_conn.return_value.send_messages.side_effect = cycle([exception]) self._test_run_with_task( send_bulk_course_email, 'emailed', num_emails, expected_succeeds, failed=expected_fails, ) def test_failure_on_unhandled_smtp(self): self._test_immediate_failure(SMTPAuthenticationError(403, "That password doesn't work!")) def test_failure_on_ses_quota_exceeded(self): self._test_immediate_failure(SESDailyQuotaExceededError(403, "You're done for the day!")) def test_failure_on_ses_address_not_verified(self): self._test_immediate_failure(SESAddressNotVerifiedError(403, "Who *are* you?")) def test_failure_on_ses_identity_not_verified(self): self._test_immediate_failure(SESIdentityNotVerifiedError(403, "May I please see an ID!")) def test_failure_on_ses_domain_not_confirmed(self): self._test_immediate_failure(SESDomainNotConfirmedError(403, "You're out of bounds!"))
agpl-3.0
aikonbrasil/ns3-20
src/core/examples/sample-simulator.py
85
2094
# -*- Mode:Python; -*- # /* # * Copyright (c) 2010 INRIA # * # * This program is free software; you can redistribute it and/or modify # * it under the terms of the GNU General Public License version 2 as # * published by the Free Software Foundation; # * # * This program is distributed in the hope that it will be useful, # * but WITHOUT ANY WARRANTY; without even the implied warranty of # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # * GNU General Public License for more details. # * # * You should have received a copy of the GNU General Public License # * along with this program; if not, write to the Free Software # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # * # * Authors: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> # */ # # Python version of sample-simulator.cc import ns.core class MyModel(object): def Start(self): ns.core.Simulator.Schedule(ns.core.Seconds(10.0), self.HandleEvent, ns.core.Simulator.Now().GetSeconds()) def HandleEvent(self, value): print "Member method received event at", ns.core.Simulator.Now().GetSeconds(), \ "s started at", value, "s" def ExampleFunction(model): print "ExampleFunction received event at", ns.core.Simulator.Now().GetSeconds(), "s" model.Start() def RandomFunction(model): print "RandomFunction received event at", ns.core.Simulator.Now().GetSeconds(), "s" def CancelledEvent(): print "I should never be called... " def main(dummy_argv): model = MyModel() v = ns.core.UniformRandomVariable() v.SetAttribute("Min", ns.core.DoubleValue (10)) v.SetAttribute("Max", ns.core.DoubleValue (20)) ns.core.Simulator.Schedule(ns.core.Seconds(10.0), ExampleFunction, model) ns.core.Simulator.Schedule(ns.core.Seconds(v.GetValue()), RandomFunction, model) id = ns.core.Simulator.Schedule(ns.core.Seconds(30.0), CancelledEvent) ns.core.Simulator.Cancel(id) ns.core.Simulator.Run() ns.core.Simulator.Destroy() if __name__ == '__main__': import sys main(sys.argv)
gpl-2.0
eblossom/gnuradio
gr-channels/python/channels/__init__.py
54
1350
# # Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Blocks for channel models and related functions. ''' import os try: from channels_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from channels_swig import * # Blocks for Hardware Impairments from amp_bal import * from conj_fs_iqcorr import * from distortion_2_gen import * from distortion_3_gen import * from iqbal_gen import * from impairments import * from phase_bal import * from phase_noise_gen import * from quantizer import *
gpl-3.0
maestrano/openerp
openerp/addons/hr_timesheet_invoice/hr_timesheet_invoice.py
8
18345
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import fields, osv from openerp.tools.translate import _ class hr_timesheet_invoice_factor(osv.osv): _name = "hr_timesheet_invoice.factor" _description = "Invoice Rate" _order = 'factor' _columns = { 'name': fields.char('Internal Name', size=128, required=True, translate=True), 'customer_name': fields.char('Name', size=128, help="Label for the customer"), 'factor': fields.float('Discount (%)', required=True, help="Discount in percentage"), } _defaults = { 'factor': lambda *a: 0.0, } hr_timesheet_invoice_factor() class account_analytic_account(osv.osv): def _invoiced_calc(self, cr, uid, ids, name, arg, context=None): obj_invoice = self.pool.get('account.invoice') res = {} cr.execute('SELECT account_id as account_id, l.invoice_id ' 'FROM hr_analytic_timesheet h LEFT JOIN account_analytic_line l ' 'ON (h.line_id=l.id) ' 'WHERE l.account_id = ANY(%s)', (ids,)) account_to_invoice_map = {} for rec in cr.dictfetchall(): account_to_invoice_map.setdefault(rec['account_id'], []).append(rec['invoice_id']) for account in self.browse(cr, uid, ids, context=context): invoice_ids = filter(None, list(set(account_to_invoice_map.get(account.id, [])))) for invoice in obj_invoice.browse(cr, uid, invoice_ids, context=context): res.setdefault(account.id, 0.0) res[account.id] += invoice.amount_untaxed for id in ids: res[id] = round(res.get(id, 0.0),2) return res _inherit = "account.analytic.account" _columns = { 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', help="The product to invoice is defined on the employee form, the price will be deducted by this pricelist on the product."), 'amount_max': fields.float('Max. Invoice Price', help="Keep empty if this contract is not limited to a total fixed price."), 'amount_invoiced': fields.function(_invoiced_calc, string='Invoiced Amount', help="Total invoiced"), 'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Timesheet Invoicing Ratio', help="You usually invoice 100% of the timesheets. But if you mix fixed price and timesheet invoicing, you may use another ratio. For instance, if you do a 20% advance invoice (fixed price, based on a sales order), you should invoice the rest on timesheet with a 80% ratio."), } def on_change_partner_id(self, cr, uid, ids, partner_id, name, context=None): res = super(account_analytic_account, self).on_change_partner_id(cr, uid, ids, partner_id, name, context=context) part = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context) pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False if pricelist: res['value']['pricelist_id'] = pricelist return res def set_close(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'close'}, context=context) def set_cancel(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'cancelled'}, context=context) def set_open(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'open'}, context=context) def set_pending(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'pending'}, context=context) class account_analytic_line(osv.osv): _inherit = 'account.analytic.line' _columns = { 'invoice_id': fields.many2one('account.invoice', 'Invoice', ondelete="set null"), 'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Invoiceable', help="It allows to set the discount while making invoice, keep empty if the activities should not be invoiced."), } def _default_journal(self, cr, uid, context=None): proxy = self.pool.get('hr.employee') record_ids = proxy.search(cr, uid, [('user_id', '=', uid)], context=context) if record_ids: employee = proxy.browse(cr, uid, record_ids[0], context=context) return employee.journal_id and employee.journal_id.id or False return False def _default_general_account(self, cr, uid, context=None): proxy = self.pool.get('hr.employee') record_ids = proxy.search(cr, uid, [('user_id', '=', uid)], context=context) if record_ids: employee = proxy.browse(cr, uid, record_ids[0], context=context) if employee.product_id and employee.product_id.property_account_income: return employee.product_id.property_account_income.id return False _defaults = { 'journal_id' : _default_journal, 'general_account_id' : _default_general_account, } def write(self, cr, uid, ids, vals, context=None): self._check_inv(cr, uid, ids, vals) return super(account_analytic_line,self).write(cr, uid, ids, vals, context=context) def _check_inv(self, cr, uid, ids, vals): select = ids if isinstance(select, (int, long)): select = [ids] if ( not vals.has_key('invoice_id')) or vals['invoice_id' ] == False: for line in self.browse(cr, uid, select): if line.invoice_id: raise osv.except_osv(_('Error!'), _('You cannot modify an invoiced analytic line!')) return True def copy(self, cursor, user, obj_id, default=None, context=None): if default is None: default = {} default = default.copy() default.update({'invoice_id': False}) return super(account_analytic_line, self).copy(cursor, user, obj_id, default, context=context) def _get_invoice_price(self, cr, uid, account, product_id, user_id, qty, context = {}): pro_price_obj = self.pool.get('product.pricelist') if account.pricelist_id: pl = account.pricelist_id.id price = pro_price_obj.price_get(cr,uid,[pl], product_id, qty or 1.0, account.partner_id.id, context=context)[pl] else: price = 0.0 return price def invoice_cost_create(self, cr, uid, ids, data=None, context=None): analytic_account_obj = self.pool.get('account.analytic.account') account_payment_term_obj = self.pool.get('account.payment.term') invoice_obj = self.pool.get('account.invoice') product_obj = self.pool.get('product.product') invoice_factor_obj = self.pool.get('hr_timesheet_invoice.factor') fiscal_pos_obj = self.pool.get('account.fiscal.position') product_uom_obj = self.pool.get('product.uom') invoice_line_obj = self.pool.get('account.invoice.line') invoices = [] if context is None: context = {} if data is None: data = {} journal_types = {} # prepare for iteration on journal and accounts for line in self.pool.get('account.analytic.line').browse(cr, uid, ids, context=context): if line.journal_id.type not in journal_types: journal_types[line.journal_id.type] = set() journal_types[line.journal_id.type].add(line.account_id.id) for journal_type, account_ids in journal_types.items(): for account in analytic_account_obj.browse(cr, uid, list(account_ids), context=context): partner = account.partner_id if (not partner) or not (account.pricelist_id): raise osv.except_osv(_('Analytic Account Incomplete!'), _('Contract incomplete. Please fill in the Customer and Pricelist fields.')) date_due = False if partner.property_payment_term: pterm_list= account_payment_term_obj.compute(cr, uid, partner.property_payment_term.id, value=1, date_ref=time.strftime('%Y-%m-%d')) if pterm_list: pterm_list = [line[0] for line in pterm_list] pterm_list.sort() date_due = pterm_list[-1] curr_invoice = { 'name': time.strftime('%d/%m/%Y') + ' - '+account.name, 'partner_id': account.partner_id.id, 'company_id': account.company_id.id, 'payment_term': partner.property_payment_term.id or False, 'account_id': partner.property_account_receivable.id, 'currency_id': account.pricelist_id.currency_id.id, 'date_due': date_due, 'fiscal_position': account.partner_id.property_account_position.id } context2 = context.copy() context2['lang'] = partner.lang # set company_id in context, so the correct default journal will be selected context2['force_company'] = curr_invoice['company_id'] # set force_company in context so the correct product properties are selected (eg. income account) context2['company_id'] = curr_invoice['company_id'] last_invoice = invoice_obj.create(cr, uid, curr_invoice, context=context2) invoices.append(last_invoice) cr.execute("""SELECT product_id, user_id, to_invoice, sum(amount), sum(unit_amount), product_uom_id FROM account_analytic_line as line LEFT JOIN account_analytic_journal journal ON (line.journal_id = journal.id) WHERE account_id = %s AND line.id IN %s AND journal.type = %s AND to_invoice IS NOT NULL GROUP BY product_id, user_id, to_invoice, product_uom_id""", (account.id, tuple(ids), journal_type)) for product_id, user_id, factor_id, total_price, qty, uom in cr.fetchall(): context2.update({'uom': uom}) if data.get('product'): # force product, use its public price product_id = data['product'][0] unit_price = self._get_invoice_price(cr, uid, account, product_id, user_id, qty, context2) elif journal_type == 'general' and product_id: # timesheets, use sale price unit_price = self._get_invoice_price(cr, uid, account, product_id, user_id, qty, context2) else: # expenses, using price from amount field unit_price = total_price*-1.0 / qty factor = invoice_factor_obj.browse(cr, uid, factor_id, context=context2) # factor_name = factor.customer_name and line_name + ' - ' + factor.customer_name or line_name factor_name = factor.customer_name curr_line = { 'price_unit': unit_price, 'quantity': qty, 'product_id': product_id or False, 'discount': factor.factor, 'invoice_id': last_invoice, 'name': factor_name, 'uos_id': uom, 'account_analytic_id': account.id, } product = product_obj.browse(cr, uid, product_id, context=context2) if product: factor_name = product_obj.name_get(cr, uid, [product_id], context=context2)[0][1] if factor.customer_name: factor_name += ' - ' + factor.customer_name general_account = product.property_account_income or product.categ_id.property_account_income_categ if not general_account: raise osv.except_osv(_("Configuration Error!"), _("Please define income account for product '%s'.") % product.name) taxes = product.taxes_id or general_account.tax_ids tax = fiscal_pos_obj.map_tax(cr, uid, account.partner_id.property_account_position, taxes) curr_line.update({ 'invoice_line_tax_id': [(6,0,tax )], 'name': factor_name, 'invoice_line_tax_id': [(6,0,tax)], 'account_id': general_account.id, }) # # Compute for lines # cr.execute("SELECT * FROM account_analytic_line WHERE account_id = %s and id IN %s AND product_id=%s and to_invoice=%s ORDER BY account_analytic_line.date", (account.id, tuple(ids), product_id, factor_id)) line_ids = cr.dictfetchall() note = [] for line in line_ids: # set invoice_line_note details = [] if data.get('date', False): details.append(line['date']) if data.get('time', False): if line['product_uom_id']: details.append("%s %s" % (line['unit_amount'], product_uom_obj.browse(cr, uid, [line['product_uom_id']],context2)[0].name)) else: details.append("%s" % (line['unit_amount'], )) if data.get('name', False): details.append(line['name']) note.append(u' - '.join(map(lambda x: unicode(x) or '',details))) if note: curr_line['name'] += "\n" + ("\n".join(map(lambda x: unicode(x) or '',note))) invoice_line_obj.create(cr, uid, curr_line, context=context) cr.execute("update account_analytic_line set invoice_id=%s WHERE account_id = %s and id IN %s", (last_invoice, account.id, tuple(ids))) invoice_obj.button_reset_taxes(cr, uid, [last_invoice], context) return invoices account_analytic_line() class hr_analytic_timesheet(osv.osv): _inherit = "hr.analytic.timesheet" def on_change_account_id(self, cr, uid, ids, account_id, user_id=False): res = {} if not account_id: return res res.setdefault('value',{}) acc = self.pool.get('account.analytic.account').browse(cr, uid, account_id) st = acc.to_invoice.id res['value']['to_invoice'] = st or False if acc.state=='pending': res['warning'] = { 'title': 'Warning', 'message': 'The analytic account is in pending state.\nYou should not work on this account !' } return res def copy(self, cursor, user, obj_id, default=None, context=None): if default is None: default = {} default = default.copy() default.update({'invoice_id': False}) return super(hr_analytic_timesheet, self).copy(cursor, user, obj_id, default, context=context) hr_analytic_timesheet() class account_invoice(osv.osv): _inherit = "account.invoice" def _get_analytic_lines(self, cr, uid, id, context=None): iml = super(account_invoice, self)._get_analytic_lines(cr, uid, id, context=context) inv = self.browse(cr, uid, [id], context=context)[0] if inv.type == 'in_invoice': obj_analytic_account = self.pool.get('account.analytic.account') for il in iml: if il['account_analytic_id']: # *-* browse (or refactor to avoid read inside the loop) to_invoice = obj_analytic_account.read(cr, uid, [il['account_analytic_id']], ['to_invoice'], context=context)[0]['to_invoice'] if to_invoice: il['analytic_lines'][0][2]['to_invoice'] = to_invoice[0] return iml account_invoice() class account_move_line(osv.osv): _inherit = "account.move.line" def create_analytic_lines(self, cr, uid, ids, context=None): res = super(account_move_line, self).create_analytic_lines(cr, uid, ids,context=context) analytic_line_obj = self.pool.get('account.analytic.line') for move_line in self.browse(cr, uid, ids, context=context): #For customer invoice, link analytic line to the invoice so it is not proposed for invoicing in Bill Tasks Work invoice_id = move_line.invoice and move_line.invoice.type in ('out_invoice','out_refund') and move_line.invoice.id or False for line in move_line.analytic_lines: analytic_line_obj.write(cr, uid, line.id, { 'invoice_id': invoice_id, 'to_invoice': line.account_id.to_invoice and line.account_id.to_invoice.id or False }, context=context) return res account_move_line() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
jhd/spunout
venv/lib/python2.7/site-packages/pip/_vendor/html5lib/treebuilders/etree.py
915
12621
from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import text_type import re from . import _base from .. import ihatexml from .. import constants from ..constants import namespaces from ..utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") def getETreeBuilder(ElementTreeImplementation, fullTree=False): ElementTree = ElementTreeImplementation ElementTreeCommentType = ElementTree.Comment("asd").tag class Element(_base.Node): def __init__(self, name, namespace=None): self._name = name self._namespace = namespace self._element = ElementTree.Element(self._getETreeTag(name, namespace)) if namespace is None: self.nameTuple = namespaces["html"], self._name else: self.nameTuple = self._namespace, self._name self.parent = None self._childNodes = [] self._flags = [] def _getETreeTag(self, name, namespace): if namespace is None: etree_tag = name else: etree_tag = "{%s}%s" % (namespace, name) return etree_tag def _setName(self, name): self._name = name self._element.tag = self._getETreeTag(self._name, self._namespace) def _getName(self): return self._name name = property(_getName, _setName) def _setNamespace(self, namespace): self._namespace = namespace self._element.tag = self._getETreeTag(self._name, self._namespace) def _getNamespace(self): return self._namespace namespace = property(_getNamespace, _setNamespace) def _getAttributes(self): return self._element.attrib def _setAttributes(self, attributes): # Delete existing attributes first # XXX - there may be a better way to do this... for key in list(self._element.attrib.keys()): del self._element.attrib[key] for key, value in attributes.items(): if isinstance(key, tuple): name = "{%s}%s" % (key[2], key[1]) else: name = key self._element.set(name, value) attributes = property(_getAttributes, _setAttributes) def _getChildNodes(self): return self._childNodes def _setChildNodes(self, value): del self._element[:] self._childNodes = [] for element in value: self.insertChild(element) childNodes = property(_getChildNodes, _setChildNodes) def hasContent(self): """Return true if the node has children or text""" return bool(self._element.text or len(self._element)) def appendChild(self, node): self._childNodes.append(node) self._element.append(node._element) node.parent = self def insertBefore(self, node, refNode): index = list(self._element).index(refNode._element) self._element.insert(index, node._element) node.parent = self def removeChild(self, node): self._element.remove(node._element) node.parent = None def insertText(self, data, insertBefore=None): if not(len(self._element)): if not self._element.text: self._element.text = "" self._element.text += data elif insertBefore is None: # Insert the text as the tail of the last child element if not self._element[-1].tail: self._element[-1].tail = "" self._element[-1].tail += data else: # Insert the text before the specified node children = list(self._element) index = children.index(insertBefore._element) if index > 0: if not self._element[index - 1].tail: self._element[index - 1].tail = "" self._element[index - 1].tail += data else: if not self._element.text: self._element.text = "" self._element.text += data def cloneNode(self): element = type(self)(self.name, self.namespace) for name, value in self.attributes.items(): element.attributes[name] = value return element def reparentChildren(self, newParent): if newParent.childNodes: newParent.childNodes[-1]._element.tail += self._element.text else: if not newParent._element.text: newParent._element.text = "" if self._element.text is not None: newParent._element.text += self._element.text self._element.text = "" _base.Node.reparentChildren(self, newParent) class Comment(Element): def __init__(self, data): # Use the superclass constructor to set all properties on the # wrapper element self._element = ElementTree.Comment(data) self.parent = None self._childNodes = [] self._flags = [] def _getData(self): return self._element.text def _setData(self, value): self._element.text = value data = property(_getData, _setData) class DocumentType(Element): def __init__(self, name, publicId, systemId): Element.__init__(self, "<!DOCTYPE>") self._element.text = name self.publicId = publicId self.systemId = systemId def _getPublicId(self): return self._element.get("publicId", "") def _setPublicId(self, value): if value is not None: self._element.set("publicId", value) publicId = property(_getPublicId, _setPublicId) def _getSystemId(self): return self._element.get("systemId", "") def _setSystemId(self, value): if value is not None: self._element.set("systemId", value) systemId = property(_getSystemId, _setSystemId) class Document(Element): def __init__(self): Element.__init__(self, "DOCUMENT_ROOT") class DocumentFragment(Element): def __init__(self): Element.__init__(self, "DOCUMENT_FRAGMENT") def testSerializer(element): rv = [] def serializeElement(element, indent=0): if not(hasattr(element, "tag")): element = element.getroot() if element.tag == "<!DOCTYPE>": if element.get("publicId") or element.get("systemId"): publicId = element.get("publicId") or "" systemId = element.get("systemId") or "" rv.append("""<!DOCTYPE %s "%s" "%s">""" % (element.text, publicId, systemId)) else: rv.append("<!DOCTYPE %s>" % (element.text,)) elif element.tag == "DOCUMENT_ROOT": rv.append("#document") if element.text is not None: rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) if element.tail is not None: raise TypeError("Document node cannot have tail") if hasattr(element, "attrib") and len(element.attrib): raise TypeError("Document node cannot have attributes") elif element.tag == ElementTreeCommentType: rv.append("|%s<!-- %s -->" % (' ' * indent, element.text)) else: assert isinstance(element.tag, text_type), \ "Expected unicode, got %s, %s" % (type(element.tag), element.tag) nsmatch = tag_regexp.match(element.tag) if nsmatch is None: name = element.tag else: ns, name = nsmatch.groups() prefix = constants.prefixes[ns] name = "%s %s" % (prefix, name) rv.append("|%s<%s>" % (' ' * indent, name)) if hasattr(element, "attrib"): attributes = [] for name, value in element.attrib.items(): nsmatch = tag_regexp.match(name) if nsmatch is not None: ns, name = nsmatch.groups() prefix = constants.prefixes[ns] attr_string = "%s %s" % (prefix, name) else: attr_string = name attributes.append((attr_string, value)) for name, value in sorted(attributes): rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value)) if element.text: rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) indent += 2 for child in element: serializeElement(child, indent) if element.tail: rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail)) serializeElement(element, 0) return "\n".join(rv) def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] filter = ihatexml.InfosetFilter() def serializeElement(element): if isinstance(element, ElementTree.ElementTree): element = element.getroot() if element.tag == "<!DOCTYPE>": if element.get("publicId") or element.get("systemId"): publicId = element.get("publicId") or "" systemId = element.get("systemId") or "" rv.append("""<!DOCTYPE %s PUBLIC "%s" "%s">""" % (element.text, publicId, systemId)) else: rv.append("<!DOCTYPE %s>" % (element.text,)) elif element.tag == "DOCUMENT_ROOT": if element.text is not None: rv.append(element.text) if element.tail is not None: raise TypeError("Document node cannot have tail") if hasattr(element, "attrib") and len(element.attrib): raise TypeError("Document node cannot have attributes") for child in element: serializeElement(child) elif element.tag == ElementTreeCommentType: rv.append("<!--%s-->" % (element.text,)) else: # This is assumed to be an ordinary element if not element.attrib: rv.append("<%s>" % (filter.fromXmlName(element.tag),)) else: attr = " ".join(["%s=\"%s\"" % ( filter.fromXmlName(name), value) for name, value in element.attrib.items()]) rv.append("<%s %s>" % (element.tag, attr)) if element.text: rv.append(element.text) for child in element: serializeElement(child) rv.append("</%s>" % (element.tag,)) if element.tail: rv.append(element.tail) serializeElement(element) return "".join(rv) class TreeBuilder(_base.TreeBuilder): documentClass = Document doctypeClass = DocumentType elementClass = Element commentClass = Comment fragmentClass = DocumentFragment implementation = ElementTreeImplementation def testSerializer(self, element): return testSerializer(element) def getDocument(self): if fullTree: return self.document._element else: if self.defaultNamespace is not None: return self.document._element.find( "{%s}html" % self.defaultNamespace) else: return self.document._element.find("html") def getFragment(self): return _base.TreeBuilder.getFragment(self)._element return locals() getETreeModule = moduleFactoryFactory(getETreeBuilder)
gpl-3.0
wshallum/ansible
lib/ansible/modules/network/f5/bigip_vlan.py
32
13440
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2016 F5 Networks Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: bigip_vlan short_description: Manage VLANs on a BIG-IP system description: - Manage VLANs on a BIG-IP system version_added: "2.2" options: description: description: - The description to give to the VLAN. tagged_interfaces: description: - Specifies a list of tagged interfaces and trunks that you want to configure for the VLAN. Use tagged interfaces or trunks when you want to assign a single interface or trunk to multiple VLANs. required: false aliases: - tagged_interface untagged_interfaces: description: - Specifies a list of untagged interfaces and trunks that you want to configure for the VLAN. required: false aliases: - untagged_interface name: description: - The VLAN to manage. If the special VLAN C(ALL) is specified with the C(state) value of C(absent) then all VLANs will be removed. required: true state: description: - The state of the VLAN on the system. When C(present), guarantees that the VLAN exists with the provided attributes. When C(absent), removes the VLAN from the system. required: false default: present choices: - absent - present tag: description: - Tag number for the VLAN. The tag number can be any integer between 1 and 4094. The system automatically assigns a tag number if you do not specify a value. notes: - Requires the f5-sdk Python package on the host. This is as easy as pip install f5-sdk. - Requires BIG-IP versions >= 12.0.0 extends_documentation_fragment: f5 requirements: - f5-sdk author: - Tim Rupp (@caphrim007) ''' EXAMPLES = ''' - name: Create VLAN bigip_vlan: name: "net1" password: "secret" server: "lb.mydomain.com" user: "admin" validate_certs: "no" delegate_to: localhost - name: Set VLAN tag bigip_vlan: name: "net1" password: "secret" server: "lb.mydomain.com" tag: "2345" user: "admin" validate_certs: "no" delegate_to: localhost - name: Add VLAN 2345 as tagged to interface 1.1 bigip_vlan: tagged_interface: 1.1 name: "net1" password: "secret" server: "lb.mydomain.com" tag: "2345" user: "admin" validate_certs: "no" delegate_to: localhost - name: Add VLAN 1234 as tagged to interfaces 1.1 and 1.2 bigip_vlan: tagged_interfaces: - 1.1 - 1.2 name: "net1" password: "secret" server: "lb.mydomain.com" tag: "1234" user: "admin" validate_certs: "no" delegate_to: localhost ''' RETURN = ''' description: description: The description set on the VLAN returned: changed type: string sample: foo VLAN interfaces: description: Interfaces that the VLAN is assigned to returned: changed type: list sample: ['1.1','1.2'] name: description: The name of the VLAN returned: changed type: string sample: net1 partition: description: The partition that the VLAN was created on returned: changed type: string sample: Common tag: description: The ID of the VLAN returned: changed type: int sample: 2345 ''' try: from f5.bigip import ManagementRoot from icontrol.session import iControlUnexpectedHTTPError HAS_F5SDK = True except ImportError: HAS_F5SDK = False class BigIpVlan(object): def __init__(self, *args, **kwargs): if not HAS_F5SDK: raise F5ModuleError("The python f5-sdk module is required") # The params that change in the module self.cparams = dict() # Stores the params that are sent to the module self.params = kwargs self.api = ManagementRoot(kwargs['server'], kwargs['user'], kwargs['password'], port=kwargs['server_port']) def present(self): if self.exists(): return self.update() else: return self.create() def absent(self): changed = False if self.exists(): changed = self.delete() return changed def read(self): """Read information and transform it The values that are returned by BIG-IP in the f5-sdk can have encoding attached to them as well as be completely missing in some cases. Therefore, this method will transform the data from the BIG-IP into a format that is more easily consumable by the rest of the class and the parameters that are supported by the module. """ p = dict() name = self.params['name'] partition = self.params['partition'] r = self.api.tm.net.vlans.vlan.load( name=name, partition=partition ) ifcs = r.interfaces_s.get_collection() if hasattr(r, 'tag'): p['tag'] = int(r.tag) if hasattr(r, 'description'): p['description'] = str(r.description) if len(ifcs) is not 0: untagged = [] tagged = [] for x in ifcs: if hasattr(x, 'tagged'): tagged.append(str(x.name)) elif hasattr(x, 'untagged'): untagged.append(str(x.name)) if untagged: p['untagged_interfaces'] = list(set(untagged)) if tagged: p['tagged_interfaces'] = list(set(tagged)) p['name'] = name return p def create(self): params = dict() check_mode = self.params['check_mode'] description = self.params['description'] name = self.params['name'] untagged_interfaces = self.params['untagged_interfaces'] tagged_interfaces = self.params['tagged_interfaces'] partition = self.params['partition'] tag = self.params['tag'] if tag is not None: params['tag'] = tag if untagged_interfaces is not None or tagged_interfaces is not None: tmp = [] ifcs = self.api.tm.net.interfaces.get_collection() ifcs = [str(x.name) for x in ifcs] if len(ifcs) is 0: raise F5ModuleError( 'No interfaces were found' ) pinterfaces = [] if untagged_interfaces: interfaces = untagged_interfaces elif tagged_interfaces: interfaces = tagged_interfaces for ifc in interfaces: ifc = str(ifc) if ifc in ifcs: pinterfaces.append(ifc) if tagged_interfaces: tmp = [dict(name=x, tagged=True) for x in pinterfaces] elif untagged_interfaces: tmp = [dict(name=x, untagged=True) for x in pinterfaces] if tmp: params['interfaces'] = tmp if description is not None: params['description'] = self.params['description'] params['name'] = name params['partition'] = partition self.cparams = camel_dict_to_snake_dict(params) if check_mode: return True d = self.api.tm.net.vlans.vlan d.create(**params) if self.exists(): return True else: raise F5ModuleError("Failed to create the VLAN") def update(self): changed = False params = dict() current = self.read() check_mode = self.params['check_mode'] description = self.params['description'] name = self.params['name'] tag = self.params['tag'] partition = self.params['partition'] tagged_interfaces = self.params['tagged_interfaces'] untagged_interfaces = self.params['untagged_interfaces'] if untagged_interfaces is not None or tagged_interfaces is not None: ifcs = self.api.tm.net.interfaces.get_collection() ifcs = [str(x.name) for x in ifcs] if len(ifcs) is 0: raise F5ModuleError( 'No interfaces were found' ) pinterfaces = [] if untagged_interfaces: interfaces = untagged_interfaces elif tagged_interfaces: interfaces = tagged_interfaces for ifc in interfaces: ifc = str(ifc) if ifc in ifcs: pinterfaces.append(ifc) else: raise F5ModuleError( 'The specified interface "%s" was not found' % (ifc) ) if tagged_interfaces: tmp = [dict(name=x, tagged=True) for x in pinterfaces] if 'tagged_interfaces' in current: if pinterfaces != current['tagged_interfaces']: params['interfaces'] = tmp else: params['interfaces'] = tmp elif untagged_interfaces: tmp = [dict(name=x, untagged=True) for x in pinterfaces] if 'untagged_interfaces' in current: if pinterfaces != current['untagged_interfaces']: params['interfaces'] = tmp else: params['interfaces'] = tmp if description is not None: if 'description' in current: if description != current['description']: params['description'] = description else: params['description'] = description if tag is not None: if 'tag' in current: if tag != current['tag']: params['tag'] = tag else: params['tag'] = tag if params: changed = True params['name'] = name params['partition'] = partition if check_mode: return changed self.cparams = camel_dict_to_snake_dict(params) else: return changed r = self.api.tm.net.vlans.vlan.load( name=name, partition=partition ) r.update(**params) r.refresh() return True def delete(self): params = dict() check_mode = self.params['check_mode'] params['name'] = self.params['name'] params['partition'] = self.params['partition'] self.cparams = camel_dict_to_snake_dict(params) if check_mode: return True dc = self.api.tm.net.vlans.vlan.load(**params) dc.delete() if self.exists(): raise F5ModuleError("Failed to delete the VLAN") return True def exists(self): name = self.params['name'] partition = self.params['partition'] return self.api.tm.net.vlans.vlan.exists( name=name, partition=partition ) def flush(self): result = dict() state = self.params['state'] try: if state == "present": changed = self.present() elif state == "absent": changed = self.absent() except iControlUnexpectedHTTPError as e: raise F5ModuleError(str(e)) result.update(**self.cparams) result.update(dict(changed=changed)) return result def main(): argument_spec = f5_argument_spec() meta_args = dict( description=dict(required=False, default=None), tagged_interfaces=dict(required=False, default=None, type='list', aliases=['tagged_interface']), untagged_interfaces=dict(required=False, default=None, type='list', aliases=['untagged_interface']), name=dict(required=True), tag=dict(required=False, default=None, type='int') ) argument_spec.update(meta_args) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[ ['tagged_interfaces', 'untagged_interfaces'] ] ) try: obj = BigIpVlan(check_mode=module.check_mode, **module.params) result = obj.flush() module.exit_json(**result) except F5ModuleError as e: module.fail_json(msg=str(e)) from ansible.module_utils.basic import * from ansible.module_utils.ec2 import camel_dict_to_snake_dict from ansible.module_utils.f5 import * if __name__ == '__main__': main()
gpl-3.0
hojel/calibre
src/calibre/gui2/device_drivers/configwidget.py
15
7661
# -*- coding: utf-8 -*- __license__ = 'GPL 3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import textwrap from PyQt5.Qt import (QWidget, QListWidgetItem, Qt, QLabel, QLineEdit, QCheckBox, QComboBox) from calibre.gui2 import error_dialog, question_dialog from calibre.gui2.device_drivers.configwidget_ui import Ui_ConfigWidget from calibre.utils.formatter import validation_formatter from calibre.ebooks import BOOK_EXTENSIONS class ConfigWidget(QWidget, Ui_ConfigWidget): def __init__(self, settings, all_formats, supports_subdirs, must_read_metadata, supports_use_author_sort, extra_customization_message, device, extra_customization_choices=None): QWidget.__init__(self) Ui_ConfigWidget.__init__(self) self.setupUi(self) self.settings = settings all_formats = set(all_formats) self.calibre_known_formats = device.FORMATS try: self.device_name = device.get_gui_name() except TypeError: self.device_name = getattr(device, 'gui_name', None) or _('Device') if device.USER_CAN_ADD_NEW_FORMATS: all_formats = set(all_formats) | set(BOOK_EXTENSIONS) format_map = settings.format_map disabled_formats = list(set(all_formats).difference(format_map)) for format in format_map + list(sorted(disabled_formats)): item = QListWidgetItem(format, self.columns) item.setData(Qt.UserRole, (format)) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) item.setCheckState(Qt.Checked if format in format_map else Qt.Unchecked) self.column_up.clicked.connect(self.up_column) self.column_down.clicked.connect(self.down_column) if device.HIDE_FORMATS_CONFIG_BOX: self.groupBox.hide() if supports_subdirs: self.opt_use_subdirs.setChecked(self.settings.use_subdirs) else: self.opt_use_subdirs.hide() if not must_read_metadata: self.opt_read_metadata.setChecked(self.settings.read_metadata) else: self.opt_read_metadata.hide() if supports_use_author_sort: self.opt_use_author_sort.setChecked(self.settings.use_author_sort) else: self.opt_use_author_sort.hide() if extra_customization_message: extra_customization_choices = extra_customization_choices or {} def parse_msg(m): msg, _, tt = m.partition(':::') if m else ('', '', '') return msg.strip(), textwrap.fill(tt.strip(), 100) if isinstance(extra_customization_message, list): self.opt_extra_customization = [] if len(extra_customization_message) > 6: row_func = lambda x, y: ((x/2) * 2) + y col_func = lambda x: x%2 else: row_func = lambda x, y: x*2 + y col_func = lambda x: 0 for i, m in enumerate(extra_customization_message): label_text, tt = parse_msg(m) if not label_text: self.opt_extra_customization.append(None) continue if isinstance(settings.extra_customization[i], bool): self.opt_extra_customization.append(QCheckBox(label_text)) self.opt_extra_customization[-1].setToolTip(tt) self.opt_extra_customization[i].setChecked(bool(settings.extra_customization[i])) elif i in extra_customization_choices: cb = QComboBox(self) self.opt_extra_customization.append(cb) l = QLabel(label_text) l.setToolTip(tt), cb.setToolTip(tt), l.setBuddy(cb), cb.setToolTip(tt) for li in sorted(extra_customization_choices[i]): self.opt_extra_customization[i].addItem(li) cb.setCurrentIndex(max(0, cb.findText(settings.extra_customization[i]))) else: self.opt_extra_customization.append(QLineEdit(self)) l = QLabel(label_text) l.setToolTip(tt) self.opt_extra_customization[i].setToolTip(tt) l.setBuddy(self.opt_extra_customization[i]) l.setWordWrap(True) self.opt_extra_customization[i].setText(settings.extra_customization[i]) self.opt_extra_customization[i].setCursorPosition(0) self.extra_layout.addWidget(l, row_func(i, 0), col_func(i)) self.extra_layout.addWidget(self.opt_extra_customization[i], row_func(i, 1), col_func(i)) else: self.opt_extra_customization = QLineEdit() label_text, tt = parse_msg(extra_customization_message) l = QLabel(label_text) l.setToolTip(tt) l.setBuddy(self.opt_extra_customization) l.setWordWrap(True) if settings.extra_customization: self.opt_extra_customization.setText(settings.extra_customization) self.opt_extra_customization.setCursorPosition(0) self.opt_extra_customization.setCursorPosition(0) self.extra_layout.addWidget(l, 0, 0) self.extra_layout.addWidget(self.opt_extra_customization, 1, 0) self.opt_save_template.setText(settings.save_template) def up_column(self): idx = self.columns.currentRow() if idx > 0: self.columns.insertItem(idx-1, self.columns.takeItem(idx)) self.columns.setCurrentRow(idx-1) def down_column(self): idx = self.columns.currentRow() if idx < self.columns.count()-1: self.columns.insertItem(idx+1, self.columns.takeItem(idx)) self.columns.setCurrentRow(idx+1) def format_map(self): formats = [unicode(self.columns.item(i).data(Qt.UserRole) or '') for i in range(self.columns.count()) if self.columns.item(i).checkState()==Qt.Checked] return formats def use_subdirs(self): return self.opt_use_subdirs.isChecked() def read_metadata(self): return self.opt_read_metadata.isChecked() def use_author_sort(self): return self.opt_use_author_sort.isChecked() def validate(self): formats = set(self.format_map()) extra = formats - set(self.calibre_known_formats) if extra: fmts = sorted([x.upper() for x in extra]) if not question_dialog(self, _('Unknown formats'), _('You have enabled the <b>{0}</b> formats for' ' your {1}. The {1} may not support them.' ' If you send these formats to your {1} they ' 'may not work. Are you sure?').format( (', '.join(fmts)), self.device_name)): return False tmpl = unicode(self.opt_save_template.text()) try: validation_formatter.validate(tmpl) return True except Exception as err: error_dialog(self, _('Invalid template'), '<p>'+_('The template %s is invalid:')%tmpl + '<br>'+unicode(err), show=True) return False
gpl-3.0
with-git/tensorflow
tensorflow/contrib/graph_editor/tests/transform_test.py
26
8575
# Copyright 2015 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.contrib.graph_editor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np from tensorflow.contrib import graph_editor as ge from tensorflow.contrib.graph_editor.tests import match from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test # Precision tolerance for floating-point value tests. ERROR_TOLERANCE = 1e-3 class TransformTest(test.TestCase): def setUp(self): self.graph = ops.Graph() with self.graph.as_default(): c0 = constant_op.constant(1.0, shape=[10], name="Const") c1 = constant_op.constant(1.0, shape=[10], name="Const") c2 = constant_op.constant(1.0, shape=[10], name="Const") i = constant_op.constant(1.0, shape=[10], name="Input") self.o = math_ops.add(c2, math_ops.add(c1, math_ops.add(c0, i))) def test_copy(self): graph = ops.Graph() _, info = ge.copy(self.graph, graph) self.assertEqual( set(op.name for op in self.graph.get_operations()), set(op.name for op in graph.get_operations())) src_ops = self.graph.get_operations() dst_ops = graph.get_operations() for op in src_ops: op_ = info.transformed(op) self.assertTrue(op_ in dst_ops) self.assertEqual(op.name, op_.name) self.assertEqual(info.original(op_), op) src_ts = ge.util.get_tensors(self.graph) dst_ts = ge.util.get_tensors(graph) for t in src_ts: t_ = info.transformed(t) self.assertTrue(t_ in dst_ts) self.assertEqual(t.name, t_.name) self.assertEqual(info.original(t_), t) def test_copy_assert(self): ops.reset_default_graph() a = constant_op.constant(1) b = constant_op.constant(1) eq = math_ops.equal(a, b) assert_op = control_flow_ops.Assert(eq, [a, b]) with ops.control_dependencies([assert_op]): _ = math_ops.add(a, b) sgv = ge.make_view([assert_op, eq.op, a.op, b.op]) copier = ge.Transformer() _, info = copier(sgv, sgv.graph, "", "") new_assert_op = info.transformed(assert_op) self.assertIsNotNone(new_assert_op) def test_transform(self): transformer = ge.Transformer() def my_transform_op_handler(info, op): add_noise = op.name.startswith("Add") op_, op_outputs_ = ge.transform.copy_op_handler(info, op) if not add_noise: return op_, op_outputs_ # add some noise to op with info.graph_.as_default(): t_ = math_ops.add( constant_op.constant(1.0, shape=[10], name="Noise"), op_.outputs[0], name="AddNoise") # return the "noisy" op return op_, [t_] transformer.transform_op_handler = my_transform_op_handler graph = ops.Graph() transformer(self.graph, graph, "", "") matcher0 = match.OpMatcher("AddNoise").input_ops( "Noise", match.OpMatcher("Add").input_ops("Const", "Input")) matcher1 = match.OpMatcher("AddNoise_1").input_ops( "Noise_1", match.OpMatcher("Add_1").input_ops("Const_1", matcher0)) matcher2 = match.OpMatcher("AddNoise_2").input_ops( "Noise_2", match.OpMatcher("Add_2").input_ops("Const_2", matcher1)) top = ge.select_ops("^AddNoise_2$", graph=graph)[0] self.assertTrue(matcher2(top)) def test_copy_with_input_replacements(self): with self.graph.as_default(): ten = constant_op.constant(10.0, shape=[10], name="Input") sgv, _ = ge.copy_with_input_replacements(self.o.op, {self.o.op.inputs[1]: ten}) with session.Session() as sess: val = sess.run(sgv.outputs[0]) self.assertNear( np.linalg.norm(val - np.array([11])), 0.0, ERROR_TOLERANCE) def test_graph_replace(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") c_new = ge.graph_replace(c, {a: a_new}) with session.Session() as sess: sess.run(variables.global_variables_initializer()) c_val, c_new_val = sess.run([c, c_new]) self.assertNear(c_val, 2.001, ERROR_TOLERANCE) self.assertNear(c_new_val, 3.001, ERROR_TOLERANCE) def test_graph_replace_dict(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") c_new = ge.graph_replace({"c": c}, {a: a_new}) self.assertTrue(isinstance(c_new, dict)) with session.Session() as sess: sess.run(variables.global_variables_initializer()) c_val, c_new_val = sess.run([c, c_new]) self.assertTrue(isinstance(c_new_val, dict)) self.assertNear(c_val, 2.001, ERROR_TOLERANCE) self.assertNear(c_new_val["c"], 3.001, ERROR_TOLERANCE) def test_graph_replace_ordered_dict(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") c_new = ge.graph_replace(collections.OrderedDict({"c": c}), {a: a_new}) self.assertTrue(isinstance(c_new, collections.OrderedDict)) def test_graph_replace_named_tuple(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") one_tensor = collections.namedtuple("OneTensor", ["t"]) c_new = ge.graph_replace(one_tensor(c), {a: a_new}) self.assertTrue(isinstance(c_new, one_tensor)) def test_graph_replace_missing(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = constant_op.constant(2.0, name="b") c = a + 2 * b d = constant_op.constant(2.0, name="d") res = ge.graph_replace([b, c], {a: d}) self.assertEqual(res[0].name, "b:0") self.assertEqual(res[1].name, "add_1:0") def test_graph_replace_gradients(self): ops.reset_default_graph() w = variables.Variable(0.0, name="w") y = math_ops.multiply(math_ops.multiply(w, w, name="mul1"), w, name="mul2") g = gradients_impl.gradients(y, w, name="grad")[0] # Extract the operations. replacement_ts = {w.value(): g} original_mul1_grad = (ops.get_default_graph(). get_operation_by_name("grad/mul1_grad/mul_1")) # Should not raise exception. res = ge.graph_replace(g, replacement_ts, dst_scope="res") # Extract the operations after graph_replace. result_mul1_grad = (ops.get_default_graph(). get_operation_by_name("res/grad/mul1_grad/mul_1")) # Make sure _original_ops are as expected. self.assertEquals(original_mul1_grad._original_op.name, u"mul1") self.assertEquals(result_mul1_grad._original_op.name, u"res/mul1") self.assertNotEquals(res.name, g.name) with session.Session() as sess: sess.run(variables.global_variables_initializer()) g_val, res_val = sess.run([g, res]) self.assertNear(g_val, 0.0, ERROR_TOLERANCE) self.assertNear(res_val, 0.0, ERROR_TOLERANCE) if __name__ == "__main__": test.main()
apache-2.0
sampepose/flownet2-tf
src/utils.py
1
1593
import tensorflow as tf # Thanks, https://github.com/tensorflow/tensorflow/issues/4079 def LeakyReLU(x, leak=0.1, name="lrelu"): with tf.variable_scope(name): f1 = 0.5 * (1.0 + leak) f2 = 0.5 * (1.0 - leak) return f1 * x + f2 * abs(x) def average_endpoint_error(labels, predictions): """ Given labels and predictions of size (N, H, W, 2), calculates average endpoint error: sqrt[sum_across_channels{(X - Y)^2}] """ num_samples = predictions.shape.as_list()[0] with tf.name_scope(None, "average_endpoint_error", (predictions, labels)) as scope: predictions = tf.to_float(predictions) labels = tf.to_float(labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) squared_difference = tf.square(tf.subtract(predictions, labels)) # sum across channels: sum[(X - Y)^2] -> N, H, W, 1 loss = tf.reduce_sum(squared_difference, 3, keep_dims=True) loss = tf.sqrt(loss) return tf.reduce_sum(loss) / num_samples def pad(tensor, num=1): """ Pads the given tensor along the height and width dimensions with `num` 0s on each side """ return tf.pad(tensor, [[0, 0], [num, num], [num, num], [0, 0]], "CONSTANT") def antipad(tensor, num=1): """ Performs a crop. "padding" for a deconvolutional layer (conv2d tranpose) removes padding from the output rather than adding it to the input. """ batch, h, w, c = tensor.shape.as_list() return tf.slice(tensor, begin=[0, num, num, 0], size=[batch, h - 2 * num, w - 2 * num, c])
mit
bwasti/caffe2
caffe2/python/mkl/convnet_benchmarks.py
1
21125
## @package convnet_benchmarks # Module caffe2.python.convnet_benchmarks from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals """ Benchmark for common convnets. Speed on Titan X, with 10 warmup steps and 10 main steps and with different versions of cudnn, are as follows (time reported below is per-batch time, forward / forward+backward): CuDNN V3 CuDNN v4 AlexNet 32.5 / 108.0 27.4 / 90.1 OverFeat 113.0 / 342.3 91.7 / 276.5 Inception 134.5 / 485.8 125.7 / 450.6 VGG (batch 64) 200.8 / 650.0 164.1 / 551.7 Speed on Inception with varied batch sizes and CuDNN v4 is as follows: Batch Size Speed per batch Speed per image 16 22.8 / 72.7 1.43 / 4.54 32 38.0 / 127.5 1.19 / 3.98 64 67.2 / 233.6 1.05 / 3.65 128 125.7 / 450.6 0.98 / 3.52 Speed on Tesla M40, which 10 warmup steps and 10 main steps and with cudnn v4, is as follows: AlexNet 68.4 / 218.1 OverFeat 210.5 / 630.3 Inception 300.2 / 1122.2 VGG (batch 64) 405.8 / 1327.7 (Note that these numbers involve a "full" backprop, i.e. the gradient with respect to the input image is also computed.) To get the numbers, simply run: for MODEL in AlexNet OverFeat Inception; do PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 128 --model $MODEL --forward_only True done for MODEL in AlexNet OverFeat Inception; do PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 128 --model $MODEL done PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 64 --model VGGA --forward_only True PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 64 --model VGGA for BS in 16 32 64 128; do PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size $BS --model Inception --forward_only True PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size $BS --model Inception done Note that VGG needs to be run at batch 64 due to memory limit on the backward pass. """ import argparse from caffe2.python import brew, cnn, workspace from caffe2.python.model_helper import ModelHelper import numpy as np def MLP(order, cudnn_ws, mkl): model = ModelHelper(name="benchmark") d = 256 depth = 20 width = 3 for i in range(depth): for j in range(width): current = "fc_{}_{}".format(i, j) if i > 0 else "data" next_ = "fc_{}_{}".format(i + 1, j) brew.fc( model, current, next_, dim_in=d, dim_out=d, weight_init=('XavierFill', {}), bias_init=('XavierFill', {})) brew.sum(model, ["fc_{}_{}".format(depth, j) for j in range(width)], ["sum"]) brew.fc(model, "sum", "last", dim_in=d, dim_out=1000, weight_init=('XavierFill', {}), bias_init=('XavierFill', {})) xent = model.LabelCrossEntropy(["last", "label"], "xent") if not mkl: model.AveragedLoss(xent, "loss") return model, d def AlexNet(order, cudnn_ws, mkl): my_arg_scope = {'order': order, 'use_cudnn': True, 'cudnn_exhaustive_search': True, 'ws_nbytes_limit': str(cudnn_ws)} model = ModelHelper(name="alexnet", arg_scope=my_arg_scope) conv1 = brew.conv( model, "data", "conv1", 3, 64, 11, ('XavierFill', {}), ('ConstantFill', {}), stride=4, pad=2 ) relu1 = brew.relu(model, conv1, "conv1") pool1 = brew.max_pool(model, relu1, "pool1", kernel=3, stride=2) conv2 = brew.conv( model, pool1, "conv2", 64, 192, 5, ('XavierFill', {}), ('ConstantFill', {}), pad=2 ) relu2 = brew.relu(model, conv2, "conv2") pool2 = brew.max_pool(model, relu2, "pool2", kernel=3, stride=2) conv3 = brew.conv( model, pool2, "conv3", 192, 384, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = brew.relu(model, conv3, "conv3") conv4 = brew.conv( model, relu3, "conv4", 384, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = brew.relu(model, conv4, "conv4") conv5 = brew.conv( model, relu4, "conv5", 256, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = brew.relu(model, conv5, "conv5") pool5 = brew.max_pool(model, relu5, "pool5", kernel=3, stride=2) fc6 = brew.fc( model, pool5, "fc6", 256 * 6 * 6, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu6 = brew.relu(model, fc6, "fc6") fc7 = brew.fc( model, relu6, "fc7", 4096, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu7 = brew.relu(model, fc7, "fc7") fc8 = brew.fc( model, relu7, "fc8", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) pred = brew.softmax(model, fc8, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") if not mkl: loss = model.AveragedLoss(xent, "loss") return model, 224 def OverFeat(order, cudnn_ws, mkl): my_arg_scope = {'order': order, 'use_cudnn': True, 'cudnn_exhaustive_search': True, 'ws_nbytes_limit': str(cudnn_ws)} model = ModelHelper(name='overfeat', arg_scope=my_arg_scope) conv1 = brew.conv( model, "data", "conv1", 3, 96, 11, ('XavierFill', {}), ('ConstantFill', {}), stride=4 ) relu1 = brew.relu(model, conv1, "conv1") pool1 = brew.max_pool(model, relu1, "pool1", kernel=2, stride=2) conv2 = brew.conv( model, pool1, "conv2", 96, 256, 5, ('XavierFill', {}), ('ConstantFill', {}) ) relu2 = brew.relu(model, conv2, "conv2") pool2 = brew.max_pool(model, relu2, "pool2", kernel=2, stride=2) conv3 = brew.conv( model, pool2, "conv3", 256, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = brew.relu(model, conv3, "conv3") conv4 = brew.conv( model, relu3, "conv4", 512, 1024, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = brew.relu(model, conv4, "conv4") conv5 = brew.conv( model, relu4, "conv5", 1024, 1024, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = brew.relu(model, conv5, "conv5") pool5 = brew.max_pool(model, relu5, "pool5", kernel=2, stride=2) fc6 = brew.fc( model, pool5, "fc6", 1024 * 6 * 6, 3072, ('XavierFill', {}), ('ConstantFill', {}) ) relu6 = brew.relu(model, fc6, "fc6") fc7 = brew.fc( model, relu6, "fc7", 3072, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu7 = brew.relu(model, fc7, "fc7") fc8 = brew.fc( model, relu7, "fc8", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) pred = brew.softmax(model, fc8, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") if not mkl: loss = model.AveragedLoss(xent, "loss") return model, 231 def VGGA(order, cudnn_ws, mkl): my_arg_scope = {'order': order, 'use_cudnn': True, 'cudnn_exhaustive_search': True, 'ws_nbytes_limit': str(cudnn_ws)} model = ModelHelper(name='vgg-a', arg_scope=my_arg_scope) conv1 = brew.conv( model, "data", "conv1", 3, 64, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu1 = brew.relu(model, conv1, "conv1") pool1 = brew.max_pool(model, relu1, "pool1", kernel=2, stride=2) conv2 = brew.conv( model, pool1, "conv2", 64, 128, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu2 = brew.relu(model, conv2, "conv2") pool2 = brew.max_pool(model, relu2, "pool2", kernel=2, stride=2) conv3 = brew.conv( model, pool2, "conv3", 128, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = brew.relu(model, conv3, "conv3") conv4 = brew.conv( model, relu3, "conv4", 256, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = brew.relu(model, conv4, "conv4") pool4 = brew.max_pool(model, relu4, "pool4", kernel=2, stride=2) conv5 = brew.conv( model, pool4, "conv5", 256, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = brew.relu(model, conv5, "conv5") conv6 = brew.conv( model, relu5, "conv6", 512, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu6 = brew.relu(model, conv6, "conv6") pool6 = brew.max_pool(model, relu6, "pool6", kernel=2, stride=2) conv7 = brew.conv( model, pool6, "conv7", 512, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu7 = brew.relu(model, conv7, "conv7") conv8 = brew.conv( model, relu7, "conv8", 512, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu8 = brew.relu(model, conv8, "conv8") pool8 = brew.max_pool(model, relu8, "pool8", kernel=2, stride=2) fcix = brew.fc( model, pool8, "fcix", 512 * 7 * 7, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) reluix = brew.relu(model, fcix, "fcix") fcx = brew.fc( model, reluix, "fcx", 4096, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relux = brew.relu(model, fcx, "fcx") fcxi = brew.fc( model, relux, "fcxi", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) pred = brew.softmax(model, fcxi, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") if not mkl: loss = model.AveragedLoss(xent, "loss") return model, 231 def _InceptionModule( model, input_blob, input_depth, output_name, conv1_depth, conv3_depths, conv5_depths, pool_depth ): # path 1: 1x1 conv conv1 = brew.conv( model, input_blob, output_name + ":conv1", input_depth, conv1_depth, 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv1 = brew.relu(model, conv1, conv1) # path 2: 1x1 conv + 3x3 conv conv3_reduce = brew.conv( model, input_blob, output_name + ":conv3_reduce", input_depth, conv3_depths[0], 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv3_reduce = brew.relu(model, conv3_reduce, conv3_reduce) conv3 = brew.conv( model, conv3_reduce, output_name + ":conv3", conv3_depths[0], conv3_depths[1], 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) conv3 = brew.relu(model, conv3, conv3) # path 3: 1x1 conv + 5x5 conv conv5_reduce = brew.conv( model, input_blob, output_name + ":conv5_reduce", input_depth, conv5_depths[0], 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv5_reduce = brew.relu(model, conv5_reduce, conv5_reduce) conv5 = brew.conv( model, conv5_reduce, output_name + ":conv5", conv5_depths[0], conv5_depths[1], 5, ('XavierFill', {}), ('ConstantFill', {}), pad=2 ) conv5 = brew.relu(model, conv5, conv5) # path 4: pool + 1x1 conv pool = brew.max_pool( model, input_blob, output_name + ":pool", kernel=3, stride=1, pad=1 ) pool_proj = brew.conv( model, pool, output_name + ":pool_proj", input_depth, pool_depth, 1, ('XavierFill', {}), ('ConstantFill', {}) ) pool_proj = brew.relu(model, pool_proj, pool_proj) output = brew.concat(model, [conv1, conv3, conv5, pool_proj], output_name) return output def Inception(order, cudnn_ws, mkl): my_arg_scope = {'order': order, 'use_cudnn': True, 'cudnn_exhaustive_search': True, 'ws_nbytes_limit': str(cudnn_ws)} model = ModelHelper(name="inception", arg_scope=my_arg_scope) conv1 = brew.conv( model, "data", "conv1", 3, 64, 7, ('XavierFill', {}), ('ConstantFill', {}), stride=2, pad=3 ) relu1 = brew.relu(model, conv1, "conv1") pool1 = brew.max_pool(model, relu1, "pool1", kernel=3, stride=2, pad=1) conv2a = brew.conv( model, pool1, "conv2a", 64, 64, 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv2a = brew.relu(model, conv2a, conv2a) conv2 = brew.conv( model, conv2a, "conv2", 64, 192, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu2 = brew.relu(model, conv2, "conv2") pool2 = brew.max_pool(model, relu2, "pool2", kernel=3, stride=2, pad=1) # Inception modules inc3 = _InceptionModule( model, pool2, 192, "inc3", 64, [96, 128], [16, 32], 32 ) inc4 = _InceptionModule( model, inc3, 256, "inc4", 128, [128, 192], [32, 96], 64 ) pool5 = brew.max_pool(model, inc4, "pool5", kernel=3, stride=2, pad=1) inc5 = _InceptionModule( model, pool5, 480, "inc5", 192, [96, 208], [16, 48], 64 ) inc6 = _InceptionModule( model, inc5, 512, "inc6", 160, [112, 224], [24, 64], 64 ) inc7 = _InceptionModule( model, inc6, 512, "inc7", 128, [128, 256], [24, 64], 64 ) inc8 = _InceptionModule( model, inc7, 512, "inc8", 112, [144, 288], [32, 64], 64 ) inc9 = _InceptionModule( model, inc8, 528, "inc9", 256, [160, 320], [32, 128], 128 ) pool9 = brew.max_pool(model, inc9, "pool9", kernel=3, stride=2, pad=1) inc10 = _InceptionModule( model, pool9, 832, "inc10", 256, [160, 320], [32, 128], 128 ) inc11 = _InceptionModule( model, inc10, 832, "inc11", 384, [192, 384], [48, 128], 128 ) pool11 = brew.average_pool(model, inc11, "pool11", kernel=7, stride=1) fc = brew.fc( model, pool11, "fc", 1024, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) # It seems that Soumith's benchmark does not have softmax on top # for Inception. We will add it anyway so we can have a proper # backward pass. pred = brew.softmax(model, fc, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") if not mkl: loss = model.AveragedLoss(xent, "loss") return model, 224 def AddParameterUpdate(model): """ Simple plain SGD update -- not tuned to actually train the models """ ITER = brew.iter(model, "iter") LR = model.LearningRate( ITER, "LR", base_lr=-1e-8, policy="step", stepsize=10000, gamma=0.999) ONE = model.param_init_net.ConstantFill([], "ONE", shape=[1], value=1.0) for param in model.params: param_grad = model.param_to_grad[param] model.WeightedSum([param, ONE, param_grad, LR], param) def Benchmark(model_gen, arg): model, input_size = model_gen(arg.order, arg.cudnn_ws, arg.mkl) model.Proto().type = arg.net_type model.Proto().num_workers = arg.num_workers # In order to be able to run everything without feeding more stuff, let's # add the data and label blobs to the parameter initialization net as well. if arg.order == "NCHW": input_shape = [arg.batch_size, 3, input_size, input_size] else: input_shape = [arg.batch_size, input_size, input_size, 3] if arg.model == "MLP": input_shape = [arg.batch_size, input_size] model.param_init_net.GaussianFill( [], "data", shape=input_shape, mean=0.0, std=1.0 ) #MKL doesn't support int, so have to use numpy if arg.mkl: label = np.random.randint(low=0, high=1000, size=(arg.batch_size,)).astype(np.int32) workspace.FeedBlob("label", label) else: model.param_init_net.UniformIntFill( [], "label", shape=[arg.batch_size, ], min=0, max=999 ) if arg.forward_only: print('{}: running forward only.'.format(arg.model)) else: if arg.mkl: print( '==WARNING==\n' 'forward-backward not supported yet in MKL, so exiting' ) print('{}: running forward-backward.'.format(arg.model)) model.AddGradientOperators(["loss"]) AddParameterUpdate(model) if arg.order == 'NHWC': print( '==WARNING==\n' 'NHWC order with CuDNN may not be supported yet, so I might\n' 'exit suddenly.' ) if not arg.cpu: if arg.mkl: model.param_init_net.RunAllOnMKL() model.net.RunAllOnMKL() else: model.param_init_net.RunAllOnGPU() model.net.RunAllOnGPU() if arg.engine: for op in model.net.Proto().op: op.engine = arg.engine if arg.dump_model: # Writes out the pbtxt for benchmarks on e.g. Android with open( "{0}_init_batch_{1}.pbtxt".format(arg.model, arg.batch_size), "w" ) as fid: fid.write(str(model.param_init_net.Proto())) with open("{0}.pbtxt".format(arg.model, arg.batch_size), "w") as fid: fid.write(str(model.net.Proto())) workspace.RunNetOnce(model.param_init_net) workspace.CreateNet(model.net) workspace.BenchmarkNet( model.net.Proto().name, arg.warmup_iterations, arg.iterations, arg.layer_wise_benchmark) def GetArgumentParser(): parser = argparse.ArgumentParser(description="Caffe2 benchmark.") parser.add_argument( "--batch_size", type=int, default=128, help="The batch size." ) parser.add_argument("--model", type=str, help="The model to benchmark.") parser.add_argument( "--order", type=str, default="NCHW", help="The order to evaluate." ) parser.add_argument( "--cudnn_ws", type=int, help="The cudnn workspace size." ) parser.add_argument( "--iterations", type=int, default=10, help="Number of iterations to run the network." ) parser.add_argument( "--warmup_iterations", type=int, default=10, help="Number of warm-up iterations before benchmarking." ) parser.add_argument( "--forward_only", action='store_true', help="If set, only run the forward pass." ) parser.add_argument( "--layer_wise_benchmark", action='store_true', help="If True, run the layer-wise benchmark as well." ) parser.add_argument( "--cpu", action='store_true', help="If True, run testing on CPU instead of GPU." ) parser.add_argument( "--mkl", action='store_true', help="If True, run testing on CPU-MKL instead of GPU." ) parser.add_argument( "--engine", type=str, default="", help="If set, blindly prefer the given engine(s) for every op.") parser.add_argument( "--dump_model", action='store_true', help="If True, dump the model prototxts to disk." ) parser.add_argument("--net_type", type=str, default="simple") parser.add_argument("--num_workers", type=int, default=2) parser.add_argument("--use-nvtx", default=False, action='store_true') parser.add_argument("--htrace_span_log_path", type=str) return parser if __name__ == '__main__': args = GetArgumentParser().parse_args() if ( not args.batch_size or not args.model or not args.order ): GetArgumentParser().print_help() else: workspace.GlobalInit( ['caffe2', '--caffe2_log_level=0'] + (['--caffe2_use_nvtx'] if args.use_nvtx else []) + (['--caffe2_htrace_span_log_path=' + args.htrace_span_log_path] if args.htrace_span_log_path else [])) model_map = { 'AlexNet': AlexNet, 'OverFeat': OverFeat, 'VGGA': VGGA, 'Inception': Inception, 'MLP': MLP, } Benchmark(model_map[args.model], args)
apache-2.0
mbr0wn/gnuradio
gr-trellis/python/trellis/qa_trellis.py
5
4351
#!/usr/bin/env python # # Copyright 2004,2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # import math import os from gnuradio import gr, gr_unittest, trellis, digital, analog, blocks fsm_args = {"awgn1o2_4": [2, 4, 4, [0, 2, 0, 2, 1, 3, 1, 3], [0, 3, 3, 0, 1, 2, 2, 1], ], "rep2": [2, 1, 4, [0, 0], [0, 3]], "nothing": [2, 1, 2, [0, 0], [0, 1]], } constells = {2: digital.constellation_bpsk(), 4: digital.constellation_qpsk(), } class test_trellis (gr_unittest.TestCase): def test_001_fsm(self): f = trellis.fsm(*fsm_args["awgn1o2_4"]) self.assertEqual( fsm_args["awgn1o2_4"], [ f.I(), f.S(), f.O(), f.NS(), f.OS()]) def test_002_fsm(self): f = trellis.fsm(*fsm_args["awgn1o2_4"]) g = trellis.fsm(f) self.assertEqual((g.I(), g.S(), g.O(), g.NS(), g.OS()), (f.I(), f.S(), f.O(), f.NS(), f.OS())) def test_003_fsm(self): # FIXME: no file "awgn1o2_4.fsm" #f = trellis.fsm("awgn1o2_4.fsm") # self.assertEqual(fsm_args["awgn1o2_4"],(f.I(),f.S(),f.O(),f.NS(),f.OS())) pass def test_004_fsm(self): """ Test to make sure fsm works with a single state fsm.""" # Just checking that it initializes properly. f = trellis.fsm(*fsm_args["rep2"]) def test_001_interleaver(self): K = 5 IN = [1, 2, 3, 4, 0] DIN = [4, 0, 1, 2, 3] i = trellis.interleaver(K, IN) self.assertEqual((K, IN, DIN), (i.K(), i.INTER(), i.DEINTER())) def test_001_viterbi(self): """ Runs some coding/decoding tests with a few different FSM specs. """ for name, args in list(fsm_args.items()): constellation = constells[args[2]] fsms = trellis.fsm(*args) noise = 0.1 tb = trellis_tb(constellation, fsms, noise) tb.run() # Make sure all packets successfully transmitted. self.assertEqual(tb.dst.ntotal(), tb.dst.nright()) class trellis_tb(gr.top_block): """ A simple top block for use testing gr-trellis. """ def __init__(self, constellation, f, N0=0.25, seed=-666): """ constellation - a constellation object used for modulation. f - a finite state machine specification used for coding. N0 - noise level seed - random seed """ super(trellis_tb, self).__init__() # packet size in bits (make it multiple of 16 so it can be packed in a # short) packet_size = 1024 * 16 # bits per FSM input symbol # bits per FSM input symbol bitspersymbol = int(round(math.log(f.I()) / math.log(2))) # packet size in trellis steps K = packet_size // bitspersymbol # TX src = blocks.lfsr_32k_source_s() # packet size in shorts src_head = blocks.head(gr.sizeof_short, packet_size // 16) # unpack shorts to symbols compatible with the FSM input cardinality s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol, gr.GR_MSB_FIRST) # initial FSM state = 0 enc = trellis.encoder_ss(f, 0) mod = digital.chunks_to_symbols_sc(constellation.points(), 1) # CHANNEL add = blocks.add_cc() noise = analog.noise_source_c( analog.GR_GAUSSIAN, math.sqrt( N0 / 2), seed) # RX # data preprocessing to generate metrics for Viterbi metrics = trellis.constellation_metrics_cf( constellation.base(), digital.TRELLIS_EUCLIDEAN) # Put -1 if the Initial/Final states are not set. va = trellis.viterbi_s(f, K, 0, -1) # pack FSM input symbols to shorts fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol, gr.GR_MSB_FIRST) # check the output self.dst = blocks.check_lfsr_32k_s() self.connect(src, src_head, s2fsmi, enc, mod) self.connect(mod, (add, 0)) self.connect(noise, (add, 1)) self.connect(add, metrics, va, fsmi2s, self.dst) if __name__ == '__main__': gr_unittest.run(test_trellis)
gpl-3.0
rockstor/rockstor-core
src/rockstor/storageadmin/models/config_backup.py
2
1317
""" Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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. RockStor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import os from django.db import models from django.conf import settings class ConfigBackup(models.Model): filename = models.CharField(max_length=64) md5sum = models.CharField(max_length=32, null=True) size = models.IntegerField(null=True) config_backup = models.FileField(upload_to="config-backups", null=True) def __unicode__(self): return "{0}".format(self.filename) def full_path(self): return os.path.join(self.cb_dir(), self.filename) class Meta: app_label = "storageadmin" @staticmethod def cb_dir(): return settings.DEFAULT_CB_DIR
gpl-3.0
TRESCLOUD/odoopub
addons/l10n_pl/__init__.py
340
1155
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2008 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # l10n_pl module improved for Poland # by Grzegorz Grzelak grzegorz.grzelak@openglobe.pl # # 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/>. # ############################################################################## # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
davy39/eric
Preferences/ConfigurationPages/EditorSpellCheckingPage.py
1
5027
# -*- coding: utf-8 -*- # Copyright (c) 2008 - 2014 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing the Editor Spellchecking configuration page. """ from __future__ import unicode_literals from PyQt5.QtCore import pyqtSlot from E5Gui.E5Completers import E5FileCompleter from E5Gui import E5FileDialog from .ConfigurationPageBase import ConfigurationPageBase from .Ui_EditorSpellCheckingPage import Ui_EditorSpellCheckingPage import Preferences import Utilities import UI.PixmapCache class EditorSpellCheckingPage(ConfigurationPageBase, Ui_EditorSpellCheckingPage): """ Class implementing the Editor Spellchecking configuration page. """ def __init__(self): """ Constructor """ super(EditorSpellCheckingPage, self).__init__() self.setupUi(self) self.setObjectName("EditorSpellCheckingPage") self.pwlButton.setIcon(UI.PixmapCache.getIcon("open.png")) self.pelButton.setIcon(UI.PixmapCache.getIcon("open.png")) from QScintilla.SpellChecker import SpellChecker languages = sorted(SpellChecker.getAvailableLanguages()) self.defaultLanguageCombo.addItems(languages) if languages: self.errorLabel.hide() else: self.spellingFrame.setEnabled(False) self.pwlFileCompleter = E5FileCompleter(self.pwlEdit, showHidden=True) self.pelFileCompleter = E5FileCompleter(self.pelEdit, showHidden=True) # set initial values self.checkingEnabledCheckBox.setChecked( Preferences.getEditor("SpellCheckingEnabled")) self.defaultLanguageCombo.setCurrentIndex( self.defaultLanguageCombo.findText( Preferences.getEditor("SpellCheckingDefaultLanguage"))) self.stringsOnlyCheckBox.setChecked( Preferences.getEditor("SpellCheckStringsOnly")) self.minimumWordSizeSlider.setValue( Preferences.getEditor("SpellCheckingMinWordSize")) self.initColour( "SpellingMarkers", self.spellingMarkerButton, Preferences.getEditorColour, hasAlpha=True) self.pwlEdit.setText( Preferences.getEditor("SpellCheckingPersonalWordList")) self.pelEdit.setText( Preferences.getEditor("SpellCheckingPersonalExcludeList")) if self.spellingFrame.isEnabled(): self.enabledCheckBox.setChecked( Preferences.getEditor("AutoSpellCheckingEnabled")) else: self.enabledCheckBox.setChecked(False) # not available self.chunkSizeSpinBox.setValue( Preferences.getEditor("AutoSpellCheckChunkSize")) def save(self): """ Public slot to save the Editor Search configuration. """ Preferences.setEditor( "SpellCheckingEnabled", self.checkingEnabledCheckBox.isChecked()) Preferences.setEditor( "SpellCheckingDefaultLanguage", self.defaultLanguageCombo.currentText()) Preferences.setEditor( "SpellCheckStringsOnly", self.stringsOnlyCheckBox.isChecked()) Preferences.setEditor( "SpellCheckingMinWordSize", self.minimumWordSizeSlider.value()) self.saveColours(Preferences.setEditorColour) Preferences.setEditor( "SpellCheckingPersonalWordList", self.pwlEdit.text()) Preferences.setEditor( "SpellCheckingPersonalExcludeList", self.pelEdit.text()) Preferences.setEditor( "AutoSpellCheckingEnabled", self.enabledCheckBox.isChecked()) Preferences.setEditor( "AutoSpellCheckChunkSize", self.chunkSizeSpinBox.value()) @pyqtSlot() def on_pwlButton_clicked(self): """ Private method to select the personal word list file. """ file = E5FileDialog.getOpenFileName( self, self.tr("Select personal word list"), self.pwlEdit.text(), self.tr("Dictionary File (*.dic);;All Files (*)")) if file: self.pwlEdit.setText(Utilities.toNativeSeparators(file)) @pyqtSlot() def on_pelButton_clicked(self): """ Private method to select the personal exclude list file. """ file = E5FileDialog.getOpenFileName( self, self.tr("Select personal exclude list"), self.pelEdit.text(), self.tr("Dictionary File (*.dic);;All Files (*)")) if file: self.pelEdit.setText(Utilities.toNativeSeparators(file)) def create(dlg): """ Module function to create the configuration page. @param dlg reference to the configuration dialog @return reference to the instantiated page (ConfigurationPageBase) """ page = EditorSpellCheckingPage() return page
gpl-3.0
minhphung171093/GreenERP
openerp/addons/website_forum_doc/controllers/main.py
54
3424
# -*- coding: utf-8 -*- from openerp import http from openerp.http import request from openerp.addons.website.models.website import slug class WebsiteDoc(http.Controller): @http.route(['/forum/how-to', '/forum/how-to/<model("forum.documentation.toc"):toc>'], type='http', auth="public", website=True) def toc(self, toc=None, **kwargs): cr, uid, context, toc_id = request.cr, request.uid, request.context, False if toc: sections = toc.child_ids forum = toc.forum_id else: toc_obj = request.registry['forum.documentation.toc'] obj_ids = toc_obj.search(cr, uid, [('parent_id', '=', False)], context=context) sections = toc_obj.browse(cr, uid, obj_ids, context=context) forum = sections and sections[0].forum_id or False value = { 'toc': toc, 'main_object': toc or forum, 'forum': forum, 'sections': sections, } return request.website.render("website_forum_doc.documentation", value) @http.route(['''/forum/how-to/<model("forum.documentation.toc"):toc>/<model("forum.post", "[('documentation_toc_id','=',toc[0])]"):post>'''], type='http', auth="public", website=True) def post(self, toc, post, **kwargs): # TODO: implement a redirect instead of crash assert post.documentation_toc_id.id == toc.id, "Wrong post!" value = { 'toc': toc, 'post': post, 'main_object': post, 'forum': post.forum_id } return request.website.render("website_forum_doc.documentation_post", value) @http.route('/forum/<model("forum.forum"):forum>/question/<model("forum.post"):post>/promote', type='http', auth="user", website=True) def post_toc(self, forum, post, **kwargs): cr, uid, context, toc_id = request.cr, request.uid, request.context, False user = request.registry['res.users'].browse(cr, uid, uid, context=context) assert user.karma >= 200, 'You need 200 karma to promote a post to the documentation' toc_obj = request.registry['forum.documentation.toc'] obj_ids = toc_obj.search(cr, uid, [], context=context) tocs = toc_obj.browse(cr, uid, obj_ids, context=context) value = { 'post': post, 'forum': post.forum_id, 'chapters': filter(lambda x: not x.child_ids, tocs) } return request.website.render("website_forum_doc.promote_question", value) @http.route('/forum/<model("forum.forum"):forum>/promote_ok', type='http', auth="user", website=True) def post_toc_ok(self, forum, post_id, toc_id, **kwargs): cr, uid, context = request.cr, request.uid, request.context user = request.registry['res.users'].browse(cr, uid, uid, context=context) assert user.karma >= 200, 'Not enough karma, you need 200 to promote a documentation.' toc_obj = request.registry['forum.documentation.toc'] stage_ids = toc_obj.search(cr, uid, [], limit=1, context=context) post_obj = request.registry['forum.post'] post_obj.write(cr, uid, [int(post_id)], { 'documentation_toc_id': toc_id and int(toc_id) or False, 'documentation_stage_id': stage_ids and stage_ids[0] or False }, context=context) return request.redirect('/forum/'+str(forum.id)+'/question/'+str(post_id))
gpl-3.0
aurelijusb/arangodb
3rdParty/V8-4.3.61/third_party/python_26/Lib/site-packages/win32comext/shell/demos/browse_for_folder.py
47
1661
# A couple of samples using SHBrowseForFolder import sys, os from win32com.shell import shell, shellcon import win32gui # A callback procedure - called by SHBrowseForFolder def BrowseCallbackProc(hwnd, msg, lp, data): if msg== shellcon.BFFM_INITIALIZED: win32gui.SendMessage(hwnd, shellcon.BFFM_SETSELECTION, 1, data) elif msg == shellcon.BFFM_SELCHANGED: # Set the status text of the # For this message, 'lp' is the address of the PIDL. pidl = shell.AddressAsPIDL(lp) try: path = shell.SHGetPathFromIDList(pidl) win32gui.SendMessage(hwnd, shellcon.BFFM_SETSTATUSTEXT, 0, path) except shell.error: # No path for this PIDL pass if __name__=='__main__': # Demonstrate a dialog with the cwd selected as the default - this # must be done via a callback function. flags = shellcon.BIF_STATUSTEXT shell.SHBrowseForFolder(0, # parent HWND None, # root PIDL. "Default of %s" % os.getcwd(), # title flags, # flags BrowseCallbackProc, # callback function os.getcwd() # 'data' param for the callback ) # Browse from this directory down only. # Get the PIDL for the cwd. desktop = shell.SHGetDesktopFolder() cb, pidl, extra = desktop.ParseDisplayName(0, None, os.getcwd()) shell.SHBrowseForFolder(0, # parent HWND pidl, # root PIDL. "From %s down only" % os.getcwd(), # title )
apache-2.0
msingh172/youtube-dl
test/test_jsinterp.py
104
3483
#!/usr/bin/env python from __future__ import unicode_literals # Allow direct execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from youtube_dl.jsinterp import JSInterpreter class TestJSInterpreter(unittest.TestCase): def test_basic(self): jsi = JSInterpreter('function x(){;}') self.assertEqual(jsi.call_function('x'), None) jsi = JSInterpreter('function x3(){return 42;}') self.assertEqual(jsi.call_function('x3'), 42) def test_calc(self): jsi = JSInterpreter('function x4(a){return 2*a+1;}') self.assertEqual(jsi.call_function('x4', 3), 7) def test_empty_return(self): jsi = JSInterpreter('function f(){return; y()}') self.assertEqual(jsi.call_function('f'), None) def test_morespace(self): jsi = JSInterpreter('function x (a) { return 2 * a + 1 ; }') self.assertEqual(jsi.call_function('x', 3), 7) jsi = JSInterpreter('function f () { x = 2 ; return x; }') self.assertEqual(jsi.call_function('f'), 2) def test_strange_chars(self): jsi = JSInterpreter('function $_xY1 ($_axY1) { var $_axY2 = $_axY1 + 1; return $_axY2; }') self.assertEqual(jsi.call_function('$_xY1', 20), 21) def test_operators(self): jsi = JSInterpreter('function f(){return 1 << 5;}') self.assertEqual(jsi.call_function('f'), 32) jsi = JSInterpreter('function f(){return 19 & 21;}') self.assertEqual(jsi.call_function('f'), 17) jsi = JSInterpreter('function f(){return 11 >> 2;}') self.assertEqual(jsi.call_function('f'), 2) def test_array_access(self): jsi = JSInterpreter('function f(){var x = [1,2,3]; x[0] = 4; x[0] = 5; x[2] = 7; return x;}') self.assertEqual(jsi.call_function('f'), [5, 2, 7]) def test_parens(self): jsi = JSInterpreter('function f(){return (1) + (2) * ((( (( (((((3)))))) )) ));}') self.assertEqual(jsi.call_function('f'), 7) jsi = JSInterpreter('function f(){return (1 + 2) * 3;}') self.assertEqual(jsi.call_function('f'), 9) def test_assignments(self): jsi = JSInterpreter('function f(){var x = 20; x = 30 + 1; return x;}') self.assertEqual(jsi.call_function('f'), 31) jsi = JSInterpreter('function f(){var x = 20; x += 30 + 1; return x;}') self.assertEqual(jsi.call_function('f'), 51) jsi = JSInterpreter('function f(){var x = 20; x -= 30 + 1; return x;}') self.assertEqual(jsi.call_function('f'), -11) def test_comments(self): 'Skipping: Not yet fully implemented' return jsi = JSInterpreter(''' function x() { var x = /* 1 + */ 2; var y = /* 30 * 40 */ 50; return x + y; } ''') self.assertEqual(jsi.call_function('x'), 52) jsi = JSInterpreter(''' function f() { var x = "/*"; var y = 1 /* comment */ + 2; return y; } ''') self.assertEqual(jsi.call_function('f'), 3) def test_precedence(self): jsi = JSInterpreter(''' function x() { var a = [10, 20, 30, 40, 50]; var b = 6; a[0]=a[b%a.length]; return a; }''') self.assertEqual(jsi.call_function('x'), [20, 20, 30, 40, 50]) if __name__ == '__main__': unittest.main()
unlicense
XiaosongWei/blink-crosswalk
Tools/Scripts/webkitpy/common/system/systemhost_mock.py
46
3089
# Copyright (c) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from StringIO import StringIO from webkitpy.common.system.environment import Environment from webkitpy.common.system.executive_mock import MockExecutive from webkitpy.common.system.filesystem_mock import MockFileSystem from webkitpy.common.system.platforminfo_mock import MockPlatformInfo from webkitpy.common.system.user_mock import MockUser from webkitpy.common.system.workspace_mock import MockWorkspace class MockSystemHost(object): def __init__(self, log_executive=False, executive_throws_when_run=None, os_name=None, os_version=None, executive=None, filesystem=None): self.executable = 'python' self.executive = executive or MockExecutive(should_log=log_executive, should_throw_when_run=executive_throws_when_run) self.filesystem = filesystem or MockFileSystem() self.user = MockUser() self.platform = MockPlatformInfo() if os_name: self.platform.os_name = os_name if os_version: self.platform.os_version = os_version # FIXME: Should this take pointers to the filesystem and the executive? self.workspace = MockWorkspace() self.stdin = StringIO() self.stdout = StringIO() self.stderr = StringIO() def copy_current_environment(self): return Environment({"MOCK_ENVIRON_COPY": '1'}) def print_(self, *args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stream = kwargs.get('stream', self.stdout) stream.write(sep.join([str(arg) for arg in args]) + end)
bsd-3-clause
ndingwall/scikit-learn
sklearn/linear_model/_ridge.py
2
77132
""" Ridge regression """ # Author: Mathieu Blondel <mathieu@mblondel.org> # Reuben Fletcher-Costin <reuben.fletchercostin@gmail.com> # Fabian Pedregosa <fabian@fseoane.net> # Michael Eickenberg <michael.eickenberg@nsup.org> # License: BSD 3 clause from abc import ABCMeta, abstractmethod import warnings import numpy as np from scipy import linalg from scipy import sparse from scipy.sparse import linalg as sp_linalg from ._base import LinearClassifierMixin, LinearModel, _rescale_data from ._sag import sag_solver from ..base import RegressorMixin, MultiOutputMixin, is_classifier from ..utils.extmath import safe_sparse_dot from ..utils.extmath import row_norms from ..utils import check_array from ..utils import check_consistent_length from ..utils import compute_sample_weight from ..utils import column_or_1d from ..utils.validation import _check_sample_weight from ..utils.validation import _deprecate_positional_args from ..preprocessing import LabelBinarizer from ..model_selection import GridSearchCV from ..metrics import check_scoring from ..exceptions import ConvergenceWarning from ..utils.sparsefuncs import mean_variance_axis def _solve_sparse_cg(X, y, alpha, max_iter=None, tol=1e-3, verbose=0, X_offset=None, X_scale=None): def _get_rescaled_operator(X): X_offset_scale = X_offset / X_scale def matvec(b): return X.dot(b) - b.dot(X_offset_scale) def rmatvec(b): return X.T.dot(b) - X_offset_scale * np.sum(b) X1 = sparse.linalg.LinearOperator(shape=X.shape, matvec=matvec, rmatvec=rmatvec) return X1 n_samples, n_features = X.shape if X_offset is None or X_scale is None: X1 = sp_linalg.aslinearoperator(X) else: X1 = _get_rescaled_operator(X) coefs = np.empty((y.shape[1], n_features), dtype=X.dtype) if n_features > n_samples: def create_mv(curr_alpha): def _mv(x): return X1.matvec(X1.rmatvec(x)) + curr_alpha * x return _mv else: def create_mv(curr_alpha): def _mv(x): return X1.rmatvec(X1.matvec(x)) + curr_alpha * x return _mv for i in range(y.shape[1]): y_column = y[:, i] mv = create_mv(alpha[i]) if n_features > n_samples: # kernel ridge # w = X.T * inv(X X^t + alpha*Id) y C = sp_linalg.LinearOperator( (n_samples, n_samples), matvec=mv, dtype=X.dtype) # FIXME atol try: coef, info = sp_linalg.cg(C, y_column, tol=tol, atol='legacy') except TypeError: # old scipy coef, info = sp_linalg.cg(C, y_column, tol=tol) coefs[i] = X1.rmatvec(coef) else: # linear ridge # w = inv(X^t X + alpha*Id) * X.T y y_column = X1.rmatvec(y_column) C = sp_linalg.LinearOperator( (n_features, n_features), matvec=mv, dtype=X.dtype) # FIXME atol try: coefs[i], info = sp_linalg.cg(C, y_column, maxiter=max_iter, tol=tol, atol='legacy') except TypeError: # old scipy coefs[i], info = sp_linalg.cg(C, y_column, maxiter=max_iter, tol=tol) if info < 0: raise ValueError("Failed with error code %d" % info) if max_iter is None and info > 0 and verbose: warnings.warn("sparse_cg did not converge after %d iterations." % info, ConvergenceWarning) return coefs def _solve_lsqr(X, y, alpha, max_iter=None, tol=1e-3): n_samples, n_features = X.shape coefs = np.empty((y.shape[1], n_features), dtype=X.dtype) n_iter = np.empty(y.shape[1], dtype=np.int32) # According to the lsqr documentation, alpha = damp^2. sqrt_alpha = np.sqrt(alpha) for i in range(y.shape[1]): y_column = y[:, i] info = sp_linalg.lsqr(X, y_column, damp=sqrt_alpha[i], atol=tol, btol=tol, iter_lim=max_iter) coefs[i] = info[0] n_iter[i] = info[2] return coefs, n_iter def _solve_cholesky(X, y, alpha): # w = inv(X^t X + alpha*Id) * X.T y n_features = X.shape[1] n_targets = y.shape[1] A = safe_sparse_dot(X.T, X, dense_output=True) Xy = safe_sparse_dot(X.T, y, dense_output=True) one_alpha = np.array_equal(alpha, len(alpha) * [alpha[0]]) if one_alpha: A.flat[::n_features + 1] += alpha[0] return linalg.solve(A, Xy, sym_pos=True, overwrite_a=True).T else: coefs = np.empty([n_targets, n_features], dtype=X.dtype) for coef, target, current_alpha in zip(coefs, Xy.T, alpha): A.flat[::n_features + 1] += current_alpha coef[:] = linalg.solve(A, target, sym_pos=True, overwrite_a=False).ravel() A.flat[::n_features + 1] -= current_alpha return coefs def _solve_cholesky_kernel(K, y, alpha, sample_weight=None, copy=False): # dual_coef = inv(X X^t + alpha*Id) y n_samples = K.shape[0] n_targets = y.shape[1] if copy: K = K.copy() alpha = np.atleast_1d(alpha) one_alpha = (alpha == alpha[0]).all() has_sw = isinstance(sample_weight, np.ndarray) \ or sample_weight not in [1.0, None] if has_sw: # Unlike other solvers, we need to support sample_weight directly # because K might be a pre-computed kernel. sw = np.sqrt(np.atleast_1d(sample_weight)) y = y * sw[:, np.newaxis] K *= np.outer(sw, sw) if one_alpha: # Only one penalty, we can solve multi-target problems in one time. K.flat[::n_samples + 1] += alpha[0] try: # Note: we must use overwrite_a=False in order to be able to # use the fall-back solution below in case a LinAlgError # is raised dual_coef = linalg.solve(K, y, sym_pos=True, overwrite_a=False) except np.linalg.LinAlgError: warnings.warn("Singular matrix in solving dual problem. Using " "least-squares solution instead.") dual_coef = linalg.lstsq(K, y)[0] # K is expensive to compute and store in memory so change it back in # case it was user-given. K.flat[::n_samples + 1] -= alpha[0] if has_sw: dual_coef *= sw[:, np.newaxis] return dual_coef else: # One penalty per target. We need to solve each target separately. dual_coefs = np.empty([n_targets, n_samples], K.dtype) for dual_coef, target, current_alpha in zip(dual_coefs, y.T, alpha): K.flat[::n_samples + 1] += current_alpha dual_coef[:] = linalg.solve(K, target, sym_pos=True, overwrite_a=False).ravel() K.flat[::n_samples + 1] -= current_alpha if has_sw: dual_coefs *= sw[np.newaxis, :] return dual_coefs.T def _solve_svd(X, y, alpha): U, s, Vt = linalg.svd(X, full_matrices=False) idx = s > 1e-15 # same default value as scipy.linalg.pinv s_nnz = s[idx][:, np.newaxis] UTy = np.dot(U.T, y) d = np.zeros((s.size, alpha.size), dtype=X.dtype) d[idx] = s_nnz / (s_nnz ** 2 + alpha) d_UT_y = d * UTy return np.dot(Vt.T, d_UT_y).T def _get_valid_accept_sparse(is_X_sparse, solver): if is_X_sparse and solver in ['auto', 'sag', 'saga']: return 'csr' else: return ['csr', 'csc', 'coo'] @_deprecate_positional_args def ridge_regression(X, y, alpha, *, sample_weight=None, solver='auto', max_iter=None, tol=1e-3, verbose=0, random_state=None, return_n_iter=False, return_intercept=False, check_input=True): """Solve the ridge equation by the method of normal equations. Read more in the :ref:`User Guide <ridge_regression>`. Parameters ---------- X : {ndarray, sparse matrix, LinearOperator} of shape \ (n_samples, n_features) Training data y : ndarray of shape (n_samples,) or (n_samples, n_targets) Target values alpha : float or array-like of shape (n_targets,) Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. If an array is passed, penalties are assumed to be specific to the targets. Hence they must correspond in number. sample_weight : float or array-like of shape (n_samples,), default=None Individual weights for each sample. If given a float, every sample will have the same weight. If sample_weight is not None and solver='auto', the solver will be set to 'cholesky'. .. versionadded:: 0.17 solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga'}, \ default='auto' Solver to use in the computational routines: - 'auto' chooses the solver automatically based on the type of data. - 'svd' uses a Singular Value Decomposition of X to compute the Ridge coefficients. More stable for singular matrices than 'cholesky'. - 'cholesky' uses the standard scipy.linalg.solve function to obtain a closed-form solution via a Cholesky decomposition of dot(X.T, X) - 'sparse_cg' uses the conjugate gradient solver as found in scipy.sparse.linalg.cg. As an iterative algorithm, this solver is more appropriate than 'cholesky' for large-scale data (possibility to set `tol` and `max_iter`). - 'lsqr' uses the dedicated regularized least-squares routine scipy.sparse.linalg.lsqr. It is the fastest and uses an iterative procedure. - 'sag' uses a Stochastic Average Gradient descent, and 'saga' uses its improved, unbiased version named SAGA. Both methods also use an iterative procedure, and are often faster than other solvers when both n_samples and n_features are large. Note that 'sag' and 'saga' fast convergence is only guaranteed on features with approximately the same scale. You can preprocess the data with a scaler from sklearn.preprocessing. All last five solvers support both dense and sparse data. However, only 'sag' and 'sparse_cg' supports sparse input when `fit_intercept` is True. .. versionadded:: 0.17 Stochastic Average Gradient descent solver. .. versionadded:: 0.19 SAGA solver. max_iter : int, default=None Maximum number of iterations for conjugate gradient solver. For the 'sparse_cg' and 'lsqr' solvers, the default value is determined by scipy.sparse.linalg. For 'sag' and saga solver, the default value is 1000. tol : float, default=1e-3 Precision of the solution. verbose : int, default=0 Verbosity level. Setting verbose > 0 will display additional information depending on the solver used. random_state : int, RandomState instance, default=None Used when ``solver`` == 'sag' or 'saga' to shuffle the data. See :term:`Glossary <random_state>` for details. return_n_iter : bool, default=False If True, the method also returns `n_iter`, the actual number of iteration performed by the solver. .. versionadded:: 0.17 return_intercept : bool, default=False If True and if X is sparse, the method also returns the intercept, and the solver is automatically changed to 'sag'. This is only a temporary fix for fitting the intercept with sparse data. For dense data, use sklearn.linear_model._preprocess_data before your regression. .. versionadded:: 0.17 check_input : bool, default=True If False, the input arrays X and y will not be checked. .. versionadded:: 0.21 Returns ------- coef : ndarray of shape (n_features,) or (n_targets, n_features) Weight vector(s). n_iter : int, optional The actual number of iteration performed by the solver. Only returned if `return_n_iter` is True. intercept : float or ndarray of shape (n_targets,) The intercept of the model. Only returned if `return_intercept` is True and if X is a scipy sparse array. Notes ----- This function won't compute the intercept. """ return _ridge_regression(X, y, alpha, sample_weight=sample_weight, solver=solver, max_iter=max_iter, tol=tol, verbose=verbose, random_state=random_state, return_n_iter=return_n_iter, return_intercept=return_intercept, X_scale=None, X_offset=None, check_input=check_input) def _ridge_regression(X, y, alpha, sample_weight=None, solver='auto', max_iter=None, tol=1e-3, verbose=0, random_state=None, return_n_iter=False, return_intercept=False, X_scale=None, X_offset=None, check_input=True): has_sw = sample_weight is not None if solver == 'auto': if return_intercept: # only sag supports fitting intercept directly solver = "sag" elif not sparse.issparse(X): solver = "cholesky" else: solver = "sparse_cg" if solver not in ('sparse_cg', 'cholesky', 'svd', 'lsqr', 'sag', 'saga'): raise ValueError("Known solvers are 'sparse_cg', 'cholesky', 'svd'" " 'lsqr', 'sag' or 'saga'. Got %s." % solver) if return_intercept and solver != 'sag': raise ValueError("In Ridge, only 'sag' solver can directly fit the " "intercept. Please change solver to 'sag' or set " "return_intercept=False.") if check_input: _dtype = [np.float64, np.float32] _accept_sparse = _get_valid_accept_sparse(sparse.issparse(X), solver) X = check_array(X, accept_sparse=_accept_sparse, dtype=_dtype, order="C") y = check_array(y, dtype=X.dtype, ensure_2d=False, order=None) check_consistent_length(X, y) n_samples, n_features = X.shape if y.ndim > 2: raise ValueError("Target y has the wrong shape %s" % str(y.shape)) ravel = False if y.ndim == 1: y = y.reshape(-1, 1) ravel = True n_samples_, n_targets = y.shape if n_samples != n_samples_: raise ValueError("Number of samples in X and y does not correspond:" " %d != %d" % (n_samples, n_samples_)) if has_sw: sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) if solver not in ['sag', 'saga']: # SAG supports sample_weight directly. For other solvers, # we implement sample_weight via a simple rescaling. X, y = _rescale_data(X, y, sample_weight) # There should be either 1 or n_targets penalties alpha = np.asarray(alpha, dtype=X.dtype).ravel() if alpha.size not in [1, n_targets]: raise ValueError("Number of targets and number of penalties " "do not correspond: %d != %d" % (alpha.size, n_targets)) if alpha.size == 1 and n_targets > 1: alpha = np.repeat(alpha, n_targets) n_iter = None if solver == 'sparse_cg': coef = _solve_sparse_cg(X, y, alpha, max_iter=max_iter, tol=tol, verbose=verbose, X_offset=X_offset, X_scale=X_scale) elif solver == 'lsqr': coef, n_iter = _solve_lsqr(X, y, alpha, max_iter, tol) elif solver == 'cholesky': if n_features > n_samples: K = safe_sparse_dot(X, X.T, dense_output=True) try: dual_coef = _solve_cholesky_kernel(K, y, alpha) coef = safe_sparse_dot(X.T, dual_coef, dense_output=True).T except linalg.LinAlgError: # use SVD solver if matrix is singular solver = 'svd' else: try: coef = _solve_cholesky(X, y, alpha) except linalg.LinAlgError: # use SVD solver if matrix is singular solver = 'svd' elif solver in ['sag', 'saga']: # precompute max_squared_sum for all targets max_squared_sum = row_norms(X, squared=True).max() coef = np.empty((y.shape[1], n_features), dtype=X.dtype) n_iter = np.empty(y.shape[1], dtype=np.int32) intercept = np.zeros((y.shape[1], ), dtype=X.dtype) for i, (alpha_i, target) in enumerate(zip(alpha, y.T)): init = {'coef': np.zeros((n_features + int(return_intercept), 1), dtype=X.dtype)} coef_, n_iter_, _ = sag_solver( X, target.ravel(), sample_weight, 'squared', alpha_i, 0, max_iter, tol, verbose, random_state, False, max_squared_sum, init, is_saga=solver == 'saga') if return_intercept: coef[i] = coef_[:-1] intercept[i] = coef_[-1] else: coef[i] = coef_ n_iter[i] = n_iter_ if intercept.shape[0] == 1: intercept = intercept[0] coef = np.asarray(coef) if solver == 'svd': if sparse.issparse(X): raise TypeError('SVD solver does not support sparse' ' inputs currently') coef = _solve_svd(X, y, alpha) if ravel: # When y was passed as a 1d-array, we flatten the coefficients. coef = coef.ravel() if return_n_iter and return_intercept: return coef, n_iter, intercept elif return_intercept: return coef, intercept elif return_n_iter: return coef, n_iter else: return coef class _BaseRidge(LinearModel, metaclass=ABCMeta): @abstractmethod @_deprecate_positional_args def __init__(self, alpha=1.0, *, fit_intercept=True, normalize=False, copy_X=True, max_iter=None, tol=1e-3, solver="auto", random_state=None): self.alpha = alpha self.fit_intercept = fit_intercept self.normalize = normalize self.copy_X = copy_X self.max_iter = max_iter self.tol = tol self.solver = solver self.random_state = random_state def fit(self, X, y, sample_weight=None): # all other solvers work at both float precision levels _dtype = [np.float64, np.float32] _accept_sparse = _get_valid_accept_sparse(sparse.issparse(X), self.solver) X, y = self._validate_data(X, y, accept_sparse=_accept_sparse, dtype=_dtype, multi_output=True, y_numeric=True) if sparse.issparse(X) and self.fit_intercept: if self.solver not in ['auto', 'sparse_cg', 'sag']: raise ValueError( "solver='{}' does not support fitting the intercept " "on sparse data. Please set the solver to 'auto' or " "'sparse_cg', 'sag', or set `fit_intercept=False`" .format(self.solver)) if (self.solver == 'sag' and self.max_iter is None and self.tol > 1e-4): warnings.warn( '"sag" solver requires many iterations to fit ' 'an intercept with sparse inputs. Either set the ' 'solver to "auto" or "sparse_cg", or set a low ' '"tol" and a high "max_iter" (especially if inputs are ' 'not standardized).') solver = 'sag' else: solver = 'sparse_cg' else: solver = self.solver if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) # when X is sparse we only remove offset from y X, y, X_offset, y_offset, X_scale = self._preprocess_data( X, y, self.fit_intercept, self.normalize, self.copy_X, sample_weight=sample_weight, return_mean=True) if solver == 'sag' and sparse.issparse(X) and self.fit_intercept: self.coef_, self.n_iter_, self.intercept_ = _ridge_regression( X, y, alpha=self.alpha, sample_weight=sample_weight, max_iter=self.max_iter, tol=self.tol, solver='sag', random_state=self.random_state, return_n_iter=True, return_intercept=True, check_input=False) # add the offset which was subtracted by _preprocess_data self.intercept_ += y_offset else: if sparse.issparse(X) and self.fit_intercept: # required to fit intercept with sparse_cg solver params = {'X_offset': X_offset, 'X_scale': X_scale} else: # for dense matrices or when intercept is set to 0 params = {} self.coef_, self.n_iter_ = _ridge_regression( X, y, alpha=self.alpha, sample_weight=sample_weight, max_iter=self.max_iter, tol=self.tol, solver=solver, random_state=self.random_state, return_n_iter=True, return_intercept=False, check_input=False, **params) self._set_intercept(X_offset, y_offset, X_scale) return self class Ridge(MultiOutputMixin, RegressorMixin, _BaseRidge): """Linear least squares with l2 regularization. Minimizes the objective function:: ||y - Xw||^2_2 + alpha * ||w||^2_2 This model solves a regression model where the loss function is the linear least squares function and regularization is given by the l2-norm. Also known as Ridge Regression or Tikhonov regularization. This estimator has built-in support for multi-variate regression (i.e., when y is a 2d-array of shape (n_samples, n_targets)). Read more in the :ref:`User Guide <ridge_regression>`. Parameters ---------- alpha : {float, ndarray of shape (n_targets,)}, default=1.0 Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. If an array is passed, penalties are assumed to be specific to the targets. Hence they must correspond in number. fit_intercept : bool, default=True Whether to fit the intercept for this model. If set to false, no intercept will be used in calculations (i.e. ``X`` and ``y`` are expected to be centered). normalize : bool, default=False This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use :class:`~sklearn.preprocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. copy_X : bool, default=True If True, X will be copied; else, it may be overwritten. max_iter : int, default=None Maximum number of iterations for conjugate gradient solver. For 'sparse_cg' and 'lsqr' solvers, the default value is determined by scipy.sparse.linalg. For 'sag' solver, the default value is 1000. tol : float, default=1e-3 Precision of the solution. solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga'}, \ default='auto' Solver to use in the computational routines: - 'auto' chooses the solver automatically based on the type of data. - 'svd' uses a Singular Value Decomposition of X to compute the Ridge coefficients. More stable for singular matrices than 'cholesky'. - 'cholesky' uses the standard scipy.linalg.solve function to obtain a closed-form solution. - 'sparse_cg' uses the conjugate gradient solver as found in scipy.sparse.linalg.cg. As an iterative algorithm, this solver is more appropriate than 'cholesky' for large-scale data (possibility to set `tol` and `max_iter`). - 'lsqr' uses the dedicated regularized least-squares routine scipy.sparse.linalg.lsqr. It is the fastest and uses an iterative procedure. - 'sag' uses a Stochastic Average Gradient descent, and 'saga' uses its improved, unbiased version named SAGA. Both methods also use an iterative procedure, and are often faster than other solvers when both n_samples and n_features are large. Note that 'sag' and 'saga' fast convergence is only guaranteed on features with approximately the same scale. You can preprocess the data with a scaler from sklearn.preprocessing. All last five solvers support both dense and sparse data. However, only 'sag' and 'sparse_cg' supports sparse input when `fit_intercept` is True. .. versionadded:: 0.17 Stochastic Average Gradient descent solver. .. versionadded:: 0.19 SAGA solver. random_state : int, RandomState instance, default=None Used when ``solver`` == 'sag' or 'saga' to shuffle the data. See :term:`Glossary <random_state>` for details. .. versionadded:: 0.17 `random_state` to support Stochastic Average Gradient. Attributes ---------- coef_ : ndarray of shape (n_features,) or (n_targets, n_features) Weight vector(s). intercept_ : float or ndarray of shape (n_targets,) Independent term in decision function. Set to 0.0 if ``fit_intercept = False``. n_iter_ : None or ndarray of shape (n_targets,) Actual number of iterations for each target. Available only for sag and lsqr solvers. Other solvers will return None. .. versionadded:: 0.17 See Also -------- RidgeClassifier : Ridge classifier. RidgeCV : Ridge regression with built-in cross validation. :class:`~sklearn.kernel_ridge.KernelRidge` : Kernel ridge regression combines ridge regression with the kernel trick. Examples -------- >>> from sklearn.linear_model import Ridge >>> import numpy as np >>> n_samples, n_features = 10, 5 >>> rng = np.random.RandomState(0) >>> y = rng.randn(n_samples) >>> X = rng.randn(n_samples, n_features) >>> clf = Ridge(alpha=1.0) >>> clf.fit(X, y) Ridge() """ @_deprecate_positional_args def __init__(self, alpha=1.0, *, fit_intercept=True, normalize=False, copy_X=True, max_iter=None, tol=1e-3, solver="auto", random_state=None): super().__init__( alpha=alpha, fit_intercept=fit_intercept, normalize=normalize, copy_X=copy_X, max_iter=max_iter, tol=tol, solver=solver, random_state=random_state) def fit(self, X, y, sample_weight=None): """Fit Ridge regression model. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples, n_features) Training data y : ndarray of shape (n_samples,) or (n_samples, n_targets) Target values sample_weight : float or ndarray of shape (n_samples,), default=None Individual weights for each sample. If given a float, every sample will have the same weight. Returns ------- self : returns an instance of self. """ return super().fit(X, y, sample_weight=sample_weight) class RidgeClassifier(LinearClassifierMixin, _BaseRidge): """Classifier using Ridge regression. This classifier first converts the target values into ``{-1, 1}`` and then treats the problem as a regression task (multi-output regression in the multiclass case). Read more in the :ref:`User Guide <ridge_regression>`. Parameters ---------- alpha : float, default=1.0 Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. fit_intercept : bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). normalize : bool, default=False This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use :class:`~sklearn.preprocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. copy_X : bool, default=True If True, X will be copied; else, it may be overwritten. max_iter : int, default=None Maximum number of iterations for conjugate gradient solver. The default value is determined by scipy.sparse.linalg. tol : float, default=1e-3 Precision of the solution. class_weight : dict or 'balanced', default=None Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))``. solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga'}, \ default='auto' Solver to use in the computational routines: - 'auto' chooses the solver automatically based on the type of data. - 'svd' uses a Singular Value Decomposition of X to compute the Ridge coefficients. More stable for singular matrices than 'cholesky'. - 'cholesky' uses the standard scipy.linalg.solve function to obtain a closed-form solution. - 'sparse_cg' uses the conjugate gradient solver as found in scipy.sparse.linalg.cg. As an iterative algorithm, this solver is more appropriate than 'cholesky' for large-scale data (possibility to set `tol` and `max_iter`). - 'lsqr' uses the dedicated regularized least-squares routine scipy.sparse.linalg.lsqr. It is the fastest and uses an iterative procedure. - 'sag' uses a Stochastic Average Gradient descent, and 'saga' uses its unbiased and more flexible version named SAGA. Both methods use an iterative procedure, and are often faster than other solvers when both n_samples and n_features are large. Note that 'sag' and 'saga' fast convergence is only guaranteed on features with approximately the same scale. You can preprocess the data with a scaler from sklearn.preprocessing. .. versionadded:: 0.17 Stochastic Average Gradient descent solver. .. versionadded:: 0.19 SAGA solver. random_state : int, RandomState instance, default=None Used when ``solver`` == 'sag' or 'saga' to shuffle the data. See :term:`Glossary <random_state>` for details. Attributes ---------- coef_ : ndarray of shape (1, n_features) or (n_classes, n_features) Coefficient of the features in the decision function. ``coef_`` is of shape (1, n_features) when the given problem is binary. intercept_ : float or ndarray of shape (n_targets,) Independent term in decision function. Set to 0.0 if ``fit_intercept = False``. n_iter_ : None or ndarray of shape (n_targets,) Actual number of iterations for each target. Available only for sag and lsqr solvers. Other solvers will return None. classes_ : ndarray of shape (n_classes,) The classes labels. See Also -------- Ridge : Ridge regression. RidgeClassifierCV : Ridge classifier with built-in cross validation. Notes ----- For multi-class classification, n_class classifiers are trained in a one-versus-all approach. Concretely, this is implemented by taking advantage of the multi-variate response support in Ridge. Examples -------- >>> from sklearn.datasets import load_breast_cancer >>> from sklearn.linear_model import RidgeClassifier >>> X, y = load_breast_cancer(return_X_y=True) >>> clf = RidgeClassifier().fit(X, y) >>> clf.score(X, y) 0.9595... """ @_deprecate_positional_args def __init__(self, alpha=1.0, *, fit_intercept=True, normalize=False, copy_X=True, max_iter=None, tol=1e-3, class_weight=None, solver="auto", random_state=None): super().__init__( alpha=alpha, fit_intercept=fit_intercept, normalize=normalize, copy_X=copy_X, max_iter=max_iter, tol=tol, solver=solver, random_state=random_state) self.class_weight = class_weight def fit(self, X, y, sample_weight=None): """Fit Ridge classifier model. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples, n_features) Training data. y : ndarray of shape (n_samples,) Target values. sample_weight : float or ndarray of shape (n_samples,), default=None Individual weights for each sample. If given a float, every sample will have the same weight. .. versionadded:: 0.17 *sample_weight* support to Classifier. Returns ------- self : object Instance of the estimator. """ _accept_sparse = _get_valid_accept_sparse(sparse.issparse(X), self.solver) X, y = self._validate_data(X, y, accept_sparse=_accept_sparse, multi_output=True, y_numeric=False) sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) self._label_binarizer = LabelBinarizer(pos_label=1, neg_label=-1) Y = self._label_binarizer.fit_transform(y) if not self._label_binarizer.y_type_.startswith('multilabel'): y = column_or_1d(y, warn=True) else: # we don't (yet) support multi-label classification in Ridge raise ValueError( "%s doesn't support multi-label classification" % ( self.__class__.__name__)) if self.class_weight: # modify the sample weights with the corresponding class weight sample_weight = (sample_weight * compute_sample_weight(self.class_weight, y)) super().fit(X, Y, sample_weight=sample_weight) return self @property def classes_(self): return self._label_binarizer.classes_ def _check_gcv_mode(X, gcv_mode): possible_gcv_modes = [None, 'auto', 'svd', 'eigen'] if gcv_mode not in possible_gcv_modes: raise ValueError( "Unknown value for 'gcv_mode'. " "Got {} instead of one of {}" .format( gcv_mode, possible_gcv_modes)) if gcv_mode in ['eigen', 'svd']: return gcv_mode # if X has more rows than columns, use decomposition of X^T.X, # otherwise X.X^T if X.shape[0] > X.shape[1]: return 'svd' return 'eigen' def _find_smallest_angle(query, vectors): """Find the column of vectors that is most aligned with the query. Both query and the columns of vectors must have their l2 norm equal to 1. Parameters ---------- query : ndarray of shape (n_samples,) Normalized query vector. vectors : ndarray of shape (n_samples, n_features) Vectors to which we compare query, as columns. Must be normalized. """ abs_cosine = np.abs(query.dot(vectors)) index = np.argmax(abs_cosine) return index class _X_CenterStackOp(sparse.linalg.LinearOperator): """Behaves as centered and scaled X with an added intercept column. This operator behaves as np.hstack([X - sqrt_sw[:, None] * X_mean, sqrt_sw[:, None]]) """ def __init__(self, X, X_mean, sqrt_sw): n_samples, n_features = X.shape super().__init__(X.dtype, (n_samples, n_features + 1)) self.X = X self.X_mean = X_mean self.sqrt_sw = sqrt_sw def _matvec(self, v): v = v.ravel() return safe_sparse_dot( self.X, v[:-1], dense_output=True ) - self.sqrt_sw * self.X_mean.dot(v[:-1]) + v[-1] * self.sqrt_sw def _matmat(self, v): return ( safe_sparse_dot(self.X, v[:-1], dense_output=True) - self.sqrt_sw[:, None] * self.X_mean.dot(v[:-1]) + v[-1] * self.sqrt_sw[:, None]) def _transpose(self): return _XT_CenterStackOp(self.X, self.X_mean, self.sqrt_sw) class _XT_CenterStackOp(sparse.linalg.LinearOperator): """Behaves as transposed centered and scaled X with an intercept column. This operator behaves as np.hstack([X - sqrt_sw[:, None] * X_mean, sqrt_sw[:, None]]).T """ def __init__(self, X, X_mean, sqrt_sw): n_samples, n_features = X.shape super().__init__(X.dtype, (n_features + 1, n_samples)) self.X = X self.X_mean = X_mean self.sqrt_sw = sqrt_sw def _matvec(self, v): v = v.ravel() n_features = self.shape[0] res = np.empty(n_features, dtype=self.X.dtype) res[:-1] = ( safe_sparse_dot(self.X.T, v, dense_output=True) - (self.X_mean * self.sqrt_sw.dot(v)) ) res[-1] = np.dot(v, self.sqrt_sw) return res def _matmat(self, v): n_features = self.shape[0] res = np.empty((n_features, v.shape[1]), dtype=self.X.dtype) res[:-1] = ( safe_sparse_dot(self.X.T, v, dense_output=True) - self.X_mean[:, None] * self.sqrt_sw.dot(v) ) res[-1] = np.dot(self.sqrt_sw, v) return res class _IdentityRegressor: """Fake regressor which will directly output the prediction.""" def decision_function(self, y_predict): return y_predict def predict(self, y_predict): return y_predict class _IdentityClassifier(LinearClassifierMixin): """Fake classifier which will directly output the prediction. We inherit from LinearClassifierMixin to get the proper shape for the output `y`. """ def __init__(self, classes): self.classes_ = classes def decision_function(self, y_predict): return y_predict class _RidgeGCV(LinearModel): """Ridge regression with built-in Leave-one-out Cross-Validation. This class is not intended to be used directly. Use RidgeCV instead. Notes ----- We want to solve (K + alpha*Id)c = y, where K = X X^T is the kernel matrix. Let G = (K + alpha*Id). Dual solution: c = G^-1y Primal solution: w = X^T c Compute eigendecomposition K = Q V Q^T. Then G^-1 = Q (V + alpha*Id)^-1 Q^T, where (V + alpha*Id) is diagonal. It is thus inexpensive to inverse for many alphas. Let loov be the vector of prediction values for each example when the model was fitted with all examples but this example. loov = (KG^-1Y - diag(KG^-1)Y) / diag(I-KG^-1) Let looe be the vector of prediction errors for each example when the model was fitted with all examples but this example. looe = y - loov = c / diag(G^-1) The best score (negative mean squared error or user-provided scoring) is stored in the `best_score_` attribute, and the selected hyperparameter in `alpha_`. References ---------- http://cbcl.mit.edu/publications/ps/MIT-CSAIL-TR-2007-025.pdf https://www.mit.edu/~9.520/spring07/Classes/rlsslides.pdf """ @_deprecate_positional_args def __init__(self, alphas=(0.1, 1.0, 10.0), *, fit_intercept=True, normalize=False, scoring=None, copy_X=True, gcv_mode=None, store_cv_values=False, is_clf=False, alpha_per_target=False): self.alphas = np.asarray(alphas) self.fit_intercept = fit_intercept self.normalize = normalize self.scoring = scoring self.copy_X = copy_X self.gcv_mode = gcv_mode self.store_cv_values = store_cv_values self.is_clf = is_clf self.alpha_per_target = alpha_per_target @staticmethod def _decomp_diag(v_prime, Q): # compute diagonal of the matrix: dot(Q, dot(diag(v_prime), Q^T)) return (v_prime * Q ** 2).sum(axis=-1) @staticmethod def _diag_dot(D, B): # compute dot(diag(D), B) if len(B.shape) > 1: # handle case where B is > 1-d D = D[(slice(None), ) + (np.newaxis, ) * (len(B.shape) - 1)] return D * B def _compute_gram(self, X, sqrt_sw): """Computes the Gram matrix XX^T with possible centering. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples, n_features) The preprocessed design matrix. sqrt_sw : ndarray of shape (n_samples,) square roots of sample weights Returns ------- gram : ndarray of shape (n_samples, n_samples) The Gram matrix. X_mean : ndarray of shape (n_feature,) The weighted mean of ``X`` for each feature. Notes ----- When X is dense the centering has been done in preprocessing so the mean is 0 and we just compute XX^T. When X is sparse it has not been centered in preprocessing, but it has been scaled by sqrt(sample weights). When self.fit_intercept is False no centering is done. The centered X is never actually computed because centering would break the sparsity of X. """ center = self.fit_intercept and sparse.issparse(X) if not center: # in this case centering has been done in preprocessing # or we are not fitting an intercept. X_mean = np.zeros(X.shape[1], dtype=X.dtype) return safe_sparse_dot(X, X.T, dense_output=True), X_mean # X is sparse n_samples = X.shape[0] sample_weight_matrix = sparse.dia_matrix( (sqrt_sw, 0), shape=(n_samples, n_samples)) X_weighted = sample_weight_matrix.dot(X) X_mean, _ = mean_variance_axis(X_weighted, axis=0) X_mean *= n_samples / sqrt_sw.dot(sqrt_sw) X_mX = sqrt_sw[:, None] * safe_sparse_dot( X_mean, X.T, dense_output=True) X_mX_m = np.outer(sqrt_sw, sqrt_sw) * np.dot(X_mean, X_mean) return (safe_sparse_dot(X, X.T, dense_output=True) + X_mX_m - X_mX - X_mX.T, X_mean) def _compute_covariance(self, X, sqrt_sw): """Computes covariance matrix X^TX with possible centering. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) The preprocessed design matrix. sqrt_sw : ndarray of shape (n_samples,) square roots of sample weights Returns ------- covariance : ndarray of shape (n_features, n_features) The covariance matrix. X_mean : ndarray of shape (n_feature,) The weighted mean of ``X`` for each feature. Notes ----- Since X is sparse it has not been centered in preprocessing, but it has been scaled by sqrt(sample weights). When self.fit_intercept is False no centering is done. The centered X is never actually computed because centering would break the sparsity of X. """ if not self.fit_intercept: # in this case centering has been done in preprocessing # or we are not fitting an intercept. X_mean = np.zeros(X.shape[1], dtype=X.dtype) return safe_sparse_dot(X.T, X, dense_output=True), X_mean # this function only gets called for sparse X n_samples = X.shape[0] sample_weight_matrix = sparse.dia_matrix( (sqrt_sw, 0), shape=(n_samples, n_samples)) X_weighted = sample_weight_matrix.dot(X) X_mean, _ = mean_variance_axis(X_weighted, axis=0) X_mean = X_mean * n_samples / sqrt_sw.dot(sqrt_sw) weight_sum = sqrt_sw.dot(sqrt_sw) return (safe_sparse_dot(X.T, X, dense_output=True) - weight_sum * np.outer(X_mean, X_mean), X_mean) def _sparse_multidot_diag(self, X, A, X_mean, sqrt_sw): """Compute the diagonal of (X - X_mean).dot(A).dot((X - X_mean).T) without explicitely centering X nor computing X.dot(A) when X is sparse. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) A : ndarray of shape (n_features, n_features) X_mean : ndarray of shape (n_features,) sqrt_sw : ndarray of shape (n_features,) square roots of sample weights Returns ------- diag : np.ndarray, shape (n_samples,) The computed diagonal. """ intercept_col = scale = sqrt_sw batch_size = X.shape[1] diag = np.empty(X.shape[0], dtype=X.dtype) for start in range(0, X.shape[0], batch_size): batch = slice(start, min(X.shape[0], start + batch_size), 1) X_batch = np.empty( (X[batch].shape[0], X.shape[1] + self.fit_intercept), dtype=X.dtype ) if self.fit_intercept: X_batch[:, :-1] = X[batch].A - X_mean * scale[batch][:, None] X_batch[:, -1] = intercept_col[batch] else: X_batch = X[batch].A diag[batch] = (X_batch.dot(A) * X_batch).sum(axis=1) return diag def _eigen_decompose_gram(self, X, y, sqrt_sw): """Eigendecomposition of X.X^T, used when n_samples <= n_features.""" # if X is dense it has already been centered in preprocessing K, X_mean = self._compute_gram(X, sqrt_sw) if self.fit_intercept: # to emulate centering X with sample weights, # ie removing the weighted average, we add a column # containing the square roots of the sample weights. # by centering, it is orthogonal to the other columns K += np.outer(sqrt_sw, sqrt_sw) eigvals, Q = linalg.eigh(K) QT_y = np.dot(Q.T, y) return X_mean, eigvals, Q, QT_y def _solve_eigen_gram(self, alpha, y, sqrt_sw, X_mean, eigvals, Q, QT_y): """Compute dual coefficients and diagonal of G^-1. Used when we have a decomposition of X.X^T (n_samples <= n_features). """ w = 1. / (eigvals + alpha) if self.fit_intercept: # the vector containing the square roots of the sample weights (1 # when no sample weights) is the eigenvector of XX^T which # corresponds to the intercept; we cancel the regularization on # this dimension. the corresponding eigenvalue is # sum(sample_weight). normalized_sw = sqrt_sw / np.linalg.norm(sqrt_sw) intercept_dim = _find_smallest_angle(normalized_sw, Q) w[intercept_dim] = 0 # cancel regularization for the intercept c = np.dot(Q, self._diag_dot(w, QT_y)) G_inverse_diag = self._decomp_diag(w, Q) # handle case where y is 2-d if len(y.shape) != 1: G_inverse_diag = G_inverse_diag[:, np.newaxis] return G_inverse_diag, c def _eigen_decompose_covariance(self, X, y, sqrt_sw): """Eigendecomposition of X^T.X, used when n_samples > n_features and X is sparse. """ n_samples, n_features = X.shape cov = np.empty((n_features + 1, n_features + 1), dtype=X.dtype) cov[:-1, :-1], X_mean = self._compute_covariance(X, sqrt_sw) if not self.fit_intercept: cov = cov[:-1, :-1] # to emulate centering X with sample weights, # ie removing the weighted average, we add a column # containing the square roots of the sample weights. # by centering, it is orthogonal to the other columns # when all samples have the same weight we add a column of 1 else: cov[-1] = 0 cov[:, -1] = 0 cov[-1, -1] = sqrt_sw.dot(sqrt_sw) nullspace_dim = max(0, n_features - n_samples) eigvals, V = linalg.eigh(cov) # remove eigenvalues and vectors in the null space of X^T.X eigvals = eigvals[nullspace_dim:] V = V[:, nullspace_dim:] return X_mean, eigvals, V, X def _solve_eigen_covariance_no_intercept( self, alpha, y, sqrt_sw, X_mean, eigvals, V, X): """Compute dual coefficients and diagonal of G^-1. Used when we have a decomposition of X^T.X (n_samples > n_features and X is sparse), and not fitting an intercept. """ w = 1 / (eigvals + alpha) A = (V * w).dot(V.T) AXy = A.dot(safe_sparse_dot(X.T, y, dense_output=True)) y_hat = safe_sparse_dot(X, AXy, dense_output=True) hat_diag = self._sparse_multidot_diag(X, A, X_mean, sqrt_sw) if len(y.shape) != 1: # handle case where y is 2-d hat_diag = hat_diag[:, np.newaxis] return (1 - hat_diag) / alpha, (y - y_hat) / alpha def _solve_eigen_covariance_intercept( self, alpha, y, sqrt_sw, X_mean, eigvals, V, X): """Compute dual coefficients and diagonal of G^-1. Used when we have a decomposition of X^T.X (n_samples > n_features and X is sparse), and we are fitting an intercept. """ # the vector [0, 0, ..., 0, 1] # is the eigenvector of X^TX which # corresponds to the intercept; we cancel the regularization on # this dimension. the corresponding eigenvalue is # sum(sample_weight), e.g. n when uniform sample weights. intercept_sv = np.zeros(V.shape[0]) intercept_sv[-1] = 1 intercept_dim = _find_smallest_angle(intercept_sv, V) w = 1 / (eigvals + alpha) w[intercept_dim] = 1 / eigvals[intercept_dim] A = (V * w).dot(V.T) # add a column to X containing the square roots of sample weights X_op = _X_CenterStackOp(X, X_mean, sqrt_sw) AXy = A.dot(X_op.T.dot(y)) y_hat = X_op.dot(AXy) hat_diag = self._sparse_multidot_diag(X, A, X_mean, sqrt_sw) # return (1 - hat_diag), (y - y_hat) if len(y.shape) != 1: # handle case where y is 2-d hat_diag = hat_diag[:, np.newaxis] return (1 - hat_diag) / alpha, (y - y_hat) / alpha def _solve_eigen_covariance( self, alpha, y, sqrt_sw, X_mean, eigvals, V, X): """Compute dual coefficients and diagonal of G^-1. Used when we have a decomposition of X^T.X (n_samples > n_features and X is sparse). """ if self.fit_intercept: return self._solve_eigen_covariance_intercept( alpha, y, sqrt_sw, X_mean, eigvals, V, X) return self._solve_eigen_covariance_no_intercept( alpha, y, sqrt_sw, X_mean, eigvals, V, X) def _svd_decompose_design_matrix(self, X, y, sqrt_sw): # X already centered X_mean = np.zeros(X.shape[1], dtype=X.dtype) if self.fit_intercept: # to emulate fit_intercept=True situation, add a column # containing the square roots of the sample weights # by centering, the other columns are orthogonal to that one intercept_column = sqrt_sw[:, None] X = np.hstack((X, intercept_column)) U, singvals, _ = linalg.svd(X, full_matrices=0) singvals_sq = singvals ** 2 UT_y = np.dot(U.T, y) return X_mean, singvals_sq, U, UT_y def _solve_svd_design_matrix( self, alpha, y, sqrt_sw, X_mean, singvals_sq, U, UT_y): """Compute dual coefficients and diagonal of G^-1. Used when we have an SVD decomposition of X (n_samples > n_features and X is dense). """ w = ((singvals_sq + alpha) ** -1) - (alpha ** -1) if self.fit_intercept: # detect intercept column normalized_sw = sqrt_sw / np.linalg.norm(sqrt_sw) intercept_dim = _find_smallest_angle(normalized_sw, U) # cancel the regularization for the intercept w[intercept_dim] = - (alpha ** -1) c = np.dot(U, self._diag_dot(w, UT_y)) + (alpha ** -1) * y G_inverse_diag = self._decomp_diag(w, U) + (alpha ** -1) if len(y.shape) != 1: # handle case where y is 2-d G_inverse_diag = G_inverse_diag[:, np.newaxis] return G_inverse_diag, c def fit(self, X, y, sample_weight=None): """Fit Ridge regression model with gcv. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples, n_features) Training data. Will be cast to float64 if necessary. y : ndarray of shape (n_samples,) or (n_samples, n_targets) Target values. Will be cast to float64 if necessary. sample_weight : float or ndarray of shape (n_samples,), default=None Individual weights for each sample. If given a float, every sample will have the same weight. Returns ------- self : object """ X, y = self._validate_data(X, y, accept_sparse=['csr', 'csc', 'coo'], dtype=[np.float64], multi_output=True, y_numeric=True) # alpha_per_target cannot be used in classifier mode. All subclasses # of _RidgeGCV that are classifiers keep alpha_per_target at its # default value: False, so the condition below should never happen. assert not (self.is_clf and self.alpha_per_target) if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) if np.any(self.alphas <= 0): raise ValueError( "alphas must be positive. Got {} containing some " "negative or null value instead.".format(self.alphas)) X, y, X_offset, y_offset, X_scale = LinearModel._preprocess_data( X, y, self.fit_intercept, self.normalize, self.copy_X, sample_weight=sample_weight) gcv_mode = _check_gcv_mode(X, self.gcv_mode) if gcv_mode == 'eigen': decompose = self._eigen_decompose_gram solve = self._solve_eigen_gram elif gcv_mode == 'svd': if sparse.issparse(X): decompose = self._eigen_decompose_covariance solve = self._solve_eigen_covariance else: decompose = self._svd_decompose_design_matrix solve = self._solve_svd_design_matrix n_samples = X.shape[0] if sample_weight is not None: X, y = _rescale_data(X, y, sample_weight) sqrt_sw = np.sqrt(sample_weight) else: sqrt_sw = np.ones(n_samples, dtype=X.dtype) X_mean, *decomposition = decompose(X, y, sqrt_sw) scorer = check_scoring(self, scoring=self.scoring, allow_none=True) error = scorer is None n_y = 1 if len(y.shape) == 1 else y.shape[1] n_alphas = 1 if np.ndim(self.alphas) == 0 else len(self.alphas) if self.store_cv_values: self.cv_values_ = np.empty( (n_samples * n_y, n_alphas), dtype=X.dtype) best_coef, best_score, best_alpha = None, None, None for i, alpha in enumerate(np.atleast_1d(self.alphas)): G_inverse_diag, c = solve( float(alpha), y, sqrt_sw, X_mean, *decomposition) if error: squared_errors = (c / G_inverse_diag) ** 2 if self.alpha_per_target: alpha_score = -squared_errors.mean(axis=0) else: alpha_score = -squared_errors.mean() if self.store_cv_values: self.cv_values_[:, i] = squared_errors.ravel() else: predictions = y - (c / G_inverse_diag) if self.store_cv_values: self.cv_values_[:, i] = predictions.ravel() if self.is_clf: identity_estimator = _IdentityClassifier( classes=np.arange(n_y) ) alpha_score = scorer(identity_estimator, predictions, y.argmax(axis=1)) else: identity_estimator = _IdentityRegressor() if self.alpha_per_target: alpha_score = np.array([ scorer(identity_estimator, predictions[:, j], y[:, j]) for j in range(n_y) ]) else: alpha_score = scorer(identity_estimator, predictions.ravel(), y.ravel()) # Keep track of the best model if best_score is None: # initialize if self.alpha_per_target and n_y > 1: best_coef = c best_score = np.atleast_1d(alpha_score) best_alpha = np.full(n_y, alpha) else: best_coef = c best_score = alpha_score best_alpha = alpha else: # update if self.alpha_per_target and n_y > 1: to_update = alpha_score > best_score best_coef[:, to_update] = c[:, to_update] best_score[to_update] = alpha_score[to_update] best_alpha[to_update] = alpha elif alpha_score > best_score: best_coef, best_score, best_alpha = c, alpha_score, alpha self.alpha_ = best_alpha self.best_score_ = best_score self.dual_coef_ = best_coef self.coef_ = safe_sparse_dot(self.dual_coef_.T, X) X_offset += X_mean * X_scale self._set_intercept(X_offset, y_offset, X_scale) if self.store_cv_values: if len(y.shape) == 1: cv_values_shape = n_samples, n_alphas else: cv_values_shape = n_samples, n_y, n_alphas self.cv_values_ = self.cv_values_.reshape(cv_values_shape) return self class _BaseRidgeCV(LinearModel): @_deprecate_positional_args def __init__(self, alphas=(0.1, 1.0, 10.0), *, fit_intercept=True, normalize=False, scoring=None, cv=None, gcv_mode=None, store_cv_values=False, alpha_per_target=False): self.alphas = np.asarray(alphas) self.fit_intercept = fit_intercept self.normalize = normalize self.scoring = scoring self.cv = cv self.gcv_mode = gcv_mode self.store_cv_values = store_cv_values self.alpha_per_target = alpha_per_target def fit(self, X, y, sample_weight=None): """Fit Ridge regression model with cv. Parameters ---------- X : ndarray of shape (n_samples, n_features) Training data. If using GCV, will be cast to float64 if necessary. y : ndarray of shape (n_samples,) or (n_samples, n_targets) Target values. Will be cast to X's dtype if necessary. sample_weight : float or ndarray of shape (n_samples,), default=None Individual weights for each sample. If given a float, every sample will have the same weight. Returns ------- self : object Notes ----- When sample_weight is provided, the selected hyperparameter may depend on whether we use leave-one-out cross-validation (cv=None or cv='auto') or another form of cross-validation, because only leave-one-out cross-validation takes the sample weights into account when computing the validation score. """ cv = self.cv if cv is None: estimator = _RidgeGCV(self.alphas, fit_intercept=self.fit_intercept, normalize=self.normalize, scoring=self.scoring, gcv_mode=self.gcv_mode, store_cv_values=self.store_cv_values, is_clf=is_classifier(self), alpha_per_target=self.alpha_per_target) estimator.fit(X, y, sample_weight=sample_weight) self.alpha_ = estimator.alpha_ self.best_score_ = estimator.best_score_ if self.store_cv_values: self.cv_values_ = estimator.cv_values_ else: if self.store_cv_values: raise ValueError("cv!=None and store_cv_values=True" " are incompatible") if self.alpha_per_target: raise ValueError("cv!=None and alpha_per_target=True" " are incompatible") parameters = {'alpha': self.alphas} solver = 'sparse_cg' if sparse.issparse(X) else 'auto' model = RidgeClassifier if is_classifier(self) else Ridge gs = GridSearchCV(model(fit_intercept=self.fit_intercept, normalize=self.normalize, solver=solver), parameters, cv=cv, scoring=self.scoring) gs.fit(X, y, sample_weight=sample_weight) estimator = gs.best_estimator_ self.alpha_ = gs.best_estimator_.alpha self.best_score_ = gs.best_score_ self.coef_ = estimator.coef_ self.intercept_ = estimator.intercept_ self.n_features_in_ = estimator.n_features_in_ return self class RidgeCV(MultiOutputMixin, RegressorMixin, _BaseRidgeCV): """Ridge regression with built-in cross-validation. See glossary entry for :term:`cross-validation estimator`. By default, it performs Leave-One-Out Cross-Validation, which is a form of efficient Leave-One-Out cross-validation. Read more in the :ref:`User Guide <ridge_regression>`. Parameters ---------- alphas : ndarray of shape (n_alphas,), default=(0.1, 1.0, 10.0) Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. If using Leave-One-Out cross-validation, alphas must be positive. fit_intercept : bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered). normalize : bool, default=False This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use :class:`~sklearn.preprocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. scoring : string, callable, default=None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. If None, the negative mean squared error if cv is 'auto' or None (i.e. when using leave-one-out cross-validation), and r2 score otherwise. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the efficient Leave-One-Out cross-validation - integer, to specify the number of folds. - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`~sklearn.model_selection.StratifiedKFold` is used, else, :class:`~sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. gcv_mode : {'auto', 'svd', eigen'}, default='auto' Flag indicating which strategy to use when performing Leave-One-Out Cross-Validation. Options are:: 'auto' : use 'svd' if n_samples > n_features, otherwise use 'eigen' 'svd' : force use of singular value decomposition of X when X is dense, eigenvalue decomposition of X^T.X when X is sparse. 'eigen' : force computation via eigendecomposition of X.X^T The 'auto' mode is the default and is intended to pick the cheaper option of the two depending on the shape of the training data. store_cv_values : bool, default=False Flag indicating if the cross-validation values corresponding to each alpha should be stored in the ``cv_values_`` attribute (see below). This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). alpha_per_target : bool, default=False Flag indicating whether to optimize the alpha value (picked from the `alphas` parameter list) for each target separately (for multi-output settings: multiple prediction targets). When set to `True`, after fitting, the `alpha_` attribute will contain a value for each target. When set to `False`, a single alpha is used for all targets. .. versionadded:: 0.24 Attributes ---------- cv_values_ : ndarray of shape (n_samples, n_alphas) or \ shape (n_samples, n_targets, n_alphas), optional Cross-validation values for each alpha (only available if ``store_cv_values=True`` and ``cv=None``). After ``fit()`` has been called, this attribute will contain the mean squared errors (by default) or the values of the ``{loss,score}_func`` function (if provided in the constructor). coef_ : ndarray of shape (n_features) or (n_targets, n_features) Weight vector(s). intercept_ : float or ndarray of shape (n_targets,) Independent term in decision function. Set to 0.0 if ``fit_intercept = False``. alpha_ : float or ndarray of shape (n_targets,) Estimated regularization parameter, or, if ``alpha_per_target=True``, the estimated regularization parameter for each target. best_score_ : float or ndarray of shape (n_targets,) Score of base estimator with best alpha, or, if ``alpha_per_target=True``, a score for each target. .. versionadded:: 0.23 Examples -------- >>> from sklearn.datasets import load_diabetes >>> from sklearn.linear_model import RidgeCV >>> X, y = load_diabetes(return_X_y=True) >>> clf = RidgeCV(alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y) >>> clf.score(X, y) 0.5166... See Also -------- Ridge : Ridge regression. RidgeClassifier : Ridge classifier. RidgeClassifierCV : Ridge classifier with built-in cross validation. """ class RidgeClassifierCV(LinearClassifierMixin, _BaseRidgeCV): """Ridge classifier with built-in cross-validation. See glossary entry for :term:`cross-validation estimator`. By default, it performs Leave-One-Out Cross-Validation. Currently, only the n_features > n_samples case is handled efficiently. Read more in the :ref:`User Guide <ridge_regression>`. Parameters ---------- alphas : ndarray of shape (n_alphas,), default=(0.1, 1.0, 10.0) Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the conditioning of the problem and reduces the variance of the estimates. Larger values specify stronger regularization. Alpha corresponds to ``1 / (2C)`` in other linear models such as :class:`~sklearn.linear_model.LogisticRegression` or :class:`~sklearn.svm.LinearSVC`. fit_intercept : bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered). normalize : bool, default=False This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use :class:`~sklearn.preprocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. scoring : string, callable, default=None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the efficient Leave-One-Out cross-validation - integer, to specify the number of folds. - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. class_weight : dict or 'balanced', default=None Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` store_cv_values : bool, default=False Flag indicating if the cross-validation values corresponding to each alpha should be stored in the ``cv_values_`` attribute (see below). This flag is only compatible with ``cv=None`` (i.e. using Leave-One-Out Cross-Validation). Attributes ---------- cv_values_ : ndarray of shape (n_samples, n_targets, n_alphas), optional Cross-validation values for each alpha (if ``store_cv_values=True`` and ``cv=None``). After ``fit()`` has been called, this attribute will contain the mean squared errors (by default) or the values of the ``{loss,score}_func`` function (if provided in the constructor). This attribute exists only when ``store_cv_values`` is True. coef_ : ndarray of shape (1, n_features) or (n_targets, n_features) Coefficient of the features in the decision function. ``coef_`` is of shape (1, n_features) when the given problem is binary. intercept_ : float or ndarray of shape (n_targets,) Independent term in decision function. Set to 0.0 if ``fit_intercept = False``. alpha_ : float Estimated regularization parameter. best_score_ : float Score of base estimator with best alpha. .. versionadded:: 0.23 classes_ : ndarray of shape (n_classes,) The classes labels. Examples -------- >>> from sklearn.datasets import load_breast_cancer >>> from sklearn.linear_model import RidgeClassifierCV >>> X, y = load_breast_cancer(return_X_y=True) >>> clf = RidgeClassifierCV(alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y) >>> clf.score(X, y) 0.9630... See Also -------- Ridge : Ridge regression. RidgeClassifier : Ridge classifier. RidgeCV : Ridge regression with built-in cross validation. Notes ----- For multi-class classification, n_class classifiers are trained in a one-versus-all approach. Concretely, this is implemented by taking advantage of the multi-variate response support in Ridge. """ @_deprecate_positional_args def __init__(self, alphas=(0.1, 1.0, 10.0), *, fit_intercept=True, normalize=False, scoring=None, cv=None, class_weight=None, store_cv_values=False): super().__init__( alphas=alphas, fit_intercept=fit_intercept, normalize=normalize, scoring=scoring, cv=cv, store_cv_values=store_cv_values) self.class_weight = class_weight def fit(self, X, y, sample_weight=None): """Fit Ridge classifier with cv. Parameters ---------- X : ndarray of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. When using GCV, will be cast to float64 if necessary. y : ndarray of shape (n_samples,) Target values. Will be cast to X's dtype if necessary. sample_weight : float or ndarray of shape (n_samples,), default=None Individual weights for each sample. If given a float, every sample will have the same weight. Returns ------- self : object """ X, y = self._validate_data(X, y, accept_sparse=['csr', 'csc', 'coo'], multi_output=True, y_numeric=False) sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) self._label_binarizer = LabelBinarizer(pos_label=1, neg_label=-1) Y = self._label_binarizer.fit_transform(y) if not self._label_binarizer.y_type_.startswith('multilabel'): y = column_or_1d(y, warn=True) if self.class_weight: # modify the sample weights with the corresponding class weight sample_weight = (sample_weight * compute_sample_weight(self.class_weight, y)) target = Y if self.cv is None else y _BaseRidgeCV.fit(self, X, target, sample_weight=sample_weight) return self @property def classes_(self): return self._label_binarizer.classes_ def _more_tags(self): return { '_xfail_checks': { 'check_sample_weights_invariance': 'zero sample_weight is not equivalent to removing samples', } }
bsd-3-clause
jriehl/numba
examples/blackscholes/blackscholes.py
2
2059
#! /usr/bin/env python from __future__ import print_function import time import numpy as np RISKFREE = 0.02 VOLATILITY = 0.30 def cnd(d): A1 = 0.31938153 A2 = -0.356563782 A3 = 1.781477937 A4 = -1.821255978 A5 = 1.330274429 RSQRT2PI = 0.39894228040143267793994605993438 K = 1.0 / (1.0 + 0.2316419 * np.abs(d)) ret_val = (RSQRT2PI * np.exp(-0.5 * d * d) * (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))))) return np.where(d > 0, 1.0 - ret_val, ret_val) # Despite the memory overhead and redundant computation, the above # is much faster than: # for i in range(len(d)): # if d[i] > 0: # ret_val[i] = 1.0 - ret_val[i] # return ret_val def black_scholes(callResult, putResult, stockPrice, optionStrike, optionYears, Riskfree, Volatility): S = stockPrice X = optionStrike T = optionYears R = Riskfree V = Volatility sqrtT = np.sqrt(T) d1 = (np.log(S / X) + (R + 0.5 * V * V) * T) / (V * sqrtT) d2 = d1 - V * sqrtT cndd1 = cnd(d1) cndd2 = cnd(d2) expRT = np.exp(- R * T) callResult[:] = (S * cndd1 - X * expRT * cndd2) putResult[:] = (X * expRT * (1.0 - cndd2) - S * (1.0 - cndd1)) def randfloat(rand_var, low, high): return (1.0 - rand_var) * low + rand_var * high def main (*args): OPT_N = 4000000 iterations = 10 if len(args) >= 2: iterations = int(args[0]) callResult = np.zeros(OPT_N) putResult = -np.ones(OPT_N) stockPrice = randfloat(np.random.random(OPT_N), 5.0, 30.0) optionStrike = randfloat(np.random.random(OPT_N), 1.0, 100.0) optionYears = randfloat(np.random.random(OPT_N), 0.25, 10.0) time0 = time.time() for i in range(iterations): black_scholes(callResult, putResult, stockPrice, optionStrike, optionYears, RISKFREE, VOLATILITY) time1 = time.time() print("Time: %f msec" % ((time1 - time0) / iterations * 1000)) if __name__ == "__main__": import sys main(*sys.argv[1:])
bsd-2-clause
ionutbalutoiu/ironic
ironic/drivers/modules/oneview/management.py
5
6510
# # Copyright 2015 Hewlett Packard Development Company, LP # Copyright 2015 Universidade Federal de Campina Grande # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_log import log as logging from oslo_utils import importutils from ironic.common import boot_devices from ironic.common import exception from ironic.common.i18n import _ from ironic.conductor import task_manager from ironic.drivers import base from ironic.drivers.modules.oneview import common LOG = logging.getLogger(__name__) BOOT_DEVICE_MAPPING_TO_OV = { boot_devices.DISK: 'HardDisk', boot_devices.PXE: 'PXE', boot_devices.CDROM: 'CD', } BOOT_DEVICE_OV_TO_GENERIC = { v: k for k, v in BOOT_DEVICE_MAPPING_TO_OV.items() } oneview_exceptions = importutils.try_import('oneview_client.exceptions') class OneViewManagement(base.ManagementInterface): def get_properties(self): return common.COMMON_PROPERTIES def validate(self, task): """Checks required info on 'driver_info' and validates node with OneView Validates whether the 'driver_info' property of the supplied task's node contains the required info such as server_hardware_uri, server_hardware_type, server_profile_template_uri and enclosure_group_uri. Also, checks if the server profile of the node is applied, if NICs are valid for the server profile of the node, and if the server hardware attributes (ram, memory, vcpus count) are consistent with OneView. :param task: a task from TaskManager. :raises: InvalidParameterValue if parameters set are inconsistent with resources in OneView """ common.verify_node_info(task.node) try: common.validate_oneview_resources_compatibility(task) except exception.OneViewError as oneview_exc: raise exception.InvalidParameterValue(oneview_exc) def get_supported_boot_devices(self, task): """Gets a list of the supported boot devices. :param task: a task from TaskManager. :returns: A list with the supported boot devices defined in :mod:`ironic.common.boot_devices`. """ return sorted(BOOT_DEVICE_MAPPING_TO_OV.keys()) @task_manager.require_exclusive_lock @common.node_has_server_profile def set_boot_device(self, task, device, persistent=False): """Sets the boot device for a node. Sets the boot device to use on next reboot of the node. :param task: a task from TaskManager. :param device: the boot device, one of the supported devices listed in :mod:`ironic.common.boot_devices`. :param persistent: Boolean value. True if the boot device will persist to all future boots, False if not. Default: False. :raises: InvalidParameterValue if an invalid boot device is specified. :raises: OperationNotPermitted if the server has no server profile or if the server is already powered on. :raises: OneViewError if the communication with OneView fails """ oneview_info = common.get_oneview_info(task.node) if device not in self.get_supported_boot_devices(task): raise exception.InvalidParameterValue( _("Invalid boot device %s specified.") % device) LOG.debug("Setting boot device to %(device)s for node %(node)s", {"device": device, "node": task.node.uuid}) try: oneview_client = common.get_oneview_client() device_to_oneview = BOOT_DEVICE_MAPPING_TO_OV.get(device) oneview_client.set_boot_device(oneview_info, device_to_oneview) except oneview_exceptions.OneViewException as oneview_exc: msg = (_( "Error setting boot device on OneView. Error: %s") % oneview_exc ) LOG.error(msg) raise exception.OneViewError(error=msg) @common.node_has_server_profile def get_boot_device(self, task): """Get the current boot device for the task's node. Provides the current boot device of the node. :param task: a task from TaskManager. :returns: a dictionary containing: :boot_device: the boot device, one of :mod:`ironic.common.boot_devices` [PXE, DISK, CDROM] :persistent: Whether the boot device will persist to all future boots or not, None if it is unknown. :raises: OperationNotPermitted if no Server Profile is associated with the node :raises: InvalidParameterValue if the boot device is unknown :raises: OneViewError if the communication with OneView fails """ oneview_info = common.get_oneview_info(task.node) try: oneview_client = common.get_oneview_client() boot_order = oneview_client.get_boot_order(oneview_info) except oneview_exceptions.OneViewException as oneview_exc: msg = (_( "Error getting boot device from OneView. Error: %s") % oneview_exc ) LOG.error(msg) raise exception.OneViewError(msg) primary_device = boot_order[0] if primary_device not in BOOT_DEVICE_OV_TO_GENERIC: raise exception.InvalidParameterValue( _("Unsupported boot Device %(device)s for Node: %(node)s") % {"device": primary_device, "node": task.node.uuid} ) boot_device = { 'boot_device': BOOT_DEVICE_OV_TO_GENERIC.get(primary_device), 'persistent': True, } return boot_device def get_sensors_data(self, task): """Get sensors data. Not implemented by this driver. :param task: a TaskManager instance. """ raise NotImplementedError()
apache-2.0
ddy88958620/lib
Python/scrapy/petsafe/amazoncom_petsafe.py
2
1919
from csv import DictReader from petsafeconfig import CSV_FILENAME from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request from product_spiders.items import Product, ProductLoader import logging class AmazonComPetsafeSpider(BaseSpider): name = 'amazon.com_petsafe' allowed_domains = ['amazon.com'] start_urls = () site_name_csv = 'amazon.com' def start_requests(self): products = [] with open(CSV_FILENAME, 'rb') as csv_file: csv_reader = DictReader(csv_file) for row in csv_reader: if row['Retailer'] == self.site_name_csv and row['Link'] != '': products.append((row['SKU'].strip(), row['Link'].strip(), row['Notes'].strip(), row['Name of Product'].strip().decode('utf-8'))) for sku, url, notes, name in products: yield Request(url, self.parse, meta={'sku': sku, 'notes': notes, 'name': name}, dont_filter=True) def parse(self, response): hxs = HtmlXPathSelector(response) url = response.url sku = response.meta['sku'] name = hxs.select("//h1[contains(@class, 'parseasinTitle')]/span/text()").extract() if not name: logging.error('ERROR!! NO NAME!! %s "%s"' % (sku, url)) return name = name[0].strip() price = hxs.select("//table[@class='product']//span[@id='actualPriceValue']/b/text()").extract() if not price: logging.error('ERROR!! NO PRICE!! %s "%s" "%s"' % (sku, name, url)) return price = price[0].strip() product = Product() loader = ProductLoader(item=product, response=response, selector=hxs) loader.add_value('url', url) loader.add_value('name', name) loader.add_value('price', price) loader.add_value('sku', sku) yield loader.load_item()
apache-2.0
direvus/ansible
test/units/playbook/test_playbook.py
119
2239
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.tests import unittest from ansible.compat.tests.mock import patch, MagicMock from ansible.errors import AnsibleError, AnsibleParserError from ansible.playbook import Playbook from ansible.vars.manager import VariableManager from units.mock.loader import DictDataLoader class TestPlaybook(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_empty_playbook(self): fake_loader = DictDataLoader({}) p = Playbook(loader=fake_loader) def test_basic_playbook(self): fake_loader = DictDataLoader({ "test_file.yml": """ - hosts: all """, }) p = Playbook.load("test_file.yml", loader=fake_loader) plays = p.get_plays() def test_bad_playbook_files(self): fake_loader = DictDataLoader({ # represents a playbook which is not a list of plays "bad_list.yml": """ foo: bar """, # represents a playbook where a play entry is mis-formatted "bad_entry.yml": """ - - "This should be a mapping..." """, }) vm = VariableManager() self.assertRaises(AnsibleParserError, Playbook.load, "bad_list.yml", vm, fake_loader) self.assertRaises(AnsibleParserError, Playbook.load, "bad_entry.yml", vm, fake_loader)
gpl-3.0
xaxa89/mitmproxy
test/mitmproxy/addons/test_readfile.py
1
1691
from mitmproxy.addons import readfile from mitmproxy.test import taddons from mitmproxy.test import tflow from mitmproxy import io from mitmproxy import exceptions from unittest import mock import pytest def write_data(path, corrupt=False): with open(path, "wb") as tf: w = io.FlowWriter(tf) for i in range(3): f = tflow.tflow(resp=True) w.add(f) for i in range(3): f = tflow.tflow(err=True) w.add(f) f = tflow.ttcpflow() w.add(f) f = tflow.ttcpflow(err=True) w.add(f) if corrupt: tf.write(b"flibble") @mock.patch('mitmproxy.master.Master.load_flow') def test_configure(mck, tmpdir): rf = readfile.ReadFile() with taddons.context() as tctx: tf = str(tmpdir.join("tfile")) write_data(tf) tctx.configure(rf, rfile=str(tf)) assert not mck.called rf.running() assert mck.called write_data(tf, corrupt=True) tctx.configure(rf, rfile=str(tf)) with pytest.raises(exceptions.OptionsError): rf.running() @mock.patch('mitmproxy.master.Master.load_flow') def test_corruption(mck, tmpdir): rf = readfile.ReadFile() with taddons.context() as tctx: with pytest.raises(exceptions.FlowReadException): rf.load_flows_file("nonexistent") assert not mck.called assert len(tctx.master.logs) == 1 tfc = str(tmpdir.join("tfile")) write_data(tfc, corrupt=True) with pytest.raises(exceptions.FlowReadException): rf.load_flows_file(tfc) assert mck.called assert len(tctx.master.logs) == 2
mit
oliverlee/sympy
sympy/core/tests/test_function.py
2
24032
from sympy import (Lambda, Symbol, Function, Derivative, Subs, sqrt, log, exp, Rational, Float, sin, cos, acos, diff, I, re, im, E, expand, pi, O, Sum, S, polygamma, loggamma, expint, Tuple, Dummy, Eq, Expr, symbols, nfloat) from sympy.utilities.pytest import XFAIL, raises from sympy.abc import t, w, x, y, z from sympy.core.function import PoleError, _mexpand from sympy.sets.sets import FiniteSet from sympy.solvers.solveset import solveset from sympy.utilities.iterables import subsets, variations from sympy.core.cache import clear_cache from sympy.core.compatibility import range f, g, h = symbols('f g h', cls=Function) def test_f_expand_complex(): x = Symbol('x', real=True) assert f(x).expand(complex=True) == I*im(f(x)) + re(f(x)) assert exp(x).expand(complex=True) == exp(x) assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x) assert exp(z).expand(complex=True) == cos(im(z))*exp(re(z)) + \ I*sin(im(z))*exp(re(z)) def test_bug1(): e = sqrt(-log(w)) assert e.subs(log(w), -x) == sqrt(x) e = sqrt(-5*log(w)) assert e.subs(log(w), -x) == sqrt(5*x) def test_general_function(): nu = Function('nu') e = nu(x) edx = e.diff(x) edy = e.diff(y) edxdx = e.diff(x).diff(x) edxdy = e.diff(x).diff(y) assert e == nu(x) assert edx != nu(x) assert edx == diff(nu(x), x) assert edy == 0 assert edxdx == diff(diff(nu(x), x), x) assert edxdy == 0 def test_derivative_subs_bug(): e = diff(g(x), x) assert e.subs(g(x), f(x)) != e assert e.subs(g(x), f(x)) == Derivative(f(x), x) assert e.subs(g(x), -f(x)) == Derivative(-f(x), x) assert e.subs(x, y) == Derivative(g(y), y) def test_derivative_subs_self_bug(): d = diff(f(x), x) assert d.subs(d, y) == y def test_derivative_linearity(): assert diff(-f(x), x) == -diff(f(x), x) assert diff(8*f(x), x) == 8*diff(f(x), x) assert diff(8*f(x), x) != 7*diff(f(x), x) assert diff(8*f(x)*x, x) == 8*f(x) + 8*x*diff(f(x), x) assert diff(8*f(x)*y*x, x) == 8*y*f(x) + 8*y*x*diff(f(x), x) def test_derivative_evaluate(): assert Derivative(sin(x), x) != diff(sin(x), x) assert Derivative(sin(x), x).doit() == diff(sin(x), x) assert Derivative(Derivative(f(x), x), x) == diff(f(x), x, x) assert Derivative(sin(x), x, 0) == sin(x) def test_diff_symbols(): assert diff(f(x, y, z), x, y, z) == Derivative(f(x, y, z), x, y, z) assert diff(f(x, y, z), x, x, x) == Derivative(f(x, y, z), x, x, x) assert diff(f(x, y, z), x, 3) == Derivative(f(x, y, z), x, 3) # issue 5028 assert [diff(-z + x/y, sym) for sym in (z, x, y)] == [-1, 1/y, -x/y**2] assert diff(f(x, y, z), x, y, z, 2) == Derivative(f(x, y, z), x, y, z, z) assert diff(f(x, y, z), x, y, z, 2, evaluate=False) == \ Derivative(f(x, y, z), x, y, z, z) assert Derivative(f(x, y, z), x, y, z)._eval_derivative(z) == \ Derivative(f(x, y, z), x, y, z, z) assert Derivative(Derivative(f(x, y, z), x), y)._eval_derivative(z) == \ Derivative(f(x, y, z), x, y, z) def test_Function(): class myfunc(Function): @classmethod def eval(cls, x): # one arg return assert myfunc.nargs == FiniteSet(1) assert myfunc(x).nargs == FiniteSet(1) raises(TypeError, lambda: myfunc(x, y).nargs) class myfunc(Function): @classmethod def eval(cls, *x): # star args return assert myfunc.nargs == S.Naturals0 assert myfunc(x).nargs == S.Naturals0 def test_nargs(): f = Function('f') assert f.nargs == S.Naturals0 assert f(1).nargs == S.Naturals0 assert Function('f', nargs=2)(1, 2).nargs == FiniteSet(2) assert sin.nargs == FiniteSet(1) assert sin(2).nargs == FiniteSet(1) assert log.nargs == FiniteSet(1, 2) assert log(2).nargs == FiniteSet(1, 2) assert Function('f', nargs=2).nargs == FiniteSet(2) assert Function('f', nargs=0).nargs == FiniteSet(0) assert Function('f', nargs=(0, 1)).nargs == FiniteSet(0, 1) assert Function('f', nargs=None).nargs == S.Naturals0 raises(ValueError, lambda: Function('f', nargs=())) def test_Lambda(): e = Lambda(x, x**2) assert e(4) == 16 assert e(x) == x**2 assert e(y) == y**2 assert Lambda(x, x**2) == Lambda(x, x**2) assert Lambda(x, x**2) == Lambda(y, y**2) assert Lambda(x, x**2) != Lambda(y, y**2 + 1) assert Lambda((x, y), x**y) == Lambda((y, x), y**x) assert Lambda((x, y), x**y) != Lambda((x, y), y**x) assert Lambda((x, y), x**y)(x, y) == x**y assert Lambda((x, y), x**y)(3, 3) == 3**3 assert Lambda((x, y), x**y)(x, 3) == x**3 assert Lambda((x, y), x**y)(3, y) == 3**y assert Lambda(x, f(x))(x) == f(x) assert Lambda(x, x**2)(e(x)) == x**4 assert e(e(x)) == x**4 assert Lambda((x, y), x + y).nargs == FiniteSet(2) p = x, y, z, t assert Lambda(p, t*(x + y + z))(*p) == t * (x + y + z) assert Lambda(x, 2*x) + Lambda(y, 2*y) == 2*Lambda(x, 2*x) assert Lambda(x, 2*x) not in [ Lambda(x, x) ] raises(TypeError, lambda: Lambda(1, x)) assert Lambda(x, 1)(1) is S.One def test_IdentityFunction(): assert Lambda(x, x) is Lambda(y, y) is S.IdentityFunction assert Lambda(x, 2*x) is not S.IdentityFunction assert Lambda((x, y), x) is not S.IdentityFunction def test_Lambda_symbols(): assert Lambda(x, 2*x).free_symbols == set() assert Lambda(x, x*y).free_symbols == set([y]) def test_Lambda_arguments(): raises(TypeError, lambda: Lambda(x, 2*x)(x, y)) raises(TypeError, lambda: Lambda((x, y), x + y)(x)) def test_Lambda_equality(): assert Lambda(x, 2*x) == Lambda(y, 2*y) # although variables are casts as Dummies, the expressions # should still compare equal assert Lambda((x, y), 2*x) == Lambda((x, y), 2*x) assert Lambda(x, 2*x) != Lambda((x, y), 2*x) assert Lambda(x, 2*x) != 2*x def test_Subs(): assert Subs(x, x, 0) == Subs(y, y, 0) assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0) assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0) assert Subs(f(x), x, 0).doit() == f(0) assert Subs(f(x**2), x**2, 0).doit() == f(0) assert Subs(f(x, y, z), (x, y, z), (0, 1, 1)) != \ Subs(f(x, y, z), (x, y, z), (0, 0, 1)) assert Subs(f(x, y), (x, y, z), (0, 1, 1)) == \ Subs(f(x, y), (x, y, z), (0, 1, 2)) assert Subs(f(x, y), (x, y, z), (0, 1, 1)) != \ Subs(f(x, y) + z, (x, y, z), (0, 1, 0)) assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1) assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1) raises(ValueError, lambda: Subs(f(x, y), (x, y), (0, 0, 1))) raises(ValueError, lambda: Subs(f(x, y), (x, x, y), (0, 0, 1))) assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2 assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1) assert Subs(f(x), x, 0) == Subs(f(y), y, 0) assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0)) assert Subs(f(x)*y, (x, y), (0, 1)) == Subs(f(y)*x, (y, x), (0, 1)) assert Subs(f(x)*y, (x, y), (1, 1)) == Subs(f(y)*x, (x, y), (1, 1)) assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0) assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0) assert Subs(y*f(x), x, y).subs(y, 2) == Subs(2*f(x), x, 2) assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2*y assert Subs(f(x), x, 0).free_symbols == set([]) assert Subs(f(x, y), x, z).free_symbols == set([y, z]) assert Subs(f(x).diff(x), x, 0).doit(), Subs(f(x).diff(x), x, 0) assert Subs(1 + f(x).diff(x), x, 0).doit(), 1 + Subs(f(x).diff(x), x, 0) assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \ 2*Subs(Derivative(f(x, 2), x), x, 0) assert Subs(y**2*f(x), x, 0).diff(y) == 2*y*f(0) e = Subs(y**2*f(x), x, y) assert e.diff(y) == e.doit().diff(y) == y**2*Derivative(f(y), y) + 2*y*f(y) assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2*Subs(f(x), x, 0) e1 = Subs(z*f(x), x, 1) e2 = Subs(z*f(y), y, 1) assert e1 + e2 == 2*e1 assert e1.__hash__() == e2.__hash__() assert Subs(z*f(x + 1), x, 1) not in [ e1, e2 ] assert Derivative( f(x), x).subs(x, g(x)) == Subs(Derivative(f(x), x), (x,), (g(x),)) assert Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).n(2) == \ Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \ z + Rational('1/2').n(2)*f(0) assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0) assert (x*f(x).diff(x).subs(x, 0)).subs(x, y) == y*f(x).diff(x).subs(x, 0) @XFAIL def test_Subs2(): # this reflects a limitation of subs(), probably won't fix assert Subs(f(x), x**2, x).doit() == f(sqrt(x)) def test_expand_function(): assert expand(x + y) == x + y assert expand(x + y, complex=True) == I*im(x) + I*im(y) + re(x) + re(y) assert expand((x + y)**11, modulus=11) == x**11 + y**11 def test_function_comparable(): assert sin(x).is_comparable is False assert cos(x).is_comparable is False assert sin(Float('0.1')).is_comparable is True assert cos(Float('0.1')).is_comparable is True assert sin(E).is_comparable is True assert cos(E).is_comparable is True assert sin(Rational(1, 3)).is_comparable is True assert cos(Rational(1, 3)).is_comparable is True @XFAIL def test_function_comparable_infinities(): assert sin(oo).is_comparable is False assert sin(-oo).is_comparable is False assert sin(zoo).is_comparable is False assert sin(nan).is_comparable is False def test_deriv1(): # These all requre derivatives evaluated at a point (issue 4719) to work. # See issue 4624 assert f(2*x).diff(x) == 2*Subs(Derivative(f(x), x), Tuple(x), Tuple(2*x)) assert (f(x)**3).diff(x) == 3*f(x)**2*f(x).diff(x) assert ( f(2*x)**3).diff(x) == 6*f(2*x)**2*Subs(Derivative(f(x), x), Tuple(x), Tuple(2*x)) assert f(2 + x).diff(x) == Subs(Derivative(f(x), x), Tuple(x), Tuple(x + 2)) assert f(2 + 3*x).diff(x) == 3*Subs(Derivative(f(x), x), Tuple(x), Tuple(3*x + 2)) assert f(3*sin(x)).diff(x) == 3*cos(x)*Subs(Derivative(f(x), x), Tuple(x), Tuple(3*sin(x))) # See issue 8510 assert f(x, x + z).diff(x) == Subs(Derivative(f(y, x + z), y), Tuple(y), Tuple(x)) \ + Subs(Derivative(f(x, y), y), Tuple(y), Tuple(x + z)) assert f(x, x**2).diff(x) == Subs(Derivative(f(y, x**2), y), Tuple(y), Tuple(x)) \ + 2*x*Subs(Derivative(f(x, y), y), Tuple(y), Tuple(x**2)) def test_deriv2(): assert (x**3).diff(x) == 3*x**2 assert (x**3).diff(x, evaluate=False) != 3*x**2 assert (x**3).diff(x, evaluate=False) == Derivative(x**3, x) assert diff(x**3, x) == 3*x**2 assert diff(x**3, x, evaluate=False) != 3*x**2 assert diff(x**3, x, evaluate=False) == Derivative(x**3, x) def test_func_deriv(): assert f(x).diff(x) == Derivative(f(x), x) # issue 4534 assert f(x, y).diff(x, y) - f(x, y).diff(y, x) == 0 assert Derivative(f(x, y), x, y).args[1:] == (x, y) assert Derivative(f(x, y), y, x).args[1:] == (y, x) assert (Derivative(f(x, y), x, y) - Derivative(f(x, y), y, x)).doit() == 0 def test_suppressed_evaluation(): a = sin(0, evaluate=False) assert a != 0 assert a.func is sin assert a.args == (0,) def test_function_evalf(): def eq(a, b, eps): return abs(a - b) < eps assert eq(sin(1).evalf(15), Float("0.841470984807897"), 1e-13) assert eq( sin(2).evalf(25), Float("0.9092974268256816953960199", 25), 1e-23) assert eq(sin(1 + I).evalf( 15), Float("1.29845758141598") + Float("0.634963914784736")*I, 1e-13) assert eq(exp(1 + I).evalf(15), Float( "1.46869393991588") + Float("2.28735528717884239")*I, 1e-13) assert eq(exp(-0.5 + 1.5*I).evalf(15), Float( "0.0429042815937374") + Float("0.605011292285002")*I, 1e-13) assert eq(log(pi + sqrt(2)*I).evalf( 15), Float("1.23699044022052") + Float("0.422985442737893")*I, 1e-13) assert eq(cos(100).evalf(15), Float("0.86231887228768"), 1e-13) def test_extensibility_eval(): class MyFunc(Function): @classmethod def eval(cls, *args): return (0, 0, 0) assert MyFunc(0) == (0, 0, 0) def test_function_non_commutative(): x = Symbol('x', commutative=False) assert f(x).is_commutative is False assert sin(x).is_commutative is False assert exp(x).is_commutative is False assert log(x).is_commutative is False assert f(x).is_complex is False assert sin(x).is_complex is False assert exp(x).is_complex is False assert log(x).is_complex is False def test_function_complex(): x = Symbol('x', complex=True) assert f(x).is_commutative is True assert sin(x).is_commutative is True assert exp(x).is_commutative is True assert log(x).is_commutative is True assert f(x).is_complex is True assert sin(x).is_complex is True assert exp(x).is_complex is True assert log(x).is_complex is True def test_function__eval_nseries(): n = Symbol('n') assert sin(x)._eval_nseries(x, 2, None) == x + O(x**2) assert sin(x + 1)._eval_nseries(x, 2, None) == x*cos(1) + sin(1) + O(x**2) assert sin(pi*(1 - x))._eval_nseries(x, 2, None) == pi*x + O(x**2) assert acos(1 - x**2)._eval_nseries(x, 2, None) == sqrt(2)*x + O(x**2) assert polygamma(n, x + 1)._eval_nseries(x, 2, None) == \ polygamma(n, 1) + polygamma(n + 1, 1)*x + O(x**2) raises(PoleError, lambda: sin(1/x)._eval_nseries(x, 2, None)) raises(PoleError, lambda: acos(1 - x)._eval_nseries(x, 2, None)) raises(PoleError, lambda: acos(1 + x)._eval_nseries(x, 2, None)) assert loggamma(1/x)._eval_nseries(x, 0, None) == \ log(x)/2 - log(x)/x - 1/x + O(1, x) assert loggamma(log(1/x)).nseries(x, n=1, logx=y) == loggamma(-y) # issue 6725: assert expint(S(3)/2, -x)._eval_nseries(x, 5, None) == \ 2 - 2*sqrt(pi)*sqrt(-x) - 2*x - x**2/3 - x**3/15 - x**4/84 + O(x**5) assert sin(sqrt(x))._eval_nseries(x, 3, None) == \ sqrt(x) - x**(S(3)/2)/6 + x**(S(5)/2)/120 + O(x**3) def test_doit(): n = Symbol('n', integer=True) f = Sum(2 * n * x, (n, 1, 3)) d = Derivative(f, x) assert d.doit() == 12 assert d.doit(deep=False) == Sum(2*n, (n, 1, 3)) def test_evalf_default(): from sympy.functions.special.gamma_functions import polygamma assert type(sin(4.0)) == Float assert type(re(sin(I + 1.0))) == Float assert type(im(sin(I + 1.0))) == Float assert type(sin(4)) == sin assert type(polygamma(2.0, 4.0)) == Float assert type(sin(Rational(1, 4))) == sin def test_issue_5399(): args = [x, y, S(2), S.Half] def ok(a): """Return True if the input args for diff are ok""" if not a: return False if a[0].is_Symbol is False: return False s_at = [i for i in range(len(a)) if a[i].is_Symbol] n_at = [i for i in range(len(a)) if not a[i].is_Symbol] # every symbol is followed by symbol or int # every number is followed by a symbol return (all(a[i + 1].is_Symbol or a[i + 1].is_Integer for i in s_at if i + 1 < len(a)) and all(a[i + 1].is_Symbol for i in n_at if i + 1 < len(a))) eq = x**10*y**8 for a in subsets(args): for v in variations(a, len(a)): if ok(v): noraise = eq.diff(*v) else: raises(ValueError, lambda: eq.diff(*v)) def test_derivative_numerically(): from random import random z0 = random() + I*random() assert abs(Derivative(sin(x), x).doit_numerically(z0) - cos(z0)) < 1e-15 def test_fdiff_argument_index_error(): from sympy.core.function import ArgumentIndexError class myfunc(Function): nargs = 1 # define since there is no eval routine def fdiff(self, idx): raise ArgumentIndexError mf = myfunc(x) assert mf.diff(x) == Derivative(mf, x) raises(TypeError, lambda: myfunc(x, x)) def test_deriv_wrt_function(): x = f(t) xd = diff(x, t) xdd = diff(xd, t) y = g(t) yd = diff(y, t) assert diff(x, t) == xd assert diff(2 * x + 4, t) == 2 * xd assert diff(2 * x + 4 + y, t) == 2 * xd + yd assert diff(2 * x + 4 + y * x, t) == 2 * xd + x * yd + xd * y assert diff(2 * x + 4 + y * x, x) == 2 + y assert (diff(4 * x**2 + 3 * x + x * y, t) == 3 * xd + x * yd + xd * y + 8 * x * xd) assert (diff(4 * x**2 + 3 * xd + x * y, t) == 3 * xdd + x * yd + xd * y + 8 * x * xd) assert diff(4 * x**2 + 3 * xd + x * y, xd) == 3 assert diff(4 * x**2 + 3 * xd + x * y, xdd) == 0 assert diff(sin(x), t) == xd * cos(x) assert diff(exp(x), t) == xd * exp(x) assert diff(sqrt(x), t) == xd / (2 * sqrt(x)) def test_diff_wrt_value(): assert Expr()._diff_wrt is False assert x._diff_wrt is True assert f(x)._diff_wrt is True assert Derivative(f(x), x)._diff_wrt is True assert Derivative(x**2, x)._diff_wrt is False def test_diff_wrt(): fx = f(x) dfx = diff(f(x), x) ddfx = diff(f(x), x, x) assert diff(sin(fx) + fx**2, fx) == cos(fx) + 2*fx assert diff(sin(dfx) + dfx**2, dfx) == cos(dfx) + 2*dfx assert diff(sin(ddfx) + ddfx**2, ddfx) == cos(ddfx) + 2*ddfx assert diff(fx**2, dfx) == 0 assert diff(fx**2, ddfx) == 0 assert diff(dfx**2, fx) == 0 assert diff(dfx**2, ddfx) == 0 assert diff(ddfx**2, dfx) == 0 assert diff(fx*dfx*ddfx, fx) == dfx*ddfx assert diff(fx*dfx*ddfx, dfx) == fx*ddfx assert diff(fx*dfx*ddfx, ddfx) == fx*dfx assert diff(f(x), x).diff(f(x)) == 0 assert (sin(f(x)) - cos(diff(f(x), x))).diff(f(x)) == cos(f(x)) assert diff(sin(fx), fx, x) == diff(sin(fx), x, fx) # Chain rule cases assert f(g(x)).diff(x) == \ Subs(Derivative(f(x), x), (x,), (g(x),))*Derivative(g(x), x) assert diff(f(g(x), h(x)), x) == \ Subs(Derivative(f(y, h(x)), y), (y,), (g(x),))*Derivative(g(x), x) + \ Subs(Derivative(f(g(x), y), y), (y,), (h(x),))*Derivative(h(x), x) assert f( sin(x)).diff(x) == Subs(Derivative(f(x), x), (x,), (sin(x),))*cos(x) assert diff(f(g(x)), g(x)) == Subs(Derivative(f(x), x), (x,), (g(x),)) def test_diff_wrt_func_subs(): assert f(g(x)).diff(x).subs(g, Lambda(x, 2*x)).doit() == f(2*x).diff(x) def test_diff_wrt_not_allowed(): raises(ValueError, lambda: diff(sin(x**2), x**2)) raises(ValueError, lambda: diff(exp(x*y), x*y)) raises(ValueError, lambda: diff(1 + x, 1 + x)) def test_klein_gordon_lagrangian(): m = Symbol('m') phi = f(x, t) L = -(diff(phi, t)**2 - diff(phi, x)**2 - m**2*phi**2)/2 eqna = Eq( diff(L, phi) - diff(L, diff(phi, x), x) - diff(L, diff(phi, t), t), 0) eqnb = Eq(diff(phi, t, t) - diff(phi, x, x) + m**2*phi, 0) assert eqna == eqnb def test_sho_lagrangian(): m = Symbol('m') k = Symbol('k') x = f(t) L = m*diff(x, t)**2/2 - k*x**2/2 eqna = Eq(diff(L, x), diff(L, diff(x, t), t)) eqnb = Eq(-k*x, m*diff(x, t, t)) assert eqna == eqnb assert diff(L, x, t) == diff(L, t, x) assert diff(L, diff(x, t), t) == m*diff(x, t, 2) assert diff(L, t, diff(x, t)) == -k*x + m*diff(x, t, 2) def test_straight_line(): F = f(x) Fd = F.diff(x) L = sqrt(1 + Fd**2) assert diff(L, F) == 0 assert diff(L, Fd) == Fd/sqrt(1 + Fd**2) def test_sort_variable(): vsort = Derivative._sort_variables assert vsort((x, y, z)) == [x, y, z] assert vsort((h(x), g(x), f(x))) == [f(x), g(x), h(x)] assert vsort((z, y, x, h(x), g(x), f(x))) == [x, y, z, f(x), g(x), h(x)] assert vsort((x, f(x), y, f(y))) == [x, f(x), y, f(y)] assert vsort((y, x, g(x), f(x), z, h(x), y, x)) == \ [x, y, f(x), g(x), z, h(x), x, y] assert vsort((z, y, f(x), x, f(x), g(x))) == [y, z, f(x), x, f(x), g(x)] assert vsort((z, y, f(x), x, f(x), g(x), z, z, y, x)) == \ [y, z, f(x), x, f(x), g(x), x, y, z, z] def test_unhandled(): class MyExpr(Expr): def _eval_derivative(self, s): if not s.name.startswith('xi'): return self else: return None expr = MyExpr(x, y, z) assert diff(expr, x, y, f(x), z) == Derivative(expr, f(x), z) assert diff(expr, f(x), x) == Derivative(expr, f(x), x) def test_issue_4711(): x = Symbol("x") assert Symbol('f')(x) == f(x) def test_nfloat(): from sympy.core.basic import _aresame from sympy.polys.rootoftools import rootof x = Symbol("x") eq = x**(S(4)/3) + 4*x**(S(1)/3)/3 assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(S(1)/3)) assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3)) eq = x**(S(4)/3) + 4*x**(x/3)/3 assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(x/3)) big = 12345678901234567890 # specify precision to match value used in nfloat Float_big = Float(big, 15) assert _aresame(nfloat(big), Float_big) assert _aresame(nfloat(big*x), Float_big*x) assert _aresame(nfloat(x**big, exponent=True), x**Float_big) assert nfloat({x: sqrt(2)}) == {x: nfloat(sqrt(2))} assert nfloat({sqrt(2): x}) == {sqrt(2): x} assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2))) # issue 6342 f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4') assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139))) # issue 6632 assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \ 9.99999999800000e-11 # issue 7122 eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0) assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)' def test_issue_7068(): from sympy.abc import a, b, f y1 = Dummy('y') y2 = Dummy('y') func1 = f(a + y1 * b) func2 = f(a + y2 * b) func1_y = func1.diff(y1) func2_y = func2.diff(y2) assert func1_y != func2_y z1 = Subs(f(a), a, y1) z2 = Subs(f(a), a, y2) assert z1 != z2 def test_issue_7231(): from sympy.abc import a ans1 = f(x).series(x, a) _xi_1 = ans1.atoms(Dummy).pop() res = (f(a) + (-a + x)*Subs(Derivative(f(_xi_1), _xi_1), (_xi_1,), (a,)) + (-a + x)**2*Subs(Derivative(f(_xi_1), _xi_1, _xi_1), (_xi_1,), (a,))/2 + (-a + x)**3*Subs(Derivative(f(_xi_1), _xi_1, _xi_1, _xi_1), (_xi_1,), (a,))/6 + (-a + x)**4*Subs(Derivative(f(_xi_1), _xi_1, _xi_1, _xi_1, _xi_1), (_xi_1,), (a,))/24 + (-a + x)**5*Subs(Derivative(f(_xi_1), _xi_1, _xi_1, _xi_1, _xi_1, _xi_1), (_xi_1,), (a,))/120 + O((-a + x)**6, (x, a))) assert res == ans1 ans2 = f(x).series(x, a) assert res == ans2 def test_issue_7687(): from sympy.core.function import Function from sympy.abc import x f = Function('f')(x) ff = Function('f')(x) match_with_cache = ff.matches(f) assert isinstance(f, type(ff)) clear_cache() ff = Function('f')(x) assert isinstance(f, type(ff)) assert match_with_cache == ff.matches(f) def test_issue_7688(): from sympy.core.function import Function, UndefinedFunction f = Function('f') # actually an UndefinedFunction clear_cache() class A(UndefinedFunction): pass a = A('f') assert isinstance(a, type(f)) def test_mexpand(): from sympy.abc import x assert _mexpand(None) is None assert _mexpand(1) is S.One assert _mexpand(x*(x + 1)**2) == (x*(x + 1)**2).expand() def test_issue_8469(): # This should not take forever to run N = 40 def g(w, theta): return 1/(1+exp(w-theta)) ws = symbols(['w%i'%i for i in range(N)]) import functools expr = functools.reduce(g,ws) def test_should_evalf(): # This should not take forever to run (see #8506) assert isinstance(sin((1.0 + 1.0*I)**10000 + 1), sin)
bsd-3-clause
CCI-MOC/nova
nova/api/openstack/compute/legacy_v2/contrib/extended_ips.py
79
3098
# Copyright 2013 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The Extended Ips API extension.""" import itertools from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute authorize = extensions.soft_extension_authorizer('compute', 'extended_ips') class ExtendedIpsController(wsgi.Controller): def __init__(self, *args, **kwargs): super(ExtendedIpsController, self).__init__(*args, **kwargs) self.compute_api = compute.API() def _extend_server(self, context, server, instance): key = "%s:type" % Extended_ips.alias networks = common.get_networks_for_instance(context, instance) for label, network in networks.items(): # NOTE(vish): ips are hidden in some states via the # hide_server_addresses extension. if label in server['addresses']: all_ips = itertools.chain(network["ips"], network["floating_ips"]) for i, ip in enumerate(all_ips): server['addresses'][label][i][key] = ip['type'] @wsgi.extends def show(self, req, resp_obj, id): context = req.environ['nova.context'] if authorize(context): server = resp_obj.obj['server'] db_instance = req.get_db_instance(server['id']) # server['id'] is guaranteed to be in the cache due to # the core API adding it in its 'show' method. self._extend_server(context, server, db_instance) @wsgi.extends def detail(self, req, resp_obj): context = req.environ['nova.context'] if authorize(context): servers = list(resp_obj.obj['servers']) for server in servers: db_instance = req.get_db_instance(server['id']) # server['id'] is guaranteed to be in the cache due to # the core API adding it in its 'detail' method. self._extend_server(context, server, db_instance) class Extended_ips(extensions.ExtensionDescriptor): """Adds type parameter to the ip list.""" name = "ExtendedIps" alias = "OS-EXT-IPS" namespace = ("http://docs.openstack.org/compute/ext/" "extended_ips/api/v1.1") updated = "2013-01-06T00:00:00Z" def get_controller_extensions(self): controller = ExtendedIpsController() extension = extensions.ControllerExtension(self, 'servers', controller) return [extension]
apache-2.0
openstack-hyper-v-python/numpy
numpy/lib/scimath.py
17
14074
""" Wrapper functions to more user-friendly calling of certain math functions whose output data-type is different than the input data-type in certain domains of the input. For example, for functions like `log` with branch cuts, the versions in this module provide the mathematically valid answers in the complex plane:: >>> import math >>> from numpy.lib import scimath >>> scimath.log(-math.exp(1)) == (1+1j*math.pi) True Similarly, `sqrt`, other base logarithms, `power` and trig functions are correctly handled. See their respective docstrings for specific examples. """ from __future__ import division, absolute_import, print_function __all__ = ['sqrt', 'log', 'log2', 'logn', 'log10', 'power', 'arccos', 'arcsin', 'arctanh'] import numpy.core.numeric as nx import numpy.core.numerictypes as nt from numpy.core.numeric import asarray, any from numpy.lib.type_check import isreal _ln2 = nx.log(2.0) def _tocomplex(arr): """Convert its input `arr` to a complex array. The input is returned as a complex array of the smallest type that will fit the original data: types like single, byte, short, etc. become csingle, while others become cdouble. A copy of the input is always made. Parameters ---------- arr : array Returns ------- array An array with the same input data as the input but in complex form. Examples -------- First, consider an input of type short: >>> a = np.array([1,2,3],np.short) >>> ac = np.lib.scimath._tocomplex(a); ac array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> ac.dtype dtype('complex64') If the input is of type double, the output is correspondingly of the complex double type as well: >>> b = np.array([1,2,3],np.double) >>> bc = np.lib.scimath._tocomplex(b); bc array([ 1.+0.j, 2.+0.j, 3.+0.j]) >>> bc.dtype dtype('complex128') Note that even if the input was complex to begin with, a copy is still made, since the astype() method always copies: >>> c = np.array([1,2,3],np.csingle) >>> cc = np.lib.scimath._tocomplex(c); cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> c *= 2; c array([ 2.+0.j, 4.+0.j, 6.+0.j], dtype=complex64) >>> cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) """ if issubclass(arr.dtype.type, (nt.single, nt.byte, nt.short, nt.ubyte, nt.ushort, nt.csingle)): return arr.astype(nt.csingle) else: return arr.astype(nt.cdouble) def _fix_real_lt_zero(x): """Convert `x` to complex if it has real, negative components. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_real_lt_zero([1,2]) array([1, 2]) >>> np.lib.scimath._fix_real_lt_zero([-1,2]) array([-1.+0.j, 2.+0.j]) """ x = asarray(x) if any(isreal(x) & (x<0)): x = _tocomplex(x) return x def _fix_int_lt_zero(x): """Convert `x` to double if it has real, negative components. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_int_lt_zero([1,2]) array([1, 2]) >>> np.lib.scimath._fix_int_lt_zero([-1,2]) array([-1., 2.]) """ x = asarray(x) if any(isreal(x) & (x < 0)): x = x * 1.0 return x def _fix_real_abs_gt_1(x): """Convert `x` to complex if it has real components x_i with abs(x_i)>1. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_real_abs_gt_1([0,1]) array([0, 1]) >>> np.lib.scimath._fix_real_abs_gt_1([0,2]) array([ 0.+0.j, 2.+0.j]) """ x = asarray(x) if any(isreal(x) & (abs(x)>1)): x = _tocomplex(x) return x def sqrt(x): """ Compute the square root of x. For negative input elements, a complex value is returned (unlike `numpy.sqrt` which returns NaN). Parameters ---------- x : array_like The input value(s). Returns ------- out : ndarray or scalar The square root of `x`. If `x` was a scalar, so is `out`, otherwise an array is returned. See Also -------- numpy.sqrt Examples -------- For real, non-negative inputs this works just like `numpy.sqrt`: >>> np.lib.scimath.sqrt(1) 1.0 >>> np.lib.scimath.sqrt([1, 4]) array([ 1., 2.]) But it automatically handles negative inputs: >>> np.lib.scimath.sqrt(-1) (0.0+1.0j) >>> np.lib.scimath.sqrt([-1,4]) array([ 0.+1.j, 2.+0.j]) """ x = _fix_real_lt_zero(x) return nx.sqrt(x) def log(x): """ Compute the natural logarithm of `x`. Return the "principal value" (for a description of this, see `numpy.log`) of :math:`log_e(x)`. For real `x > 0`, this is a real number (``log(0)`` returns ``-inf`` and ``log(np.inf)`` returns ``inf``). Otherwise, the complex principle value is returned. Parameters ---------- x : array_like The value(s) whose log is (are) required. Returns ------- out : ndarray or scalar The log of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array is returned. See Also -------- numpy.log Notes ----- For a log() that returns ``NAN`` when real `x < 0`, use `numpy.log` (note, however, that otherwise `numpy.log` and this `log` are identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, notably, the complex principle value if ``x.imag != 0``). Examples -------- >>> np.emath.log(np.exp(1)) 1.0 Negative arguments are handled "correctly" (recall that ``exp(log(x)) == x`` does *not* hold for real ``x < 0``): >>> np.emath.log(-np.exp(1)) == (1 + np.pi * 1j) True """ x = _fix_real_lt_zero(x) return nx.log(x) def log10(x): """ Compute the logarithm base 10 of `x`. Return the "principal value" (for a description of this, see `numpy.log10`) of :math:`log_{10}(x)`. For real `x > 0`, this is a real number (``log10(0)`` returns ``-inf`` and ``log10(np.inf)`` returns ``inf``). Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose log base 10 is (are) required. Returns ------- out : ndarray or scalar The log base 10 of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.log10 Notes ----- For a log10() that returns ``NAN`` when real `x < 0`, use `numpy.log10` (note, however, that otherwise `numpy.log10` and this `log10` are identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, notably, the complex principle value if ``x.imag != 0``). Examples -------- (We set the printing precision so the example can be auto-tested) >>> np.set_printoptions(precision=4) >>> np.emath.log10(10**1) 1.0 >>> np.emath.log10([-10**1, -10**2, 10**2]) array([ 1.+1.3644j, 2.+1.3644j, 2.+0.j ]) """ x = _fix_real_lt_zero(x) return nx.log10(x) def logn(n, x): """ Take log base n of x. If `x` contains negative inputs, the answer is computed and returned in the complex domain. Parameters ---------- n : int The base in which the log is taken. x : array_like The value(s) whose log base `n` is (are) required. Returns ------- out : ndarray or scalar The log base `n` of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array is returned. Examples -------- >>> np.set_printoptions(precision=4) >>> np.lib.scimath.logn(2, [4, 8]) array([ 2., 3.]) >>> np.lib.scimath.logn(2, [-4, -8, 8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) """ x = _fix_real_lt_zero(x) n = _fix_real_lt_zero(n) return nx.log(x)/nx.log(n) def log2(x): """ Compute the logarithm base 2 of `x`. Return the "principal value" (for a description of this, see `numpy.log2`) of :math:`log_2(x)`. For real `x > 0`, this is a real number (``log2(0)`` returns ``-inf`` and ``log2(np.inf)`` returns ``inf``). Otherwise, the complex principle value is returned. Parameters ---------- x : array_like The value(s) whose log base 2 is (are) required. Returns ------- out : ndarray or scalar The log base 2 of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array is returned. See Also -------- numpy.log2 Notes ----- For a log2() that returns ``NAN`` when real `x < 0`, use `numpy.log2` (note, however, that otherwise `numpy.log2` and this `log2` are identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, notably, the complex principle value if ``x.imag != 0``). Examples -------- We set the printing precision so the example can be auto-tested: >>> np.set_printoptions(precision=4) >>> np.emath.log2(8) 3.0 >>> np.emath.log2([-4, -8, 8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) """ x = _fix_real_lt_zero(x) return nx.log2(x) def power(x, p): """ Return x to the power p, (x**p). If `x` contains negative values, the output is converted to the complex domain. Parameters ---------- x : array_like The input value(s). p : array_like of ints The power(s) to which `x` is raised. If `x` contains multiple values, `p` has to either be a scalar, or contain the same number of values as `x`. In the latter case, the result is ``x[0]**p[0], x[1]**p[1], ...``. Returns ------- out : ndarray or scalar The result of ``x**p``. If `x` and `p` are scalars, so is `out`, otherwise an array is returned. See Also -------- numpy.power Examples -------- >>> np.set_printoptions(precision=4) >>> np.lib.scimath.power([2, 4], 2) array([ 4, 16]) >>> np.lib.scimath.power([2, 4], -2) array([ 0.25 , 0.0625]) >>> np.lib.scimath.power([-2, 4], 2) array([ 4.+0.j, 16.+0.j]) """ x = _fix_real_lt_zero(x) p = _fix_int_lt_zero(p) return nx.power(x, p) def arccos(x): """ Compute the inverse cosine of x. Return the "principal value" (for a description of this, see `numpy.arccos`) of the inverse cosine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[0, \\pi]`. Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose arccos is (are) required. Returns ------- out : ndarray or scalar The inverse cosine(s) of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.arccos Notes ----- For an arccos() that returns ``NAN`` when real `x` is not in the interval ``[-1,1]``, use `numpy.arccos`. Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arccos(1) # a scalar is returned 0.0 >>> np.emath.arccos([1,2]) array([ 0.-0.j , 0.+1.317j]) """ x = _fix_real_abs_gt_1(x) return nx.arccos(x) def arcsin(x): """ Compute the inverse sine of x. Return the "principal value" (for a description of this, see `numpy.arcsin`) of the inverse sine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[-\\pi/2, \\pi/2]`. Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose arcsin is (are) required. Returns ------- out : ndarray or scalar The inverse sine(s) of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.arcsin Notes ----- For an arcsin() that returns ``NAN`` when real `x` is not in the interval ``[-1,1]``, use `numpy.arcsin`. Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arcsin(0) 0.0 >>> np.emath.arcsin([0,1]) array([ 0. , 1.5708]) """ x = _fix_real_abs_gt_1(x) return nx.arcsin(x) def arctanh(x): """ Compute the inverse hyperbolic tangent of `x`. Return the "principal value" (for a description of this, see `numpy.arctanh`) of `arctanh(x)`. For real `x` such that `abs(x) < 1`, this is a real number. If `abs(x) > 1`, or if `x` is complex, the result is complex. Finally, `x = 1` returns``inf`` and `x=-1` returns ``-inf``. Parameters ---------- x : array_like The value(s) whose arctanh is (are) required. Returns ------- out : ndarray or scalar The inverse hyperbolic tangent(s) of the `x` value(s). If `x` was a scalar so is `out`, otherwise an array is returned. See Also -------- numpy.arctanh Notes ----- For an arctanh() that returns ``NAN`` when real `x` is not in the interval ``(-1,1)``, use `numpy.arctanh` (this latter, however, does return +/-inf for `x = +/-1`). Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arctanh(np.matrix(np.eye(2))) array([[ Inf, 0.], [ 0., Inf]]) >>> np.emath.arctanh([1j]) array([ 0.+0.7854j]) """ x = _fix_real_abs_gt_1(x) return nx.arctanh(x)
bsd-3-clause
camradal/ansible
lib/ansible/plugins/action/group_by.py
130
1556
# Copyright 2012, Jeroen Hoekx <jeroen@hoekx.be> # # 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/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action import ActionBase class ActionModule(ActionBase): ''' Create inventory groups based on variables ''' ### We need to be able to modify the inventory TRANSFERS_FILES = False def run(self, tmp=None, task_vars=None): if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) if 'key' not in self._task.args: result['failed'] = True result['msg'] = "the 'key' param is required when using group_by" return result group_name = self._task.args.get('key') group_name = group_name.replace(' ','-') result['changed'] = False result['add_group'] = group_name return result
gpl-3.0
mbuesch/toprammer
libtoprammer/chips/microchip8/pic12f629dip8.py
1
2446
""" # TOP2049 Open Source programming suite # # Microchip PIC12F629 DIP8 # # Copyright (c) 2013 Pavel Stemberk <stemberk@gmail.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 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ from .microchip8_splittedPMarea import * class Chip_Pic12F629dip8(microchip8_splittedPMarea): voltageVDD = 5 voltageVPP = 9 userIDLocationSize = 4 hasEEPROM = True CMD_BEGIN_INTERNALLY_TIMED_PROGRAMMING = 0x08 delayTinternalProgPM = 0.002 delayTinternalProgDM = 0.005 def __init__(self): microchip8_splittedPMarea.__init__(self, chipPackage="DIP8", chipPinVCC=1, chipPinsVPP=4, chipPinGND=8, signature=b"\xCB\x0F", flashPageSize=0x400, # 1024 words flashPages=1, eepromPageSize=128, eepromPages=1, fuseBytes=2 ) self.configWordAddr = 0x2007 self.osccalAddr = self.flashPageSize - 1 fuseDesc = ( BitDescription(0, "FOSC[0], 0=LP, 100=INTOSC"), BitDescription(1, "FOSC[1]"), BitDescription(2, "FOSC[2]"), BitDescription(3, "WDTE, 0=WDT disabled, 1=WDT enabled"), BitDescription(4, "nPWRTE"), BitDescription(5, "MCLRE"), BitDescription(6, "BODEN, 0=BOD disabled"), BitDescription(7, "nCP 1=program memory code protection is disabled"), BitDescription(8, "nCPD, 1=data memory code protection is disabled"), BitDescription(9, "Unused"), BitDescription(10, "Unused"), BitDescription(11, "Unused"), BitDescription(12, "BG[0], Band Gap Calibration bits, 00 = Lowest band gap voltage"), BitDescription(13, "BG[1]"), ) ChipDescription( Chip_Pic12F629dip8, bitfile="microchip01dip8", chipID="pic12F629dip8", runtimeID=(0xDE02, 0x01), chipVendors="Microchip", description="PIC12F629, PIC12F675", packages=(("DIP8", ""),), fuseDesc=fuseDesc, maintainer="Pavel Stemberk <stemberk@gmail.com>", )
gpl-2.0
Johnzero/OE7
openerp/addons-modules/survey/report/survey_analysis_report.py
15
28564
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp import pooler, tools from openerp.report import report_sxw from openerp.report.interface import report_rml from openerp.tools import to_xml class survey_analysis(report_rml): def create(self, cr, uid, ids, datas, context): surv_obj = pooler.get_pool(cr.dbname).get('survey') user_obj = pooler.get_pool(cr.dbname).get('res.users') rml_obj=report_sxw.rml_parse(cr, uid, surv_obj._name,context) company=user_obj.browse(cr,uid,[uid],context)[0].company_id rml ="""<document filename="Survey Analysis Report.pdf"> <template pageSize="(595.0,842.0)" title="Survey Analysis" author="OpenERP S.A.(sales@openerp.com)" allowSplitting="20"> <pageTemplate> <frame id="first" x1="1.3cm" y1="1.5cm" width="18.4cm" height="26.5cm"/> <pageGraphics> <fill color="black"/> <stroke color="black"/> <setFont name="DejaVu Sans" size="8"/> <drawString x="1.3cm" y="28.3cm"> """+to_xml(rml_obj.formatLang(time.strftime("%Y-%m-%d %H:%M:%S"),date_time=True))+"""</drawString> <setFont name="DejaVu Sans Bold" size="10"/> <drawString x="9.8cm" y="28.3cm">"""+ to_xml(company.name) +"""</drawString> <stroke color="#000000"/> <lines>1.3cm 28.1cm 20cm 28.1cm</lines> </pageGraphics> </pageTemplate> </template> <stylesheet> <blockTableStyle id="Table1"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6"/> </blockTableStyle> <blockTableStyle id="Table2"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table3"> <blockAlignment value="LEFT"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="1,0" stop="2,-1"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table4"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/> </blockTableStyle> <blockTableStyle id="Table5"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/> </blockTableStyle> <blockTableStyle id="Table_heading"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBEFORE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEABOVE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="Table_head_2"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBEFORE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEABOVE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> </blockTableStyle> <initialize> <paraStyle name="all" alignment="justify"/> </initialize> <paraStyle name="answer_right" alignment="RIGHT" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="Standard1" fontName="helvetica-bold" alignment="RIGHT" fontSize="09.0"/> <paraStyle name="Standard" alignment="LEFT" fontName="Helvetica-Bold" fontSize="11.0"/> <paraStyle name="header1" fontName="Helvetica" fontSize="11.0"/> <paraStyle name="response" fontName="Helvetica-oblique" fontSize="9.5"/> <paraStyle name="response-bold" fontName="Helvetica-bold" fontSize="9" alignment="RIGHT" /> <paraStyle name="page" fontName="helvetica" fontSize="11.0" leftIndent="0.0"/> <paraStyle name="question" fontName="helvetica-boldoblique" fontSize="10.0" leftIndent="3.0"/> <paraStyle name="answer_bold" fontName="Helvetica-Bold" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="answer" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="Title" fontName="helvetica" fontSize="20.0" leading="15" spaceBefore="6.0" spaceAfter="6.0" alignment="CENTER"/> <paraStyle name="terp_tblheader_General_Centre" fontName="Helvetica-Bold" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_default_Centre_8" fontName="Helvetica" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_Center_heading" fontName="Helvetica-bold" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/> </stylesheet> <images/> """ if datas.has_key('form') and datas['form']['survey_ids']: ids = datas['form']['survey_ids'] for survey in surv_obj.browse(cr, uid, ids): rml += """<story> <para style="Title">Answers Summary</para> <para style="Standard"><font></font></para> <para style="P2"> <font color="white"> </font> </para> <blockTable colWidths="280.0,100.0,120.0" style="Table_heading"> <tr> <td> <para style="terp_tblheader_General_Centre">Survey Title </para> </td> <td> <para style="terp_tblheader_General_Centre">Total Started Survey </para> </td> <td> <para style="terp_tblheader_General_Centre">Total Completed Survey </para> </td> </tr> </blockTable> <blockTable colWidths="280.0,100.0,120.0" style="Table_head_2"> <tr> <td> <para style="terp_default_Centre_8">""" + to_xml(tools.ustr(survey.title)) + """</para> </td> <td> <para style="terp_default_Centre_8">""" + str(survey.tot_start_survey) + """</para> </td> <td> <para style="terp_default_Centre_8">""" + str(survey.tot_comp_survey) + """</para> </td> </tr> </blockTable> <para style="P2"> <font color="white"> </font> </para>""" for page in survey.page_ids: rml += """ <blockTable colWidths="500" style="Table4"> <tr> <td><para style="page">Page :- """ + to_xml(tools.ustr(page.title)) + """</para></td> </tr> </blockTable>""" for que in page.question_ids: rml +="""<blockTable colWidths="500" style="Table5"> <tr> <td><para style="question">""" + to_xml(tools.ustr(que.question)) + """</para></td> </tr> </blockTable>""" cols_widhts = [] if que.type in ['matrix_of_choices_only_one_ans','matrix_of_choices_only_multi_ans']: cols_widhts.append(200) for col in range(0, len(que.column_heading_ids) + 1): cols_widhts.append(float(300 / (len(que.column_heading_ids) + 1))) colWidths = ",".join(map(tools.ustr, cols_widhts)) matrix_ans = [(0,'')] for col in que.column_heading_ids: if col.title not in matrix_ans: matrix_ans.append((col.id,col.title)) rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>""" for mat_col in range(0, len(matrix_ans)): rml+="""<td><para style="response">""" + to_xml(tools.ustr(matrix_ans[mat_col][1])) + """</para></td>""" rml += """<td><para style="response-bold">Answer Count</para></td> </tr>""" last_col = cols_widhts[-1] for ans in que.answer_choice_ids: rml += """<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>""" cr.execute("select count(id) from survey_response_answer sra where sra.answer_id = %s", (ans.id,)) tot_res = cr.fetchone()[0] cr.execute("select count(id) ,sra.column_id from survey_response_answer sra where sra.answer_id=%s group by sra.column_id", (ans.id,)) calc_res = cr.dictfetchall() for mat_col in range(1, len(matrix_ans)): percantage = 0.0 cal_count = 0 for cal in calc_res: if cal['column_id'] == matrix_ans[mat_col][0]: cal_count = cal['count'] if tot_res: percantage = round(float(cal_count)*100 / tot_res,2) if percantage: rml += """<td color="#FFF435"><para style="answer_bold">""" + tools.ustr(percantage) +"% (" + tools.ustr(cal_count) + """)</para></td>""" else: rml += """<td color="#FFF435"><para style="answer">""" + tools.ustr(percantage) +"% (" + tools.ustr(cal_count) + """)</para></td>""" rml += """<td><para style="answer_right">""" + tools.ustr(tot_res) + """</para></td> </tr>""" rml += """</blockTable>""" if que.is_comment_require: cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''",(que.id,)) tot_res = cr.fetchone()[0] rml += """<blockTable colWidths=" """+ str(500 - last_col) +"," + str(last_col) + """ " style="Table1"><tr><td><para style="answer_right">""" + to_xml(tools.ustr(que.comment_label)) + """</para></td> <td><para style="answer">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>""" elif que.type in['multiple_choice_only_one_ans', 'multiple_choice_multiple_ans', 'multiple_textboxes','date_and_time','date','multiple_textboxes_diff_type']: rml += """<blockTable colWidths="240.0,210,50.0" style="Table1">""" rml += """ <tr> <td> <para style="Standard"> </para></td> <td> <para style="terp_default_Center_heading">Answer Percentage</para></td> <td> <para style="response-bold">Answer Count</para></td> </tr>""" for ans in que.answer_choice_ids: progress = ans.average * 7 / 100 rml += """<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td> <td> <illustration> <stroke color="lightslategray"/> <rect x="0.1cm" y="-0.45cm" width="7.2 cm" height="0.5cm" fill="no" stroke="yes" round="0.1cm"/> """ if progress: rml += """<fill color="lightsteelblue"/> <rect x="0.2cm" y="-0.35cm" width='""" + tools.ustr(str(float(progress)) +'cm') + """' height="0.3cm" fill="yes" stroke="no" round="0.1cm"/>""" rml += """ <fill color="black"/> <setFont name="Helvetica" size="9"/> <drawString x="3.2cm" y="-0.30cm">""" + tools.ustr(ans.average) + """%</drawString></illustration> </td> <td><para style="answer_right">""" + tools.ustr(ans.response) + """</para></td></tr>""" rml += """</blockTable>""" if que.is_comment_require: # if que.make_comment_field: # cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''", (que.id,)) # tot_res = cr.fetchone()[0] # tot_avg = 0.00 # if que.tot_resp: # tot_avg = round(float(tot_res * 100)/ que.tot_resp,2) # rml+="""<blockTable colWidths="280.0,120,100.0" style="Table1"><tr><td><para style="answer">""" +to_xml(tools.ustr(que.comment_label)) + """</para></td> # <td><para style="answer">""" + str(tot_avg) + """%</para></td> # <td><para style="answer">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>""" # else: cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''", (que.id,)) tot_res = cr.fetchone()[0] rml += """<blockTable colWidths="450.0,50.0" style="Table1"><tr><td><para style="answer_right">""" + to_xml(tools.ustr(que.comment_label)) + """</para></td> <td><para style="answer_right">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>""" elif que.type in['single_textbox']: cr.execute("select count(id) from survey_response_line where question_id = %s and single_text!=''",(que.id,)) rml += """<blockTable colWidths="400.0,100.0" style="Table1"> <tr> <td> <para style="Standard"> </para></td> <td> <para style="response-bold">Answer Count</para></td> </tr> <tr><td><para style="answer"></para></td> <td><para style="answer_right">""" + tools.ustr(cr.fetchone()[0]) + """ </para></td></tr> </blockTable>""" elif que.type in['comment']: cr.execute("select count(id) from survey_response_line where question_id = %s and comment !=''", (que.id,)) rml += """<blockTable colWidths="400.0,100.0" style="Table1"> <tr> <td> <para style="Standard"> </para></td> <td> <para style="response-bold">Answer Count</para></td> </tr> <tr><td><para style="answer"></para></td> <td><para style="answer_right">""" + tools.ustr(cr.fetchone()[0]) + """ </para></td></tr> </blockTable>""" elif que.type in['rating_scale']: cols_widhts.append(200) for col in range(0,len(que.column_heading_ids) + 2): cols_widhts.append(float(300 / (len(que.column_heading_ids) + 2))) colWidths = ",".join(map(tools.ustr, cols_widhts)) matrix_ans = [(0,'')] for col in que.column_heading_ids: if col.title not in matrix_ans: matrix_ans.append((col.id,col.title)) rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>""" for mat_col in range(0,len(matrix_ans)): rml += """<td><para style="response">""" + to_xml(tools.ustr(matrix_ans[mat_col][1])) + """</para></td>""" rml += """<td><para style="response-bold">Rating Average</para></td> <td><para style="response-bold">Answer Count</para></td> </tr>""" for ans in que.answer_choice_ids: rml += """<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>""" res_count = 0 rating_weight_sum = 0 for mat_col in range(1, len(matrix_ans)): cr.execute("select count(sra.answer_id) from survey_response_line sr, survey_response_answer sra\ where sr.id = sra.response_id and sra.answer_id = %s and sra.column_id ='%s'", (ans.id,matrix_ans[mat_col][0])) tot_res = cr.fetchone()[0] cr.execute("select count(sra.answer_id),sqc.rating_weight from survey_response_line sr, survey_response_answer sra ,\ survey_question_column_heading sqc where sr.id = sra.response_id and \ sqc.question_id = sr.question_id and sra.answer_id = %s and sqc.title ='%s'\ + group by sra.answer_id,sqc.rating_weight", (ans.id,matrix_ans[mat_col][1])) col_weight = cr.fetchone() if not col_weight: col_weight= (0,0) elif not col_weight[1]: col_weight = (col_weight[0],0) res_count = col_weight[0] if tot_res and res_count: rating_weight_sum += int(col_weight[1]) * tot_res tot_per = round((float(tot_res) * 100) / int(res_count), 2) else: tot_per = 0.0 if tot_res: rml += """<td><para style="answer_bold">""" + tools.ustr(tot_per) + "%(" + tools.ustr(tot_res) + """)</para></td>""" else: rml += """<td><para style="answer">""" + tools.ustr(tot_per)+"%(" + tools.ustr(tot_res) + """)</para></td>""" percantage = 0.00 if res_count: percantage = round((float(rating_weight_sum)/res_count), 2) rml += """<td><para style="answer_right">""" + tools.ustr(percantage) + """</para></td> <td><para style="answer_right">""" + tools.ustr(res_count) + """</para></td></tr>""" rml += """</blockTable>""" elif que.type in['matrix_of_drop_down_menus']: for column in que.column_heading_ids: rml += """<blockTable colWidths="500" style="Table1"><tr> <td><para style="answer">""" + to_xml(tools.ustr(column.title)) + """</para></td></tr></blockTable>""" menu_choices = column.menu_choice.split('\n') cols_widhts = [] cols_widhts.append(200) for col in range(0, len(menu_choices) + 1): cols_widhts.append(float(300 / (len(menu_choices) + 1))) colWidths = ",".join(map(tools.ustr, cols_widhts)) rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr> <td><para style="response"></para></td>""" for menu in menu_choices: rml += """<td><para style="response">""" + to_xml(tools.ustr(menu)) + """</para></td>""" rml += """<td><para style="response-bold">Answer Count</para></td></tr>""" cr.execute("select count(id), sra.answer_id from survey_response_answer sra \ where sra.column_id='%s' group by sra.answer_id ", (column.id,)) res_count = cr.dictfetchall() cr.execute("select count(sra.id),sra.value_choice, sra.answer_id, sra.column_id from survey_response_answer sra \ where sra.column_id='%s' group by sra.value_choice ,sra.answer_id, sra.column_id", (column.id,)) calc_percantage = cr.dictfetchall() for ans in que.answer_choice_ids: rml += """<tr><td><para style="answer_right">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>""" for mat_col in range(0, len(menu_choices)): calc = 0 response = 0 for res in res_count: if res['answer_id'] == ans.id: response = res['count'] for per in calc_percantage: if ans.id == per['answer_id'] and menu_choices[mat_col] == per['value_choice']: calc = per['count'] percantage = 0.00 if calc and response: percantage = round((float(calc)* 100) / response,2) if calc: rml += """<td><para style="answer_bold">""" +tools.ustr(percantage)+"% (" + tools.ustr(calc) + """)</para></td>""" else: rml += """<td><para style="answer">""" +tools.ustr(percantage)+"% (" + tools.ustr(calc) + """)</para></td>""" response = 0 for res in res_count: if res['answer_id'] == ans.id: response = res['count'] rml += """<td><para style="answer_right">""" + tools.ustr(response) + """</para></td></tr>""" rml += """</blockTable>""" elif que.type in['numerical_textboxes']: rml += """<blockTable colWidths="240.0,20,100.0,70,70.0" style="Table1"> <tr> <td> <para style="Standard"> </para></td> <td> <para style="Standard"> </para></td> <td> <para style="response">Answer Average</para></td> <td> <para style="response">Answer Total</para></td> <td> <para style="response-bold">Answer Count</para></td> </tr>""" for ans in que.answer_choice_ids: cr.execute("select answer from survey_response_answer where answer_id=%s group by answer", (ans.id,)) tot_res = cr.dictfetchall() total = 0 for tot in tot_res: total += int(tot['answer']) per = 0.00 if len(tot_res): per = round((float(total) / len(tot_res)),2) rml+="""<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td> <td> <para style="Standard"> </para></td> <td> <para style="answer">""" + tools.ustr(per) +"""</para></td> <td><para style="answer">""" + tools.ustr(total) + """</para></td> <td><para style="answer_right">""" + tools.ustr(len(tot_res)) + """</para></td></tr>""" rml+="""</blockTable>""" rml +="""<blockTable colWidths="300,100,100.0" style="Table3"> <tr> <td><para style="Standard1"></para></td> <td><para style="Standard1">Answered Question</para></td> <td><para style="Standard1">""" + tools.ustr(que.tot_resp) + """</para></td> </tr> <tr> <td><para style="Standard1"></para></td> <td><para style="Standard1">Skipped Question</para></td> <td><para style="Standard1">""" + tools.ustr(survey.tot_start_survey - que.tot_resp) + """</para></td> </tr> </blockTable>""" rml += """</story>""" rml += """</document>""" report_type = datas.get('report_type', 'pdf') create_doc = self.generators[report_type] self.internal_header=True pdf = create_doc(rml, title=self.title) return (pdf, report_type) survey_analysis('report.survey.analysis', 'survey','','') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
liosha2007/temporary-groupdocs-python3-sdk
groupdocs/models/CreateQuestionnaireResult.py
2
1105
#!/usr/bin/env python """ Copyright 2012 GroupDocs. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class CreateQuestionnaireResult: """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): self.swaggerTypes = { 'questionnaire_id': 'float', 'questionnaire_guid': 'str', 'adjusted_name': 'str' } self.questionnaire_id = None # float self.questionnaire_guid = None # str self.adjusted_name = None # str
apache-2.0
saddingtonbaynes/rez
src/rez/cli/search.py
2
7666
""" Search for packages. """ # these are package fields that can be printed using the --format option. # It's a hardcoded list because some fields, even though they can be printed, # aren't very useful to see here. fields = sorted(( 'pre_commands', 'tools', 'uuid', 'build_requires', 'version', 'timestamp', 'release_message', 'private_build_requires', 'revision', 'description', 'base', 'authors', 'variants', 'commands', 'name', 'changelog', 'post_commands', 'requires', 'root', 'index', 'uri', 'num_variants', 'qualified_name')) def setup_parser(parser, completions=False): types_ = ("package", "family", "variant", "auto") parser.add_argument( "-s", "--sort", action="store_true", help="print results in sorted order") parser.add_argument( "-t", "--type", default="auto", choices=types_, help="type of resource to search for. If 'auto', either packages or " "package families are searched, depending on the value of PKG") parser.add_argument( "--nl", "--no-local", dest="no_local", action="store_true", help="don't search local packages") parser.add_argument( "--validate", action="store_true", help="validate each resource that is found") parser.add_argument( "--paths", type=str, default=None, help="set package search path") parser.add_argument( "-f", "--format", type=str, default=None, help="format package output, eg --format='{qualified_name} | " "{description}'. Valid fields include: %s" % ", ".join(fields)) parser.add_argument( "--no-newlines", action="store_true", help="print newlines as '\\n' rather than actual newlines") parser.add_argument( "-l", "--latest", action="store_true", help="when searching packages, only show the latest version of each " "package") parser.add_argument( "-e", "--errors", action="store_true", help="search for packages containing errors") parser.add_argument( "--nw", "--no-warnings", dest="no_warnings", action="store_true", help="suppress warnings") parser.add_argument( "--before", type=str, help="only show packages released before the given time. Supported " "formats are: epoch time (eg 1393014494), or relative time (eg -10s, " "-5m, -0.5h, -10d)") parser.add_argument( "--after", type=str, help="only show packages released after the given time. Supported " "formats are: epoch time (eg 1393014494), or relative time (eg -10s, " "-5m, -0.5h, -10d)") PKG_action = parser.add_argument( "PKG", type=str, nargs='?', help="packages to search, glob-style patterns are supported") if completions: from rez.cli._complete_util import PackageCompleter PKG_action.completer = PackageCompleter def command(opts, parser, extra_arg_groups=None): from rez.config import config from rez.exceptions import RezError from rez.utils.formatting import get_epoch_time_from_str, expand_abbreviations from rez.utils.logging_ import print_error from rez.packages_ import iter_package_families, iter_packages from rez.vendor.version.requirement import Requirement import os.path import fnmatch import sys error_class = None if opts.debug else RezError before_time = 0 after_time = 0 if opts.before: before_time = get_epoch_time_from_str(opts.before) if opts.after: after_time = get_epoch_time_from_str(opts.after) if after_time and before_time and (after_time >= before_time): parser.error("non-overlapping --before and --after") if opts.paths is None: pkg_paths = config.nonlocal_packages_path if opts.no_local else None else: pkg_paths = (opts.paths or "").split(os.pathsep) pkg_paths = [os.path.expanduser(x) for x in pkg_paths if x] name_pattern = opts.PKG or '*' version_range = None if opts.PKG: try: req = Requirement(opts.PKG) name_pattern = req.name if not req.range.is_any(): version_range = req.range except: pass type_ = opts.type if opts.errors or (type_ == "auto" and version_range): type_ = "package" # turn some of the nastier rez-1 warnings into errors config.override("error_package_name_mismatch", True) config.override("error_version_mismatch", True) config.override("error_nonstring_version", True) if opts.no_warnings: config.override("warn_none", True) # families found = False family_names = [] families = iter_package_families(paths=pkg_paths) if opts.sort: families = sorted(families, key=lambda x: x.name) for family in families: if family.name not in family_names and \ fnmatch.fnmatch(family.name, name_pattern): family_names.append(family.name) if type_ == "auto": type_ = "package" if family.name == name_pattern else "family" if type_ == "family": print family.name found = True def _handle(e): print_error(str(e)) def _print_resource(r): if opts.validate: try: r.validate_data() except error_class as e: _handle(e) return if opts.format: txt = expand_abbreviations(opts.format, fields) lines = txt.split("\\n") for line in lines: try: line_ = r.format(line) except error_class as e: _handle(e) break if opts.no_newlines: line_ = line_.replace('\n', "\\n") print line_ else: print r.qualified_name # packages/variants if type_ in ("package", "variant"): for name in family_names: packages = iter_packages(name, version_range, paths=pkg_paths) if opts.sort or opts.latest: packages = sorted(packages, key=lambda x: x.version) if opts.latest and packages: packages = [packages[-1]] for package in packages: if ((before_time or after_time) and package.timestamp and (before_time and package.timestamp >= before_time or after_time and package.timestamp <= after_time)): continue if opts.errors: try: package.validate_data() except error_class as e: _handle(e) found = True elif type_ == "package": _print_resource(package) found = True elif type_ == "variant": try: package.validate_data() except error_class as e: _handle(e) continue try: for variant in package.iter_variants(): _print_resource(variant) found = True except error_class as e: _handle(e) continue if not found: if opts.errors: print "no erroneous packages found" else: print "no matches found" sys.exit(1)
gpl-3.0
subtek/axiomk
scripts/tracing/draw_functrace.py
14676
3560
#!/usr/bin/python """ Copyright 2008 (c) Frederic Weisbecker <fweisbec@gmail.com> Licensed under the terms of the GNU GPL License version 2 This script parses a trace provided by the function tracer in kernel/trace/trace_functions.c The resulted trace is processed into a tree to produce a more human view of the call stack by drawing textual but hierarchical tree of calls. Only the functions's names and the the call time are provided. Usage: Be sure that you have CONFIG_FUNCTION_TRACER # mount -t debugfs nodev /sys/kernel/debug # echo function > /sys/kernel/debug/tracing/current_tracer $ cat /sys/kernel/debug/tracing/trace_pipe > ~/raw_trace_func Wait some times but not too much, the script is a bit slow. Break the pipe (Ctrl + Z) $ scripts/draw_functrace.py < raw_trace_func > draw_functrace Then you have your drawn trace in draw_functrace """ import sys, re class CallTree: """ This class provides a tree representation of the functions call stack. If a function has no parent in the kernel (interrupt, syscall, kernel thread...) then it is attached to a virtual parent called ROOT. """ ROOT = None def __init__(self, func, time = None, parent = None): self._func = func self._time = time if parent is None: self._parent = CallTree.ROOT else: self._parent = parent self._children = [] def calls(self, func, calltime): """ If a function calls another one, call this method to insert it into the tree at the appropriate place. @return: A reference to the newly created child node. """ child = CallTree(func, calltime, self) self._children.append(child) return child def getParent(self, func): """ Retrieve the last parent of the current node that has the name given by func. If this function is not on a parent, then create it as new child of root @return: A reference to the parent. """ tree = self while tree != CallTree.ROOT and tree._func != func: tree = tree._parent if tree == CallTree.ROOT: child = CallTree.ROOT.calls(func, None) return child return tree def __repr__(self): return self.__toString("", True) def __toString(self, branch, lastChild): if self._time is not None: s = "%s----%s (%s)\n" % (branch, self._func, self._time) else: s = "%s----%s\n" % (branch, self._func) i = 0 if lastChild: branch = branch[:-1] + " " while i < len(self._children): if i != len(self._children) - 1: s += "%s" % self._children[i].__toString(branch +\ " |", False) else: s += "%s" % self._children[i].__toString(branch +\ " |", True) i += 1 return s class BrokenLineException(Exception): """If the last line is not complete because of the pipe breakage, we want to stop the processing and ignore this line. """ pass class CommentLineException(Exception): """ If the line is a comment (as in the beginning of the trace file), just ignore it. """ pass def parseLine(line): line = line.strip() if line.startswith("#"): raise CommentLineException m = re.match("[^]]+?\\] +([0-9.]+): (\\w+) <-(\\w+)", line) if m is None: raise BrokenLineException return (m.group(1), m.group(2), m.group(3)) def main(): CallTree.ROOT = CallTree("Root (Nowhere)", None, None) tree = CallTree.ROOT for line in sys.stdin: try: calltime, callee, caller = parseLine(line) except BrokenLineException: break except CommentLineException: continue tree = tree.getParent(caller) tree = tree.calls(callee, calltime) print CallTree.ROOT if __name__ == "__main__": main()
gpl-2.0
eduNEXT/edunext-platform
common/djangoapps/student/management/tests/test_transfer_students.py
3
6331
""" Tests the transfer student management command """ import unittest import ddt from django.conf import settings from django.core.management import call_command from mock import call, patch from opaque_keys.edx import locator from six import text_type from course_modes.models import CourseMode from shoppingcart.models import CertificateItem, Order from student.models import ( EVENT_NAME_ENROLLMENT_ACTIVATED, EVENT_NAME_ENROLLMENT_DEACTIVATED, EVENT_NAME_ENROLLMENT_MODE_CHANGED, CourseEnrollment ) from student.signals import UNENROLL_DONE from student.tests.factories import UserFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') @ddt.ddt class TestTransferStudents(ModuleStoreTestCase): """ Tests for transferring students between courses. """ PASSWORD = 'test' signal_fired = False def setUp(self, **kwargs): """ Connect a stub receiver, and analytics event tracking. """ super(TestTransferStudents, self).setUp() UNENROLL_DONE.connect(self.assert_unenroll_signal) patcher = patch('student.models.tracker') self.mock_tracker = patcher.start() self.addCleanup(patcher.stop) self.addCleanup(UNENROLL_DONE.disconnect, self.assert_unenroll_signal) def assert_unenroll_signal(self, skip_refund=False, **kwargs): # pylint: disable=unused-argument """ Signal Receiver stub for testing that the unenroll signal was fired. """ self.assertFalse(self.signal_fired) self.assertTrue(skip_refund) self.signal_fired = True def test_transfer_students(self): """ Verify the transfer student command works as intended. """ student = UserFactory.create() student.set_password(self.PASSWORD) student.save() mode = 'verified' # Original Course original_course_location = locator.CourseLocator('Org0', 'Course0', 'Run0') course = self._create_course(original_course_location) # Enroll the student in 'verified' CourseEnrollment.enroll(student, course.id, mode='verified') # Create and purchase a verified cert for the original course. self._create_and_purchase_verified(student, course.id) # New Course 1 course_location_one = locator.CourseLocator('Org1', 'Course1', 'Run1') new_course_one = self._create_course(course_location_one) # New Course 2 course_location_two = locator.CourseLocator('Org2', 'Course2', 'Run2') new_course_two = self._create_course(course_location_two) original_key = text_type(course.id) new_key_one = text_type(new_course_one.id) new_key_two = text_type(new_course_two.id) # Run the actual management command call_command( 'transfer_students', '--from', original_key, '--to', new_key_one, new_key_two, ) self.assertTrue(self.signal_fired) # Confirm the analytics event was emitted. self.mock_tracker.emit.assert_has_calls( [ call( EVENT_NAME_ENROLLMENT_ACTIVATED, {'course_id': original_key, 'user_id': student.id, 'mode': mode} ), call( EVENT_NAME_ENROLLMENT_MODE_CHANGED, {'course_id': original_key, 'user_id': student.id, 'mode': mode} ), call( EVENT_NAME_ENROLLMENT_DEACTIVATED, {'course_id': original_key, 'user_id': student.id, 'mode': mode} ), call( EVENT_NAME_ENROLLMENT_ACTIVATED, {'course_id': new_key_one, 'user_id': student.id, 'mode': mode} ), call( EVENT_NAME_ENROLLMENT_MODE_CHANGED, {'course_id': new_key_one, 'user_id': student.id, 'mode': mode} ), call( EVENT_NAME_ENROLLMENT_ACTIVATED, {'course_id': new_key_two, 'user_id': student.id, 'mode': mode} ), call( EVENT_NAME_ENROLLMENT_MODE_CHANGED, {'course_id': new_key_two, 'user_id': student.id, 'mode': mode} ) ] ) self.mock_tracker.reset_mock() # Confirm the enrollment mode is verified on the new courses, and enrollment is enabled as appropriate. self.assertEqual((mode, False), CourseEnrollment.enrollment_mode_for_user(student, course.id)) self.assertEqual((mode, True), CourseEnrollment.enrollment_mode_for_user(student, new_course_one.id)) self.assertEqual((mode, True), CourseEnrollment.enrollment_mode_for_user(student, new_course_two.id)) # Confirm the student has not be refunded. target_certs = CertificateItem.objects.filter( course_id=course.id, user_id=student, status='purchased', mode=mode ) self.assertTrue(target_certs[0]) self.assertFalse(target_certs[0].refund_requested_time) self.assertEqual(target_certs[0].order.status, 'purchased') def _create_course(self, course_location): """ Creates a course """ return CourseFactory.create( org=course_location.org, number=course_location.course, run=course_location.run ) def _create_and_purchase_verified(self, student, course_id): """ Creates a verified mode for the course and purchases it for the student. """ course_mode = CourseMode(course_id=course_id, mode_slug='verified', mode_display_name='verified cert', min_price=50) course_mode.save() # When there is no expiration date on a verified mode, the user can always get a refund cart = Order.get_cart_for_user(user=student) CertificateItem.add_to_order(cart, course_id, 50, 'verified') cart.purchase()
agpl-3.0
prculley/gramps
gramps/plugins/view/repoview.py
4
10108
# Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2001-2006 Donald N. Allingham # Copyright (C) 2008 Gary Burton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Repository View """ #------------------------------------------------------------------------- # # GTK/Gnome modules # #------------------------------------------------------------------------- from gi.repository import Gtk #------------------------------------------------------------------------- # # gramps modules # #------------------------------------------------------------------------- from gramps.gen.lib import Repository from gramps.gui.views.listview import ListView, TEXT, MARKUP, ICON from gramps.gui.views.treemodels import RepositoryModel from gramps.gui.views.bookmarks import RepoBookmarks from gramps.gen.errors import WindowActiveError from gramps.gen.config import config from gramps.gui.editors import EditRepository, DeleteRepositoryQuery from gramps.gui.ddtargets import DdTargets from gramps.gui.dialog import ErrorDialog from gramps.gui.filters.sidebar import RepoSidebarFilter from gramps.gui.merge import MergeRepository from gramps.gen.plug import CATEGORY_QR_REPOSITORY #------------------------------------------------------------------------- # # internationalization # #------------------------------------------------------------------------- from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # # RepositoryView # #------------------------------------------------------------------------- class RepositoryView(ListView): """ repository listview class """ COL_NAME = 0 COL_ID = 1 COL_TYPE = 2 COL_URL = 3 COL_STREET = 4 COL_LOCALITY = 5 COL_CITY = 6 COL_STATE = 7 COL_COUNTRY = 8 COL_ZIP = 9 COL_EMAIL = 10 COL_SURL = 11 COL_PRIV = 12 COL_TAGS = 13 COL_CHAN = 14 # column definitions COLUMNS = [ (_('Name'), TEXT, None), (_('ID'), TEXT, None), (_('Type'), TEXT, None), (_('Home URL'), TEXT, None), (_('Street'), TEXT, None), (_('Locality'), TEXT, None), (_('City'), TEXT, None), (_('State/County'), TEXT, None), (_('Country'), TEXT, None), (_('ZIP/Postal Code'), TEXT, None), (_('Email'), TEXT, None), (_('Search URL'), TEXT, None), (_('Private'), ICON, 'gramps-lock'), (_('Tags'), TEXT, None), (_('Last Changed'), TEXT, None), ] # default setting with visible columns, order of the col, and their size CONFIGSETTINGS = ( ('columns.visible', [COL_NAME, COL_ID, COL_TYPE, COL_URL, COL_STREET, ]), ('columns.rank', [COL_NAME, COL_ID, COL_TYPE, COL_URL, COL_STREET, COL_LOCALITY, COL_CITY, COL_STATE, COL_COUNTRY, COL_ZIP, COL_EMAIL, COL_SURL, COL_PRIV, COL_TAGS, COL_CHAN]), ('columns.size', [200, 75, 100, 250, 100, 100, 100, 100, 100, 100, 100, 100, 40, 100, 100]) ) ADD_MSG = _("Add a new repository") EDIT_MSG = _("Edit the selected repository") DEL_MSG = _("Delete the selected repository") MERGE_MSG = _("Merge the selected repositories") FILTER_TYPE = "Repository" QR_CATEGORY = CATEGORY_QR_REPOSITORY def __init__(self, pdata, dbstate, uistate, nav_group=0): signal_map = { 'repository-add' : self.row_add, 'repository-update' : self.row_update, 'repository-delete' : self.row_delete, 'repository-rebuild' : self.object_build, } ListView.__init__( self, _('Repositories'), pdata, dbstate, uistate, RepositoryModel, signal_map, RepoBookmarks, nav_group, multiple=True, filter_class=RepoSidebarFilter) self.func_list.update({ '<PRIMARY>J' : self.jump, '<PRIMARY>BackSpace' : self.key_delete, }) self.additional_uis.append(self.additional_ui()) def navigation_type(self): return 'Repository' def drag_info(self): return DdTargets.REPO_LINK def define_actions(self): ListView.define_actions(self) self._add_action('FilterEdit', None, _('Repository Filter Editor'), callback=self.filter_editor,) self._add_action('QuickReport', None, _("Quick View"), None, None, None) def get_stock(self): return 'gramps-repository' def additional_ui(self): return '''<ui> <menubar name="MenuBar"> <menu action="FileMenu"> <placeholder name="LocalExport"> <menuitem action="ExportTab"/> </placeholder> </menu> <menu action="BookMenu"> <placeholder name="AddEditBook"> <menuitem action="AddBook"/> <menuitem action="EditBook"/> </placeholder> </menu> <menu action="GoMenu"> <placeholder name="CommonGo"> <menuitem action="Back"/> <menuitem action="Forward"/> <separator/> </placeholder> </menu> <menu action="EditMenu"> <placeholder name="CommonEdit"> <menuitem action="Add"/> <menuitem action="Edit"/> <menuitem action="Remove"/> <menuitem action="Merge"/> </placeholder> <menuitem action="FilterEdit"/> </menu> </menubar> <toolbar name="ToolBar"> <placeholder name="CommonNavigation"> <toolitem action="Back"/> <toolitem action="Forward"/> </placeholder> <placeholder name="CommonEdit"> <toolitem action="Add"/> <toolitem action="Edit"/> <toolitem action="Remove"/> <toolitem action="Merge"/> </placeholder> </toolbar> <popup name="Popup"> <menuitem action="Back"/> <menuitem action="Forward"/> <separator/> <menuitem action="Add"/> <menuitem action="Edit"/> <menuitem action="Remove"/> <menuitem action="Merge"/> <separator/> <menu name="QuickReport" action="QuickReport"/> </popup> </ui>''' def add(self, obj): EditRepository(self.dbstate, self.uistate, [], Repository()) def remove(self, obj): self.remove_selected_objects() def remove_object_from_handle(self, handle): source_list = [ item[1] for item in self.dbstate.db.find_backlink_handles(handle, ['Source'])] object = self.dbstate.db.get_repository_from_handle(handle) query = DeleteRepositoryQuery(self.dbstate, self.uistate, object, source_list) is_used = len(source_list) > 0 return (query, is_used, object) def edit(self, obj): for handle in self.selected_handles(): repos = self.dbstate.db.get_repository_from_handle(handle) try: EditRepository(self.dbstate, self.uistate, [], repos) except WindowActiveError: pass def merge(self, obj): """ Merge the selected repositories. """ mlist = self.selected_handles() if len(mlist) != 2: msg = _("Cannot merge repositories.") msg2 = _("Exactly two repositories must be selected to perform a " "merge. A second repository can be selected by holding " "down the control key while clicking on the desired " "repository.") ErrorDialog(msg, msg2, parent=self.uistate.window) else: MergeRepository(self.dbstate, self.uistate, [], mlist[0], mlist[1]) def get_handle_from_gramps_id(self, gid): obj = self.dbstate.db.get_repository_from_gramps_id(gid) if obj: return obj.get_handle() else: return None def tag_updated(self, handle_list): """ Update tagged rows when a tag color changes. """ all_links = set([]) for tag_handle in handle_list: links = set([link[1] for link in self.dbstate.db.find_backlink_handles(tag_handle, include_classes='Repository')]) all_links = all_links.union(links) self.row_update(list(all_links)) def add_tag(self, transaction, repo_handle, tag_handle): """ Add the given tag to the given repository. """ repo = self.dbstate.db.get_repository_from_handle(repo_handle) repo.add_tag(tag_handle) self.dbstate.db.commit_repository(repo, transaction) def get_default_gramplets(self): """ Define the default gramplets for the sidebar and bottombar. """ return (("Repository Filter",), ("Repository Details", "Repository Notes", "Repository Backlinks"))
gpl-2.0
emilk/sproxel
distro/common/lib/xml/etree/ElementPath.py
64
9778
# # ElementTree # $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $ # # limited xpath support for element trees # # history: # 2003-05-23 fl created # 2003-05-28 fl added support for // etc # 2003-08-27 fl fixed parsing of periods in element names # 2007-09-10 fl new selection engine # 2007-09-12 fl fixed parent selector # 2007-09-13 fl added iterfind; changed findall to return a list # 2007-11-30 fl added namespaces support # 2009-10-30 fl added child element value filter # # Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved. # # fredrik@pythonware.com # http://www.pythonware.com # # -------------------------------------------------------------------- # The ElementTree toolkit is # # Copyright (c) 1999-2009 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/psf/license for licensing details. ## # Implementation module for XPath support. There's usually no reason # to import this module directly; the <b>ElementTree</b> does this for # you, if needed. ## import re xpath_tokenizer_re = re.compile( "(" "'[^']*'|\"[^\"]*\"|" "::|" "//?|" "\.\.|" "\(\)|" "[/.*:\[\]\(\)@=])|" "((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|" "\s+" ) def xpath_tokenizer(pattern, namespaces=None): for token in xpath_tokenizer_re.findall(pattern): tag = token[1] if tag and tag[0] != "{" and ":" in tag: try: prefix, uri = tag.split(":", 1) if not namespaces: raise KeyError yield token[0], "{%s}%s" % (namespaces[prefix], uri) except KeyError: raise SyntaxError("prefix %r not found in prefix map" % prefix) else: yield token def get_parent_map(context): parent_map = context.parent_map if parent_map is None: context.parent_map = parent_map = {} for p in context.root.iter(): for e in p: parent_map[e] = p return parent_map def prepare_child(next, token): tag = token[1] def select(context, result): for elem in result: for e in elem: if e.tag == tag: yield e return select def prepare_star(next, token): def select(context, result): for elem in result: for e in elem: yield e return select def prepare_self(next, token): def select(context, result): for elem in result: yield elem return select def prepare_descendant(next, token): token = next() if token[0] == "*": tag = "*" elif not token[0]: tag = token[1] else: raise SyntaxError("invalid descendant") def select(context, result): for elem in result: for e in elem.iter(tag): if e is not elem: yield e return select def prepare_parent(next, token): def select(context, result): # FIXME: raise error if .. is applied at toplevel? parent_map = get_parent_map(context) result_map = {} for elem in result: if elem in parent_map: parent = parent_map[elem] if parent not in result_map: result_map[parent] = None yield parent return select def prepare_predicate(next, token): # FIXME: replace with real parser!!! refs: # http://effbot.org/zone/simple-iterator-parser.htm # http://javascript.crockford.com/tdop/tdop.html signature = [] predicate = [] while 1: token = next() if token[0] == "]": break if token[0] and token[0][:1] in "'\"": token = "'", token[0][1:-1] signature.append(token[0] or "-") predicate.append(token[1]) signature = "".join(signature) # use signature to determine predicate type if signature == "@-": # [@attribute] predicate key = predicate[1] def select(context, result): for elem in result: if elem.get(key) is not None: yield elem return select if signature == "@-='": # [@attribute='value'] key = predicate[1] value = predicate[-1] def select(context, result): for elem in result: if elem.get(key) == value: yield elem return select if signature == "-" and not re.match("\d+$", predicate[0]): # [tag] tag = predicate[0] def select(context, result): for elem in result: if elem.find(tag) is not None: yield elem return select if signature == "-='" and not re.match("\d+$", predicate[0]): # [tag='value'] tag = predicate[0] value = predicate[-1] def select(context, result): for elem in result: for e in elem.findall(tag): if "".join(e.itertext()) == value: yield elem break return select if signature == "-" or signature == "-()" or signature == "-()-": # [index] or [last()] or [last()-index] if signature == "-": index = int(predicate[0]) - 1 else: if predicate[0] != "last": raise SyntaxError("unsupported function") if signature == "-()-": try: index = int(predicate[2]) - 1 except ValueError: raise SyntaxError("unsupported expression") else: index = -1 def select(context, result): parent_map = get_parent_map(context) for elem in result: try: parent = parent_map[elem] # FIXME: what if the selector is "*" ? elems = list(parent.findall(elem.tag)) if elems[index] is elem: yield elem except (IndexError, KeyError): pass return select raise SyntaxError("invalid predicate") ops = { "": prepare_child, "*": prepare_star, ".": prepare_self, "..": prepare_parent, "//": prepare_descendant, "[": prepare_predicate, } _cache = {} class _SelectorContext: parent_map = None def __init__(self, root): self.root = root # -------------------------------------------------------------------- ## # Generate all matching objects. def iterfind(elem, path, namespaces=None): # compile selector pattern if path[-1:] == "/": path = path + "*" # implicit all (FIXME: keep this?) try: selector = _cache[path] except KeyError: if len(_cache) > 100: _cache.clear() if path[:1] == "/": raise SyntaxError("cannot use absolute path on element") next = iter(xpath_tokenizer(path, namespaces)).next token = next() selector = [] while 1: try: selector.append(ops[token[0]](next, token)) except StopIteration: raise SyntaxError("invalid path") try: token = next() if token[0] == "/": token = next() except StopIteration: break _cache[path] = selector # execute selector pattern result = [elem] context = _SelectorContext(elem) for select in selector: result = select(context, result) return result ## # Find first matching object. def find(elem, path, namespaces=None): try: return iterfind(elem, path, namespaces).next() except StopIteration: return None ## # Find all matching objects. def findall(elem, path, namespaces=None): return list(iterfind(elem, path, namespaces)) ## # Find text for first matching object. def findtext(elem, path, default=None, namespaces=None): try: elem = iterfind(elem, path, namespaces).next() return elem.text or "" except StopIteration: return default
bsd-3-clause
ganadist/chromium-trace
trace-viewer/third_party/pywebsocket/src/test/test_handshake_hybi.py
29
17457
#!/usr/bin/env python # # Copyright 2011, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Tests for handshake module.""" import unittest import set_sys_path # Update sys.path to locate mod_pywebsocket module. from mod_pywebsocket import common from mod_pywebsocket.handshake._base import AbortedByUserException from mod_pywebsocket.handshake._base import HandshakeException from mod_pywebsocket.handshake._base import VersionException from mod_pywebsocket.handshake.hybi import Handshaker import mock class RequestDefinition(object): """A class for holding data for constructing opening handshake strings for testing the opening handshake processor. """ def __init__(self, method, uri, headers): self.method = method self.uri = uri self.headers = headers def _create_good_request_def(): return RequestDefinition( 'GET', '/demo', {'Host': 'server.example.com', 'Upgrade': 'websocket', 'Connection': 'Upgrade', 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==', 'Sec-WebSocket-Version': '13', 'Origin': 'http://example.com'}) def _create_request(request_def): conn = mock.MockConn('') return mock.MockRequest( method=request_def.method, uri=request_def.uri, headers_in=request_def.headers, connection=conn) def _create_handshaker(request): handshaker = Handshaker(request, mock.MockDispatcher()) return handshaker class SubprotocolChoosingDispatcher(object): """A dispatcher for testing. This dispatcher sets the i-th subprotocol of requested ones to ws_protocol where i is given on construction as index argument. If index is negative, default_value will be set to ws_protocol. """ def __init__(self, index, default_value=None): self.index = index self.default_value = default_value def do_extra_handshake(self, conn_context): if self.index >= 0: conn_context.ws_protocol = conn_context.ws_requested_protocols[ self.index] else: conn_context.ws_protocol = self.default_value def transfer_data(self, conn_context): pass class HandshakeAbortedException(Exception): pass class AbortingDispatcher(object): """A dispatcher for testing. This dispatcher raises an exception in do_extra_handshake to reject the request. """ def do_extra_handshake(self, conn_context): raise HandshakeAbortedException('An exception to reject the request') def transfer_data(self, conn_context): pass class AbortedByUserDispatcher(object): """A dispatcher for testing. This dispatcher raises an AbortedByUserException in do_extra_handshake to reject the request. """ def do_extra_handshake(self, conn_context): raise AbortedByUserException('An AbortedByUserException to reject the ' 'request') def transfer_data(self, conn_context): pass _EXPECTED_RESPONSE = ( 'HTTP/1.1 101 Switching Protocols\r\n' 'Upgrade: websocket\r\n' 'Connection: Upgrade\r\n' 'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n') class HandshakerTest(unittest.TestCase): """A unittest for draft-ietf-hybi-thewebsocketprotocol-06 and later handshake processor. """ def test_do_handshake(self): request = _create_request(_create_good_request_def()) dispatcher = mock.MockDispatcher() handshaker = Handshaker(request, dispatcher) handshaker.do_handshake() self.assertTrue(dispatcher.do_extra_handshake_called) self.assertEqual( _EXPECTED_RESPONSE, request.connection.written_data()) self.assertEqual('/demo', request.ws_resource) self.assertEqual('http://example.com', request.ws_origin) self.assertEqual(None, request.ws_protocol) self.assertEqual(None, request.ws_extensions) self.assertEqual(common.VERSION_HYBI_LATEST, request.ws_version) def test_do_handshake_with_capitalized_value(self): request_def = _create_good_request_def() request_def.headers['upgrade'] = 'WEBSOCKET' request = _create_request(request_def) handshaker = _create_handshaker(request) handshaker.do_handshake() self.assertEqual( _EXPECTED_RESPONSE, request.connection.written_data()) request_def = _create_good_request_def() request_def.headers['Connection'] = 'UPGRADE' request = _create_request(request_def) handshaker = _create_handshaker(request) handshaker.do_handshake() self.assertEqual( _EXPECTED_RESPONSE, request.connection.written_data()) def test_do_handshake_with_multiple_connection_values(self): request_def = _create_good_request_def() request_def.headers['Connection'] = 'Upgrade, keep-alive, , ' request = _create_request(request_def) handshaker = _create_handshaker(request) handshaker.do_handshake() self.assertEqual( _EXPECTED_RESPONSE, request.connection.written_data()) def test_aborting_handshake(self): handshaker = Handshaker( _create_request(_create_good_request_def()), AbortingDispatcher()) # do_extra_handshake raises an exception. Check that it's not caught by # do_handshake. self.assertRaises(HandshakeAbortedException, handshaker.do_handshake) def test_do_handshake_with_protocol(self): request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Protocol'] = 'chat, superchat' request = _create_request(request_def) handshaker = Handshaker(request, SubprotocolChoosingDispatcher(0)) handshaker.do_handshake() EXPECTED_RESPONSE = ( 'HTTP/1.1 101 Switching Protocols\r\n' 'Upgrade: websocket\r\n' 'Connection: Upgrade\r\n' 'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n' 'Sec-WebSocket-Protocol: chat\r\n\r\n') self.assertEqual(EXPECTED_RESPONSE, request.connection.written_data()) self.assertEqual('chat', request.ws_protocol) def test_do_handshake_protocol_not_in_request_but_in_response(self): request_def = _create_good_request_def() request = _create_request(request_def) handshaker = Handshaker( request, SubprotocolChoosingDispatcher(-1, 'foobar')) # No request has been made but ws_protocol is set. HandshakeException # must be raised. self.assertRaises(HandshakeException, handshaker.do_handshake) def test_do_handshake_with_protocol_no_protocol_selection(self): request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Protocol'] = 'chat, superchat' request = _create_request(request_def) handshaker = _create_handshaker(request) # ws_protocol is not set. HandshakeException must be raised. self.assertRaises(HandshakeException, handshaker.do_handshake) def test_do_handshake_with_extensions(self): request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Extensions'] = ( 'deflate-stream, unknown') EXPECTED_RESPONSE = ( 'HTTP/1.1 101 Switching Protocols\r\n' 'Upgrade: websocket\r\n' 'Connection: Upgrade\r\n' 'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n' 'Sec-WebSocket-Extensions: deflate-stream\r\n\r\n') request = _create_request(request_def) handshaker = _create_handshaker(request) handshaker.do_handshake() self.assertEqual(EXPECTED_RESPONSE, request.connection.written_data()) self.assertEqual(1, len(request.ws_extensions)) extension = request.ws_extensions[0] self.assertEqual('deflate-stream', extension.name()) self.assertEqual(0, len(extension.get_parameter_names())) def test_do_handshake_with_quoted_extensions(self): request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Extensions'] = ( 'deflate-stream, , ' 'unknown; e = "mc^2"; ma="\r\n \\\rf "; pv=nrt') request = _create_request(request_def) handshaker = _create_handshaker(request) handshaker.do_handshake() self.assertEqual(2, len(request.ws_requested_extensions)) first_extension = request.ws_requested_extensions[0] self.assertEqual('deflate-stream', first_extension.name()) self.assertEqual(0, len(first_extension.get_parameter_names())) second_extension = request.ws_requested_extensions[1] self.assertEqual('unknown', second_extension.name()) self.assertEqual( ['e', 'ma', 'pv'], second_extension.get_parameter_names()) self.assertEqual('mc^2', second_extension.get_parameter_value('e')) self.assertEqual(' \rf ', second_extension.get_parameter_value('ma')) self.assertEqual('nrt', second_extension.get_parameter_value('pv')) def test_do_handshake_with_optional_headers(self): request_def = _create_good_request_def() request_def.headers['EmptyValue'] = '' request_def.headers['AKey'] = 'AValue' request = _create_request(request_def) handshaker = _create_handshaker(request) handshaker.do_handshake() self.assertEqual( 'AValue', request.headers_in['AKey']) self.assertEqual( '', request.headers_in['EmptyValue']) def test_abort_extra_handshake(self): handshaker = Handshaker( _create_request(_create_good_request_def()), AbortedByUserDispatcher()) # do_extra_handshake raises an AbortedByUserException. Check that it's # not caught by do_handshake. self.assertRaises(AbortedByUserException, handshaker.do_handshake) def test_do_handshake_with_mux_and_deflateframe(self): request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Extensions'] = ('%s, %s' % ( common.MUX_EXTENSION, common.DEFLATE_FRAME_EXTENSION)) request = _create_request(request_def) handshaker = _create_handshaker(request) handshaker.do_handshake() self.assertEqual(2, len(request.ws_extensions)) self.assertEqual(common.MUX_EXTENSION, request.ws_extensions[0].name()) self.assertEqual(common.DEFLATE_FRAME_EXTENSION, request.ws_extensions[1].name()) self.assertTrue(request.mux) self.assertEqual(0, len(request.mux_extensions)) def test_do_handshake_with_deflateframe_and_mux(self): request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Extensions'] = ('%s, %s' % ( common.DEFLATE_FRAME_EXTENSION, common.MUX_EXTENSION)) request = _create_request(request_def) handshaker = _create_handshaker(request) handshaker.do_handshake() # mux should be rejected. self.assertEqual(1, len(request.ws_extensions)) first_extension = request.ws_extensions[0] self.assertEqual(common.DEFLATE_FRAME_EXTENSION, first_extension.name()) def test_bad_requests(self): bad_cases = [ ('HTTP request', RequestDefinition( 'GET', '/demo', {'Host': 'www.google.com', 'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5;' ' en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3' ' GTB6 GTBA', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,' '*/*;q=0.8', 'Accept-Language': 'en-us,en;q=0.5', 'Accept-Encoding': 'gzip,deflate', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Keep-Alive': '300', 'Connection': 'keep-alive'}), None, True)] request_def = _create_good_request_def() request_def.method = 'POST' bad_cases.append(('Wrong method', request_def, None, True)) request_def = _create_good_request_def() del request_def.headers['Host'] bad_cases.append(('Missing Host', request_def, None, True)) request_def = _create_good_request_def() del request_def.headers['Upgrade'] bad_cases.append(('Missing Upgrade', request_def, None, True)) request_def = _create_good_request_def() request_def.headers['Upgrade'] = 'nonwebsocket' bad_cases.append(('Wrong Upgrade', request_def, None, True)) request_def = _create_good_request_def() del request_def.headers['Connection'] bad_cases.append(('Missing Connection', request_def, None, True)) request_def = _create_good_request_def() request_def.headers['Connection'] = 'Downgrade' bad_cases.append(('Wrong Connection', request_def, None, True)) request_def = _create_good_request_def() del request_def.headers['Sec-WebSocket-Key'] bad_cases.append(('Missing Sec-WebSocket-Key', request_def, 400, True)) request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Key'] = ( 'dGhlIHNhbXBsZSBub25jZQ==garbage') bad_cases.append(('Wrong Sec-WebSocket-Key (with garbage on the tail)', request_def, 400, True)) request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Key'] = 'YQ==' # BASE64 of 'a' bad_cases.append( ('Wrong Sec-WebSocket-Key (decoded value is not 16 octets long)', request_def, 400, True)) request_def = _create_good_request_def() # The last character right before == must be any of A, Q, w and g. request_def.headers['Sec-WebSocket-Key'] = ( 'AQIDBAUGBwgJCgsMDQ4PEC==') bad_cases.append( ('Wrong Sec-WebSocket-Key (padding bits are not zero)', request_def, 400, True)) request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Key'] = ( 'dGhlIHNhbXBsZSBub25jZQ==,dGhlIHNhbXBsZSBub25jZQ==') bad_cases.append( ('Wrong Sec-WebSocket-Key (multiple values)', request_def, 400, True)) request_def = _create_good_request_def() del request_def.headers['Sec-WebSocket-Version'] bad_cases.append(('Missing Sec-WebSocket-Version', request_def, None, True)) request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Version'] = '3' bad_cases.append(('Wrong Sec-WebSocket-Version', request_def, None, False)) request_def = _create_good_request_def() request_def.headers['Sec-WebSocket-Version'] = '13, 13' bad_cases.append(('Wrong Sec-WebSocket-Version (multiple values)', request_def, 400, True)) for (case_name, request_def, expected_status, expect_handshake_exception) in bad_cases: request = _create_request(request_def) handshaker = Handshaker(request, mock.MockDispatcher()) try: handshaker.do_handshake() self.fail('No exception thrown for \'%s\' case' % case_name) except HandshakeException, e: self.assertTrue(expect_handshake_exception) self.assertEqual(expected_status, e.status) except VersionException, e: self.assertFalse(expect_handshake_exception) if __name__ == '__main__': unittest.main() # vi:sts=4 sw=4 et
bsd-3-clause
nocnokneo/ninja
misc/write_fake_manifests.py
11
7551
#!/usr/bin/env python """Writes large manifest files, for manifest parser performance testing. The generated manifest files are (eerily) similar in appearance and size to the ones used in the Chromium project. Usage: python misc/write_fake_manifests.py outdir # Will run for about 5s. The program contains a hardcoded random seed, so it will generate the same output every time it runs. By changing the seed, it's easy to generate many different sets of manifest files. """ import argparse import contextlib import os import random import sys import ninja_syntax def paretoint(avg, alpha): """Returns a random integer that's avg on average, following a power law. alpha determines the shape of the power curve. alpha has to be larger than 1. The closer alpha is to 1, the higher the variation of the returned numbers.""" return int(random.paretovariate(alpha) * avg / (alpha / (alpha - 1))) # Based on http://neugierig.org/software/chromium/class-name-generator.html def moar(avg_options, p_suffix): kStart = ['render', 'web', 'browser', 'tab', 'content', 'extension', 'url', 'file', 'sync', 'content', 'http', 'profile'] kOption = ['view', 'host', 'holder', 'container', 'impl', 'ref', 'delegate', 'widget', 'proxy', 'stub', 'context', 'manager', 'master', 'watcher', 'service', 'file', 'data', 'resource', 'device', 'info', 'provider', 'internals', 'tracker', 'api', 'layer'] kOS = ['win', 'mac', 'aura', 'linux', 'android', 'unittest', 'browsertest'] num_options = min(paretoint(avg_options, alpha=4), 5) # The original allows kOption to repeat as long as no consecutive options # repeat. This version doesn't allow any option repetition. name = [random.choice(kStart)] + random.sample(kOption, num_options) if random.random() < p_suffix: name.append(random.choice(kOS)) return '_'.join(name) class GenRandom(object): def __init__(self): self.seen_names = set([None]) self.seen_defines = set([None]) def _unique_string(self, seen, avg_options=1.3, p_suffix=0.1): s = None while s in seen: s = moar(avg_options, p_suffix) seen.add(s) return s def _n_unique_strings(self, n): seen = set([None]) return [self._unique_string(seen, avg_options=3, p_suffix=0.4) for _ in xrange(n)] def target_name(self): return self._unique_string(p_suffix=0, seen=self.seen_names) def path(self): return os.path.sep.join([ self._unique_string(self.seen_names, avg_options=1, p_suffix=0) for _ in xrange(1 + paretoint(0.6, alpha=4))]) def src_obj_pairs(self, path, name): num_sources = paretoint(55, alpha=2) + 1 return [(os.path.join('..', '..', path, s + '.cc'), os.path.join('obj', path, '%s.%s.o' % (name, s))) for s in self._n_unique_strings(num_sources)] def defines(self): return [ '-DENABLE_' + self._unique_string(self.seen_defines).upper() for _ in xrange(paretoint(20, alpha=3))] LIB, EXE = 0, 1 class Target(object): def __init__(self, gen, kind): self.name = gen.target_name() self.dir_path = gen.path() self.ninja_file_path = os.path.join( 'obj', self.dir_path, self.name + '.ninja') self.src_obj_pairs = gen.src_obj_pairs(self.dir_path, self.name) if kind == LIB: self.output = os.path.join('lib' + self.name + '.a') elif kind == EXE: self.output = os.path.join(self.name) self.defines = gen.defines() self.deps = [] self.kind = kind self.has_compile_depends = random.random() < 0.4 @property def includes(self): return ['-I' + dep.dir_path for dep in self.deps] def write_target_ninja(ninja, target): compile_depends = None if target.has_compile_depends: compile_depends = os.path.join( 'obj', target.dir_path, target.name + '.stamp') ninja.build(compile_depends, 'stamp', target.src_obj_pairs[0][0]) ninja.newline() ninja.variable('defines', target.defines) if target.deps: ninja.variable('includes', target.includes) ninja.variable('cflags', ['-Wall', '-fno-rtti', '-fno-exceptions']) ninja.newline() for src, obj in target.src_obj_pairs: ninja.build(obj, 'cxx', src, implicit=compile_depends) ninja.newline() deps = [dep.output for dep in target.deps] libs = [dep.output for dep in target.deps if dep.kind == LIB] if target.kind == EXE: ninja.variable('ldflags', '-Wl,pie') ninja.variable('libs', libs) link = { LIB: 'alink', EXE: 'link'}[target.kind] ninja.build(target.output, link, [obj for _, obj in target.src_obj_pairs], implicit=deps) def write_master_ninja(master_ninja, targets): """Writes master build.ninja file, referencing all given subninjas.""" master_ninja.variable('cxx', 'c++') master_ninja.variable('ld', '$cxx') master_ninja.newline() master_ninja.pool('link_pool', depth=4) master_ninja.newline() master_ninja.rule('cxx', description='CXX $out', command='$cxx -MMD -MF $out.d $defines $includes $cflags -c $in -o $out', depfile='$out.d', deps='gcc') master_ninja.rule('alink', description='LIBTOOL-STATIC $out', command='rm -f $out && libtool -static -o $out $in') master_ninja.rule('link', description='LINK $out', pool='link_pool', command='$ld $ldflags -o $out $in $libs') master_ninja.rule('stamp', description='STAMP $out', command='touch $out') master_ninja.newline() for target in targets: master_ninja.subninja(target.ninja_file_path) master_ninja.newline() master_ninja.comment('Short names for targets.') for target in targets: if target.name != target.output: master_ninja.build(target.name, 'phony', target.output) master_ninja.newline() master_ninja.build('all', 'phony', [target.output for target in targets]) master_ninja.default('all') @contextlib.contextmanager def FileWriter(path): """Context manager for a ninja_syntax object writing to a file.""" try: os.makedirs(os.path.dirname(path)) except OSError: pass f = open(path, 'w') yield ninja_syntax.Writer(f) f.close() def random_targets(): num_targets = 800 gen = GenRandom() # N-1 static libraries, and 1 executable depending on all of them. targets = [Target(gen, LIB) for i in xrange(num_targets - 1)] for i in range(len(targets)): targets[i].deps = [t for t in targets[0:i] if random.random() < 0.05] last_target = Target(gen, EXE) last_target.deps = targets[:] last_target.src_obj_pairs = last_target.src_obj_pairs[0:10] # Trim. targets.append(last_target) return targets def main(): parser = argparse.ArgumentParser() parser.add_argument('outdir', help='output directory') args = parser.parse_args() root_dir = args.outdir random.seed(12345) targets = random_targets() for target in targets: with FileWriter(os.path.join(root_dir, target.ninja_file_path)) as n: write_target_ninja(n, target) with FileWriter(os.path.join(root_dir, 'build.ninja')) as master_ninja: master_ninja.width = 120 write_master_ninja(master_ninja, targets) if __name__ == '__main__': sys.exit(main())
apache-2.0
shrutisingala/ns-3-dev-git-limited-slow-start
src/spectrum/bindings/modulegen__gcc_LP64.py
16
539079
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.spectrum', 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', 'LOG_PREFIX_LEVEL', 'LOG_PREFIX_ALL'], 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') ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::AdhocAlohaNoackIdealPhyHelper [class] module.add_class('AdhocAlohaNoackIdealPhyHelper') ## angles.h (module 'antenna'): ns3::Angles [struct] module.add_class('Angles', import_from_module='ns.antenna') ## 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') ## 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') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## log.h (module 'core'): ns3::LogComponent [class] module.add_class('LogComponent', import_from_module='ns.core') ## mac16-address.h (module 'network'): ns3::Mac16Address [class] module.add_class('Mac16Address', import_from_module='ns.network') ## mac16-address.h (module 'network'): ns3::Mac16Address [class] root_module['ns3::Mac16Address'].implicitly_converts_to(root_module['ns3::Address']) ## 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']) ## mac64-address.h (module 'network'): ns3::Mac64Address [class] module.add_class('Mac64Address', import_from_module='ns.network') ## mac64-address.h (module 'network'): ns3::Mac64Address [class] root_module['ns3::Mac64Address'].implicitly_converts_to(root_module['ns3::Address']) ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): ns3::MicrowaveOvenSpectrumValueHelper [class] module.add_class('MicrowaveOvenSpectrumValueHelper') ## 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') ## non-copyable.h (module 'core'): ns3::NonCopyable [class] module.add_class('NonCopyable', destructor_visibility='protected', import_from_module='ns.core') ## 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']) ## log.h (module 'core'): ns3::ParameterLogger [class] module.add_class('ParameterLogger', import_from_module='ns.core') ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo [class] module.add_class('RxSpectrumModelInfo') ## 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')) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::SpectrumAnalyzerHelper [class] module.add_class('SpectrumAnalyzerHelper') ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumChannelHelper [class] module.add_class('SpectrumChannelHelper') ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumPhyHelper [class] module.add_class('SpectrumPhyHelper') ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class] module.add_class('SystemWallClockMs', import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## traced-value.h (module 'core'): ns3::TracedValue<unsigned int> [class] module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['unsigned int']) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): ns3::TvSpectrumTransmitterHelper [class] module.add_class('TvSpectrumTransmitterHelper') ## tv-spectrum-transmitter-helper.h (module 'spectrum'): ns3::TvSpectrumTransmitterHelper::Region [enumeration] module.add_enum('Region', ['REGION_NORTH_AMERICA', 'REGION_JAPAN', 'REGION_EUROPE'], outer_class=root_module['ns3::TvSpectrumTransmitterHelper']) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): ns3::TvSpectrumTransmitterHelper::Density [enumeration] module.add_enum('Density', ['DENSITY_LOW', 'DENSITY_MEDIUM', 'DENSITY_HIGH'], outer_class=root_module['ns3::TvSpectrumTransmitterHelper']) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo [class] module.add_class('TxSpectrumModelInfo') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## 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') ## waveform-generator-helper.h (module 'spectrum'): ns3::WaveformGeneratorHelper [class] module.add_class('WaveformGeneratorHelper') ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValue5MhzFactory [class] module.add_class('WifiSpectrumValue5MhzFactory', allow_subclassing=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValueHelper [class] module.add_class('WifiSpectrumValueHelper') ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel [class] module.add_class('PropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::Object']) ## propagation-loss-model.h (module 'propagation'): ns3::PropagationLossModel [class] module.add_class('PropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::Object']) ## queue.h (module 'network'): ns3::QueueBase [class] module.add_class('QueueBase', import_from_module='ns.network', parent=root_module['ns3::Object']) ## queue.h (module 'network'): ns3::QueueBase::QueueMode [enumeration] module.add_enum('QueueMode', ['QUEUE_MODE_PACKETS', 'QUEUE_MODE_BYTES'], outer_class=root_module['ns3::QueueBase'], import_from_module='ns.network') ## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel [class] module.add_class('RandomPropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationDelayModel']) ## propagation-loss-model.h (module 'propagation'): ns3::RandomPropagationLossModel [class] module.add_class('RandomPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## propagation-loss-model.h (module 'propagation'): ns3::RangePropagationLossModel [class] module.add_class('RangePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::SpectrumConverter', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SpectrumConverter>'], 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, 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, 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, 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-converter.h (module 'spectrum'): ns3::SpectrumConverter [class] module.add_class('SpectrumConverter', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >']) ## spectrum-error-model.h (module 'spectrum'): ns3::SpectrumErrorModel [class] module.add_class('SpectrumErrorModel', parent=root_module['ns3::Object']) ## spectrum-interference.h (module 'spectrum'): ns3::SpectrumInterference [class] module.add_class('SpectrumInterference', parent=root_module['ns3::Object']) ## spectrum-model.h (module 'spectrum'): ns3::SpectrumModel [class] module.add_class('SpectrumModel', 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', parent=root_module['ns3::Object']) ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::SpectrumPropagationLossModel [class] module.add_class('SpectrumPropagationLossModel', parent=root_module['ns3::Object']) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters [struct] module.add_class('SpectrumSignalParameters', 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', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumValue, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumValue> >']) ## propagation-loss-model.h (module 'propagation'): ns3::ThreeLogDistancePropagationLossModel [class] module.add_class('ThreeLogDistancePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## tv-spectrum-transmitter.h (module 'spectrum'): ns3::TvSpectrumTransmitter [class] module.add_class('TvSpectrumTransmitter', parent=root_module['ns3::SpectrumPhy']) ## tv-spectrum-transmitter.h (module 'spectrum'): ns3::TvSpectrumTransmitter::TvType [enumeration] module.add_enum('TvType', ['TVTYPE_ANALOG', 'TVTYPE_8VSB', 'TVTYPE_COFDM'], outer_class=root_module['ns3::TvSpectrumTransmitter']) ## propagation-loss-model.h (module 'propagation'): ns3::TwoRayGroundPropagationLossModel [class] module.add_class('TwoRayGroundPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## waveform-generator.h (module 'spectrum'): ns3::WaveformGenerator [class] module.add_class('WaveformGenerator', parent=root_module['ns3::SpectrumPhy']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::AlohaNoackMacHeader [class] module.add_class('AlohaNoackMacHeader', parent=root_module['ns3::Header']) ## antenna-model.h (module 'antenna'): ns3::AntennaModel [class] module.add_class('AntennaModel', import_from_module='ns.antenna', parent=root_module['ns3::Object']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## boolean.h (module 'core'): ns3::BooleanChecker [class] module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## boolean.h (module 'core'): ns3::BooleanValue [class] module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## constant-spectrum-propagation-loss.h (module 'spectrum'): ns3::ConstantSpectrumPropagationLossModel [class] module.add_class('ConstantSpectrumPropagationLossModel', parent=root_module['ns3::SpectrumPropagationLossModel']) ## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel [class] module.add_class('ConstantSpeedPropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationDelayModel']) ## 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']) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## double.h (module 'core'): ns3::DoubleValue [class] module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class] module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## enum.h (module 'core'): ns3::EnumChecker [class] module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## enum.h (module 'core'): ns3::EnumValue [class] module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class] module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class] module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## propagation-loss-model.h (module 'propagation'): ns3::FixedRssLossModel [class] module.add_class('FixedRssLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## propagation-loss-model.h (module 'propagation'): ns3::FriisPropagationLossModel [class] module.add_class('FriisPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## friis-spectrum-propagation-loss.h (module 'spectrum'): ns3::FriisSpectrumPropagationLossModel [class] module.add_class('FriisSpectrumPropagationLossModel', parent=root_module['ns3::SpectrumPropagationLossModel']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::HalfDuplexIdealPhy [class] module.add_class('HalfDuplexIdealPhy', parent=root_module['ns3::SpectrumPhy']) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::HalfDuplexIdealPhy::State [enumeration] module.add_enum('State', ['IDLE', 'TX', 'RX'], outer_class=root_module['ns3::HalfDuplexIdealPhy']) ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::HalfDuplexIdealPhySignalParameters [struct] module.add_class('HalfDuplexIdealPhySignalParameters', parent=root_module['ns3::SpectrumSignalParameters']) ## integer.h (module 'core'): ns3::IntegerValue [class] module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## propagation-loss-model.h (module 'propagation'): ns3::LogDistancePropagationLossModel [class] module.add_class('LogDistancePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## mac16-address.h (module 'network'): ns3::Mac16AddressChecker [class] module.add_class('Mac16AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac16-address.h (module 'network'): ns3::Mac16AddressValue [class] module.add_class('Mac16AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## 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']) ## mac64-address.h (module 'network'): ns3::Mac64AddressChecker [class] module.add_class('Mac64AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac64-address.h (module 'network'): ns3::Mac64AddressValue [class] module.add_class('Mac64AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## propagation-loss-model.h (module 'propagation'): ns3::MatrixPropagationLossModel [class] module.add_class('MatrixPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## mobility-model.h (module 'mobility'): ns3::MobilityModel [class] module.add_class('MobilityModel', import_from_module='ns.mobility', parent=root_module['ns3::Object']) ## propagation-loss-model.h (module 'propagation'): ns3::NakagamiPropagationLossModel [class] module.add_class('NakagamiPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## 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']) ## non-communicating-net-device.h (module 'spectrum'): ns3::NonCommunicatingNetDevice [class] module.add_class('NonCommunicatingNetDevice', parent=root_module['ns3::NetDevice']) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class] module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## spectrum-error-model.h (module 'spectrum'): ns3::ShannonSpectrumErrorModel [class] module.add_class('ShannonSpectrumErrorModel', parent=root_module['ns3::SpectrumErrorModel']) ## spectrum-analyzer.h (module 'spectrum'): ns3::SpectrumAnalyzer [class] module.add_class('SpectrumAnalyzer', parent=root_module['ns3::SpectrumPhy']) ## spectrum-channel.h (module 'spectrum'): ns3::SpectrumChannel [class] module.add_class('SpectrumChannel', parent=root_module['ns3::Channel']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## uinteger.h (module 'core'): ns3::UintegerValue [class] module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector2DChecker [class] module.add_class('Vector2DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector2DValue [class] module.add_class('Vector2DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector3DChecker [class] module.add_class('Vector3DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector3DValue [class] module.add_class('Vector3DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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']) ## aloha-noack-net-device.h (module 'spectrum'): ns3::AlohaNoackNetDevice [class] module.add_class('AlohaNoackNetDevice', parent=root_module['ns3::NetDevice']) ## aloha-noack-net-device.h (module 'spectrum'): ns3::AlohaNoackNetDevice::State [enumeration] module.add_enum('State', ['IDLE', 'TX', 'RX'], outer_class=root_module['ns3::AlohaNoackNetDevice']) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::MultiModelSpectrumChannel [class] module.add_class('MultiModelSpectrumChannel', parent=root_module['ns3::SpectrumChannel']) ## single-model-spectrum-channel.h (module 'spectrum'): ns3::SingleModelSpectrumChannel [class] module.add_class('SingleModelSpectrumChannel', parent=root_module['ns3::SpectrumChannel']) module.add_container('std::map< std::string, ns3::LogComponent * >', ('std::string', 'ns3::LogComponent *'), container_type=u'map') module.add_container('std::set< ns3::Ptr< ns3::SpectrumPhy > >', 'ns3::Ptr< ns3::SpectrumPhy >', container_type=u'set') module.add_container('ns3::SpectrumConverterMap_t', ('unsigned int', 'ns3::SpectrumConverter'), container_type=u'map') module.add_container('std::vector< double >', 'double', container_type=u'vector') module.add_container('ns3::Bands', 'ns3::BandInfo', container_type=u'vector') module.add_container('std::vector< ns3::Ptr< ns3::SpectrumPhy > >', 'ns3::Ptr< ns3::SpectrumPhy >', container_type=u'vector') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxEndCallback') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxEndCallback*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxEndCallback&') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndOkCallback') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndOkCallback*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndOkCallback&') typehandlers.add_type_alias(u'std::vector< ns3::BandInfo, std::allocator< ns3::BandInfo > >', u'ns3::Bands') typehandlers.add_type_alias(u'std::vector< ns3::BandInfo, std::allocator< ns3::BandInfo > >*', u'ns3::Bands*') typehandlers.add_type_alias(u'std::vector< ns3::BandInfo, std::allocator< ns3::BandInfo > >&', u'ns3::Bands&') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogTimePrinter') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogTimePrinter*') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogTimePrinter&') typehandlers.add_type_alias(u'ns3::Vector3DValue', u'ns3::VectorValue') typehandlers.add_type_alias(u'ns3::Vector3DValue*', u'ns3::VectorValue*') typehandlers.add_type_alias(u'ns3::Vector3DValue&', u'ns3::VectorValue&') module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogNodePrinter') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogNodePrinter*') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogNodePrinter&') typehandlers.add_type_alias(u'ns3::Vector3D', u'ns3::Vector') typehandlers.add_type_alias(u'ns3::Vector3D*', u'ns3::Vector*') typehandlers.add_type_alias(u'ns3::Vector3D&', u'ns3::Vector&') module.add_typedef(root_module['ns3::Vector3D'], 'Vector') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxStartCallback') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxStartCallback*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxStartCallback&') typehandlers.add_type_alias(u'std::map< unsigned int, ns3::RxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::RxSpectrumModelInfo > > >', u'ns3::RxSpectrumModelInfoMap_t') typehandlers.add_type_alias(u'std::map< unsigned int, ns3::RxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::RxSpectrumModelInfo > > >*', u'ns3::RxSpectrumModelInfoMap_t*') typehandlers.add_type_alias(u'std::map< unsigned int, ns3::RxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::RxSpectrumModelInfo > > >&', u'ns3::RxSpectrumModelInfoMap_t&') typehandlers.add_type_alias(u'uint32_t', u'ns3::SpectrumModelUid_t') typehandlers.add_type_alias(u'uint32_t*', u'ns3::SpectrumModelUid_t*') typehandlers.add_type_alias(u'uint32_t&', u'ns3::SpectrumModelUid_t&') typehandlers.add_type_alias(u'std::map< unsigned int, ns3::TxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::TxSpectrumModelInfo > > >', u'ns3::TxSpectrumModelInfoMap_t') typehandlers.add_type_alias(u'std::map< unsigned int, ns3::TxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::TxSpectrumModelInfo > > >*', u'ns3::TxSpectrumModelInfoMap_t*') typehandlers.add_type_alias(u'std::map< unsigned int, ns3::TxSpectrumModelInfo, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::TxSpectrumModelInfo > > >&', u'ns3::TxSpectrumModelInfoMap_t&') typehandlers.add_type_alias(u'ns3::Vector3DChecker', u'ns3::VectorChecker') typehandlers.add_type_alias(u'ns3::Vector3DChecker*', u'ns3::VectorChecker*') typehandlers.add_type_alias(u'ns3::Vector3DChecker&', u'ns3::VectorChecker&') module.add_typedef(root_module['ns3::Vector3DChecker'], 'VectorChecker') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndErrorCallback') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndErrorCallback*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndErrorCallback&') typehandlers.add_type_alias(u'std::vector< double, std::allocator< double > >', u'ns3::Values') typehandlers.add_type_alias(u'std::vector< double, std::allocator< double > >*', u'ns3::Values*') typehandlers.add_type_alias(u'std::vector< double, std::allocator< double > >&', u'ns3::Values&') typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxStartCallback') typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxStartCallback*') typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxStartCallback&') typehandlers.add_type_alias(u'std::map< unsigned int, ns3::SpectrumConverter, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::SpectrumConverter > > >', u'ns3::SpectrumConverterMap_t') typehandlers.add_type_alias(u'std::map< unsigned int, ns3::SpectrumConverter, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::SpectrumConverter > > >*', u'ns3::SpectrumConverterMap_t*') typehandlers.add_type_alias(u'std::map< unsigned int, ns3::SpectrumConverter, std::less< unsigned int >, std::allocator< std::pair< unsigned int const, ns3::SpectrumConverter > > >&', u'ns3::SpectrumConverterMap_t&') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) ## Register a nested module for the namespace 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_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *', u'ns3::TracedValueCallback::Bool') typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) **', u'ns3::TracedValueCallback::Bool*') typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *&', u'ns3::TracedValueCallback::Bool&') typehandlers.add_type_alias(u'void ( * ) ( double, double ) *', u'ns3::TracedValueCallback::Double') typehandlers.add_type_alias(u'void ( * ) ( double, double ) **', u'ns3::TracedValueCallback::Double*') typehandlers.add_type_alias(u'void ( * ) ( double, double ) *&', u'ns3::TracedValueCallback::Double&') typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *', u'ns3::TracedValueCallback::Int8') typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) **', u'ns3::TracedValueCallback::Int8*') typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *&', u'ns3::TracedValueCallback::Int8&') typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *', u'ns3::TracedValueCallback::Uint8') typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) **', u'ns3::TracedValueCallback::Uint8*') typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *&', u'ns3::TracedValueCallback::Uint8&') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *', u'ns3::TracedValueCallback::Uint32') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) **', u'ns3::TracedValueCallback::Uint32*') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *&', u'ns3::TracedValueCallback::Uint32&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&') typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *', u'ns3::TracedValueCallback::Int16') typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) **', u'ns3::TracedValueCallback::Int16*') typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *&', u'ns3::TracedValueCallback::Int16&') typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *', u'ns3::TracedValueCallback::Int32') typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) **', u'ns3::TracedValueCallback::Int32*') typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *&', u'ns3::TracedValueCallback::Int32&') typehandlers.add_type_alias(u'void ( * ) ( ) *', u'ns3::TracedValueCallback::Void') typehandlers.add_type_alias(u'void ( * ) ( ) **', u'ns3::TracedValueCallback::Void*') typehandlers.add_type_alias(u'void ( * ) ( ) *&', u'ns3::TracedValueCallback::Void&') typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *', u'ns3::TracedValueCallback::Uint16') typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) **', u'ns3::TracedValueCallback::Uint16*') typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *&', u'ns3::TracedValueCallback::Uint16&') def register_types_ns3_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_Ns3AdhocAlohaNoackIdealPhyHelper_methods(root_module, root_module['ns3::AdhocAlohaNoackIdealPhyHelper']) register_Ns3Angles_methods(root_module, root_module['ns3::Angles']) 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_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent']) register_Ns3Mac16Address_methods(root_module, root_module['ns3::Mac16Address']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3Mac64Address_methods(root_module, root_module['ns3::Mac64Address']) register_Ns3MicrowaveOvenSpectrumValueHelper_methods(root_module, root_module['ns3::MicrowaveOvenSpectrumValueHelper']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3NonCopyable_methods(root_module, root_module['ns3::NonCopyable']) 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_Ns3ParameterLogger_methods(root_module, root_module['ns3::ParameterLogger']) register_Ns3RxSpectrumModelInfo_methods(root_module, root_module['ns3::RxSpectrumModelInfo']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3SpectrumAnalyzerHelper_methods(root_module, root_module['ns3::SpectrumAnalyzerHelper']) register_Ns3SpectrumChannelHelper_methods(root_module, root_module['ns3::SpectrumChannelHelper']) register_Ns3SpectrumPhyHelper_methods(root_module, root_module['ns3::SpectrumPhyHelper']) register_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TracedValue__Unsigned_int_methods(root_module, root_module['ns3::TracedValue< unsigned int >']) register_Ns3TvSpectrumTransmitterHelper_methods(root_module, root_module['ns3::TvSpectrumTransmitterHelper']) register_Ns3TxSpectrumModelInfo_methods(root_module, root_module['ns3::TxSpectrumModelInfo']) 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_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D']) register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D']) register_Ns3WaveformGeneratorHelper_methods(root_module, root_module['ns3::WaveformGeneratorHelper']) register_Ns3WifiSpectrumValue5MhzFactory_methods(root_module, root_module['ns3::WifiSpectrumValue5MhzFactory']) register_Ns3WifiSpectrumValueHelper_methods(root_module, root_module['ns3::WifiSpectrumValueHelper']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PropagationDelayModel_methods(root_module, root_module['ns3::PropagationDelayModel']) register_Ns3PropagationLossModel_methods(root_module, root_module['ns3::PropagationLossModel']) register_Ns3QueueBase_methods(root_module, root_module['ns3::QueueBase']) register_Ns3RandomPropagationDelayModel_methods(root_module, root_module['ns3::RandomPropagationDelayModel']) register_Ns3RandomPropagationLossModel_methods(root_module, root_module['ns3::RandomPropagationLossModel']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3RangePropagationLossModel_methods(root_module, root_module['ns3::RangePropagationLossModel']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__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__Ns3SpectrumConverter_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumConverter__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >']) 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_Ns3SpectrumConverter_methods(root_module, root_module['ns3::SpectrumConverter']) register_Ns3SpectrumErrorModel_methods(root_module, root_module['ns3::SpectrumErrorModel']) 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_Ns3ThreeLogDistancePropagationLossModel_methods(root_module, root_module['ns3::ThreeLogDistancePropagationLossModel']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3TvSpectrumTransmitter_methods(root_module, root_module['ns3::TvSpectrumTransmitter']) register_Ns3TwoRayGroundPropagationLossModel_methods(root_module, root_module['ns3::TwoRayGroundPropagationLossModel']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WaveformGenerator_methods(root_module, root_module['ns3::WaveformGenerator']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_Ns3AlohaNoackMacHeader_methods(root_module, root_module['ns3::AlohaNoackMacHeader']) register_Ns3AntennaModel_methods(root_module, root_module['ns3::AntennaModel']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker']) register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3ConstantSpectrumPropagationLossModel_methods(root_module, root_module['ns3::ConstantSpectrumPropagationLossModel']) register_Ns3ConstantSpeedPropagationDelayModel_methods(root_module, root_module['ns3::ConstantSpeedPropagationDelayModel']) register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker']) register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker']) register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue']) register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3FixedRssLossModel_methods(root_module, root_module['ns3::FixedRssLossModel']) register_Ns3FriisPropagationLossModel_methods(root_module, root_module['ns3::FriisPropagationLossModel']) register_Ns3FriisSpectrumPropagationLossModel_methods(root_module, root_module['ns3::FriisSpectrumPropagationLossModel']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3HalfDuplexIdealPhy_methods(root_module, root_module['ns3::HalfDuplexIdealPhy']) register_Ns3HalfDuplexIdealPhySignalParameters_methods(root_module, root_module['ns3::HalfDuplexIdealPhySignalParameters']) register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3LogDistancePropagationLossModel_methods(root_module, root_module['ns3::LogDistancePropagationLossModel']) register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) register_Ns3Mac16AddressChecker_methods(root_module, root_module['ns3::Mac16AddressChecker']) register_Ns3Mac16AddressValue_methods(root_module, root_module['ns3::Mac16AddressValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3Mac64AddressChecker_methods(root_module, root_module['ns3::Mac64AddressChecker']) register_Ns3Mac64AddressValue_methods(root_module, root_module['ns3::Mac64AddressValue']) register_Ns3MatrixPropagationLossModel_methods(root_module, root_module['ns3::MatrixPropagationLossModel']) register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel']) register_Ns3NakagamiPropagationLossModel_methods(root_module, root_module['ns3::NakagamiPropagationLossModel']) 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_Ns3NonCommunicatingNetDevice_methods(root_module, root_module['ns3::NonCommunicatingNetDevice']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3ShannonSpectrumErrorModel_methods(root_module, root_module['ns3::ShannonSpectrumErrorModel']) register_Ns3SpectrumAnalyzer_methods(root_module, root_module['ns3::SpectrumAnalyzer']) register_Ns3SpectrumChannel_methods(root_module, root_module['ns3::SpectrumChannel']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue']) register_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker']) register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue']) register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker']) register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3AlohaNoackNetDevice_methods(root_module, root_module['ns3::AlohaNoackNetDevice']) register_Ns3MultiModelSpectrumChannel_methods(root_module, root_module['ns3::MultiModelSpectrumChannel']) register_Ns3SingleModelSpectrumChannel_methods(root_module, root_module['ns3::SingleModelSpectrumChannel']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AdhocAlohaNoackIdealPhyHelper_methods(root_module, cls): ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::AdhocAlohaNoackIdealPhyHelper::AdhocAlohaNoackIdealPhyHelper(ns3::AdhocAlohaNoackIdealPhyHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::AdhocAlohaNoackIdealPhyHelper const &', 'arg0')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::AdhocAlohaNoackIdealPhyHelper::AdhocAlohaNoackIdealPhyHelper() [constructor] cls.add_constructor([]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::AdhocAlohaNoackIdealPhyHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::AdhocAlohaNoackIdealPhyHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::AdhocAlohaNoackIdealPhyHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'nodeName')], is_const=True) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetAntenna(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetAntenna', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetChannel(ns3::Ptr<ns3::SpectrumChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'channel')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetChannel(std::string channelName) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'channelName')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetNoisePowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> noisePsd) [member function] cls.add_method('SetNoisePowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'noisePsd')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetPhyAttribute(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('SetPhyAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')]) ## adhoc-aloha-noack-ideal-phy-helper.h (module 'spectrum'): void ns3::AdhocAlohaNoackIdealPhyHelper::SetTxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> txPsd) [member function] cls.add_method('SetTxPowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'txPsd')]) return def register_Ns3Angles_methods(root_module, cls): cls.add_output_stream_operator() ## angles.h (module 'antenna'): ns3::Angles::Angles(ns3::Angles const & arg0) [copy constructor] cls.add_constructor([param('ns3::Angles const &', 'arg0')]) ## angles.h (module 'antenna'): ns3::Angles::Angles() [constructor] cls.add_constructor([]) ## angles.h (module 'antenna'): ns3::Angles::Angles(double phi, double theta) [constructor] cls.add_constructor([param('double', 'phi'), param('double', 'theta')]) ## angles.h (module 'antenna'): ns3::Angles::Angles(ns3::Vector v) [constructor] cls.add_constructor([param('ns3::Vector', 'v')]) ## angles.h (module 'antenna'): ns3::Angles::Angles(ns3::Vector v, ns3::Vector o) [constructor] cls.add_constructor([param('ns3::Vector', 'v'), param('ns3::Vector', 'o')]) ## angles.h (module 'antenna'): ns3::Angles::phi [variable] cls.add_instance_attribute('phi', 'double', is_const=False) ## angles.h (module 'antenna'): ns3::Angles::theta [variable] cls.add_instance_attribute('theta', 'double', is_const=False) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3BandInfo_methods(root_module, cls): ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::BandInfo() [constructor] cls.add_constructor([]) ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::BandInfo(ns3::BandInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::BandInfo const &', 'arg0')]) ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::fc [variable] cls.add_instance_attribute('fc', 'double', is_const=False) ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::fh [variable] cls.add_instance_attribute('fh', 'double', is_const=False) ## spectrum-model.h (module 'spectrum'): ns3::BandInfo::fl [variable] cls.add_instance_attribute('fl', 'double', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') return def register_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'): ns3::Time ns3::DataRate::CalculateBitsTxTime(uint32_t bits) const [member function] cls.add_method('CalculateBitsTxTime', 'ns3::Time', [param('uint32_t', 'bits')], is_const=True) ## data-rate.h (module 'network'): ns3::Time ns3::DataRate::CalculateBytesTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateBytesTxTime', 'ns3::Time', [param('uint32_t', 'bytes')], is_const=True) ## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateTxTime', 'double', [param('uint32_t', 'bytes')], deprecated=True, 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_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], deprecated=True, is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_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(std::string const & name, std::string const & file, ns3::LogLevel const mask=::ns3::LOG_NONE) [constructor] cls.add_constructor([param('std::string const &', 'name'), param('std::string const &', 'file'), param('ns3::LogLevel const', 'mask', default_value='::ns3::LOG_NONE')]) ## log.h (module 'core'): void ns3::LogComponent::Disable(ns3::LogLevel const level) [member function] cls.add_method('Disable', 'void', [param('ns3::LogLevel const', 'level')]) ## log.h (module 'core'): void ns3::LogComponent::Enable(ns3::LogLevel const level) [member function] cls.add_method('Enable', 'void', [param('ns3::LogLevel const', 'level')]) ## log.h (module 'core'): std::string ns3::LogComponent::File() const [member function] cls.add_method('File', 'std::string', [], is_const=True) ## log.h (module 'core'): static std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >,ns3::LogComponent*,std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, ns3::LogComponent*> > > * ns3::LogComponent::GetComponentList() [member function] cls.add_method('GetComponentList', 'std::map< std::string, ns3::LogComponent * > *', [], is_static=True) ## log.h (module 'core'): static std::string ns3::LogComponent::GetLevelLabel(ns3::LogLevel const level) [member function] cls.add_method('GetLevelLabel', 'std::string', [param('ns3::LogLevel const', 'level')], is_static=True) ## log.h (module 'core'): bool ns3::LogComponent::IsEnabled(ns3::LogLevel const level) const [member function] cls.add_method('IsEnabled', 'bool', [param('ns3::LogLevel const', '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) ## log.h (module 'core'): void ns3::LogComponent::SetMask(ns3::LogLevel const level) [member function] cls.add_method('SetMask', 'void', [param('ns3::LogLevel const', 'level')]) return def register_Ns3Mac16Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(ns3::Mac16Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac16Address const &', 'arg0')]) ## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address() [constructor] cls.add_constructor([]) ## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac16Address', [], is_static=True) ## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac16Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac16-address.h (module 'network'): static bool ns3::Mac16Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3Mac64Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(ns3::Mac64Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac64Address const &', 'arg0')]) ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address() [constructor] cls.add_constructor([]) ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac64Address', [], is_static=True) ## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac64Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac64-address.h (module 'network'): static bool ns3::Mac64Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3MicrowaveOvenSpectrumValueHelper_methods(root_module, cls): ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): ns3::MicrowaveOvenSpectrumValueHelper::MicrowaveOvenSpectrumValueHelper() [constructor] cls.add_constructor([]) ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): ns3::MicrowaveOvenSpectrumValueHelper::MicrowaveOvenSpectrumValueHelper(ns3::MicrowaveOvenSpectrumValueHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::MicrowaveOvenSpectrumValueHelper const &', 'arg0')]) ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::MicrowaveOvenSpectrumValueHelper::CreatePowerSpectralDensityMwo1() [member function] cls.add_method('CreatePowerSpectralDensityMwo1', 'ns3::Ptr< ns3::SpectrumValue >', [], is_static=True) ## microwave-oven-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::MicrowaveOvenSpectrumValueHelper::CreatePowerSpectralDensityMwo2() [member function] cls.add_method('CreatePowerSpectralDensityMwo2', 'ns3::Ptr< ns3::SpectrumValue >', [], 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_Ns3NonCopyable_methods(root_module, cls): ## non-copyable.h (module 'core'): ns3::NonCopyable::NonCopyable() [constructor] cls.add_constructor([], visibility='protected') return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 1 ]', 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::size [variable] cls.add_instance_attribute('size', 'uint32_t', 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_Ns3ParameterLogger_methods(root_module, cls): ## log.h (module 'core'): ns3::ParameterLogger::ParameterLogger(ns3::ParameterLogger const & arg0) [copy constructor] cls.add_constructor([param('ns3::ParameterLogger const &', 'arg0')]) ## log.h (module 'core'): ns3::ParameterLogger::ParameterLogger(std::ostream & os) [constructor] cls.add_constructor([param('std::ostream &', 'os')]) return def register_Ns3RxSpectrumModelInfo_methods(root_module, cls): ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo::RxSpectrumModelInfo(ns3::RxSpectrumModelInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::RxSpectrumModelInfo const &', 'arg0')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo::RxSpectrumModelInfo(ns3::Ptr<ns3::SpectrumModel const> rxSpectrumModel) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::SpectrumModel const >', 'rxSpectrumModel')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo::m_rxPhySet [variable] cls.add_instance_attribute('m_rxPhySet', 'std::set< ns3::Ptr< ns3::SpectrumPhy > >', is_const=False) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::RxSpectrumModelInfo::m_rxSpectrumModel [variable] cls.add_instance_attribute('m_rxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SpectrumAnalyzerHelper_methods(root_module, cls): ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::SpectrumAnalyzerHelper::SpectrumAnalyzerHelper(ns3::SpectrumAnalyzerHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumAnalyzerHelper const &', 'arg0')]) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::SpectrumAnalyzerHelper::SpectrumAnalyzerHelper() [constructor] cls.add_constructor([]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::EnableAsciiAll(std::string prefix) [member function] cls.add_method('EnableAsciiAll', 'void', [param('std::string', 'prefix')]) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::SpectrumAnalyzerHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::SpectrumAnalyzerHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## spectrum-analyzer-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::SpectrumAnalyzerHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'nodeName')], is_const=True) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetAntenna(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetAntenna', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetChannel(ns3::Ptr<ns3::SpectrumChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'channel')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetChannel(std::string channelName) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'channelName')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetPhyAttribute(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('SetPhyAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')]) ## spectrum-analyzer-helper.h (module 'spectrum'): void ns3::SpectrumAnalyzerHelper::SetRxSpectrumModel(ns3::Ptr<ns3::SpectrumModel> m) [member function] cls.add_method('SetRxSpectrumModel', 'void', [param('ns3::Ptr< ns3::SpectrumModel >', 'm')]) return def register_Ns3SpectrumChannelHelper_methods(root_module, cls): ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumChannelHelper::SpectrumChannelHelper() [constructor] cls.add_constructor([]) ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumChannelHelper::SpectrumChannelHelper(ns3::SpectrumChannelHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumChannelHelper const &', 'arg0')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::AddPropagationLoss(std::string name, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('AddPropagationLoss', 'void', [param('std::string', 'name'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::AddPropagationLoss(ns3::Ptr<ns3::PropagationLossModel> m) [member function] cls.add_method('AddPropagationLoss', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'm')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::AddSpectrumPropagationLoss(std::string name, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('AddSpectrumPropagationLoss', 'void', [param('std::string', 'name'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::AddSpectrumPropagationLoss(ns3::Ptr<ns3::SpectrumPropagationLossModel> m) [member function] cls.add_method('AddSpectrumPropagationLoss', 'void', [param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'm')]) ## spectrum-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumChannel> ns3::SpectrumChannelHelper::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::SpectrumChannel >', [], is_const=True) ## spectrum-helper.h (module 'spectrum'): static ns3::SpectrumChannelHelper ns3::SpectrumChannelHelper::Default() [member function] cls.add_method('Default', 'ns3::SpectrumChannelHelper', [], is_static=True) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::SetChannel(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumChannelHelper::SetPropagationDelay(std::string name, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetPropagationDelay', 'void', [param('std::string', 'name'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) return def register_Ns3SpectrumPhyHelper_methods(root_module, cls): ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumPhyHelper::SpectrumPhyHelper() [constructor] cls.add_constructor([]) ## spectrum-helper.h (module 'spectrum'): ns3::SpectrumPhyHelper::SpectrumPhyHelper(ns3::SpectrumPhyHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumPhyHelper const &', 'arg0')]) ## spectrum-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumPhy> ns3::SpectrumPhyHelper::Create(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::NetDevice> device) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::SpectrumPhy >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::NetDevice >', 'device')], is_const=True) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumPhyHelper::SetChannel(ns3::Ptr<ns3::SpectrumChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'channel')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumPhyHelper::SetChannel(std::string channelName) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'channelName')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumPhyHelper::SetPhy(std::string name, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetPhy', 'void', [param('std::string', 'name'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## spectrum-helper.h (module 'spectrum'): void ns3::SpectrumPhyHelper::SetPhyAttribute(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('SetPhyAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')]) return def register_Ns3SystemWallClockMs_methods(root_module, cls): ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [copy constructor] cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')]) ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor] cls.add_constructor([]) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function] cls.add_method('End', 'int64_t', []) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function] cls.add_method('GetElapsedReal', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function] cls.add_method('GetElapsedSystem', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function] cls.add_method('GetElapsedUser', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function] cls.add_method('Start', 'void', []) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TracedValue__Unsigned_int_methods(root_module, cls): ## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue() [constructor] cls.add_constructor([]) ## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue(ns3::TracedValue<unsigned int> const & o) [copy constructor] cls.add_constructor([param('ns3::TracedValue< unsigned int > const &', 'o')]) ## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue(unsigned int const & v) [constructor] cls.add_constructor([param('unsigned int const &', 'v')]) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Connect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Connect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::ConnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('ConnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Disconnect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Disconnect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::DisconnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('DisconnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): unsigned int ns3::TracedValue<unsigned int>::Get() const [member function] cls.add_method('Get', 'unsigned int', [], is_const=True) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Set(unsigned int const & v) [member function] cls.add_method('Set', 'void', [param('unsigned int const &', 'v')]) return def register_Ns3TvSpectrumTransmitterHelper_methods(root_module, cls): ## tv-spectrum-transmitter-helper.h (module 'spectrum'): ns3::TvSpectrumTransmitterHelper::TvSpectrumTransmitterHelper(ns3::TvSpectrumTransmitterHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::TvSpectrumTransmitterHelper const &', 'arg0')]) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): ns3::TvSpectrumTransmitterHelper::TvSpectrumTransmitterHelper() [constructor] cls.add_constructor([]) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): int64_t ns3::TvSpectrumTransmitterHelper::AssignStreams(int64_t streamNum) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'streamNum')]) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): void ns3::TvSpectrumTransmitterHelper::CreateRegionalTvTransmitters(ns3::TvSpectrumTransmitterHelper::Region region, ns3::TvSpectrumTransmitterHelper::Density density, double originLatitude, double originLongitude, double maxAltitude, double maxRadius) [member function] cls.add_method('CreateRegionalTvTransmitters', 'void', [param('ns3::TvSpectrumTransmitterHelper::Region', 'region'), param('ns3::TvSpectrumTransmitterHelper::Density', 'density'), param('double', 'originLatitude'), param('double', 'originLongitude'), param('double', 'maxAltitude'), param('double', 'maxRadius')]) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::TvSpectrumTransmitterHelper::Install(ns3::NodeContainer nodes) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'nodes')]) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::TvSpectrumTransmitterHelper::Install(ns3::NodeContainer nodes, ns3::TvSpectrumTransmitterHelper::Region region, uint16_t channelNumber) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'nodes'), param('ns3::TvSpectrumTransmitterHelper::Region', 'region'), param('uint16_t', 'channelNumber')]) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::TvSpectrumTransmitterHelper::InstallAdjacent(ns3::NodeContainer nodes) [member function] cls.add_method('InstallAdjacent', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'nodes')]) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::TvSpectrumTransmitterHelper::InstallAdjacent(ns3::NodeContainer nodes, ns3::TvSpectrumTransmitterHelper::Region region, uint16_t channelNumber) [member function] cls.add_method('InstallAdjacent', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'nodes'), param('ns3::TvSpectrumTransmitterHelper::Region', 'region'), param('uint16_t', 'channelNumber')]) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): void ns3::TvSpectrumTransmitterHelper::SetAttribute(std::string name, ns3::AttributeValue const & val) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'val')]) ## tv-spectrum-transmitter-helper.h (module 'spectrum'): void ns3::TvSpectrumTransmitterHelper::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')]) return def register_Ns3TxSpectrumModelInfo_methods(root_module, cls): ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo::TxSpectrumModelInfo(ns3::TxSpectrumModelInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::TxSpectrumModelInfo const &', 'arg0')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo::TxSpectrumModelInfo(ns3::Ptr<ns3::SpectrumModel const> txSpectrumModel) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::SpectrumModel const >', 'txSpectrumModel')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo::m_spectrumConverterMap [variable] cls.add_instance_attribute('m_spectrumConverterMap', 'ns3::SpectrumConverterMap_t', is_const=False) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::TxSpectrumModelInfo::m_txSpectrumModel [variable] cls.add_instance_attribute('m_txSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', is_const=False) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')], deprecated=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function] cls.add_method('GetSize', 'std::size_t', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent() [member function] cls.add_method('SetParent', 'ns3::TypeId', [], template_parameters=['ns3::QueueBase']) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function] cls.add_method('SetSize', 'ns3::TypeId', [param('std::size_t', 'size')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t uid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'uid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable] cls.add_instance_attribute('callback', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3Vector2D_methods(root_module, cls): cls.add_binary_numeric_operator('+', root_module['ns3::Vector2D'], root_module['ns3::Vector2D'], param('ns3::Vector2D const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Vector2D'], root_module['ns3::Vector2D'], param('ns3::Vector2D const &', u'right')) cls.add_binary_comparison_operator('<') 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'): double ns3::Vector2D::GetLength() const [member function] cls.add_method('GetLength', 'double', [], is_const=True) ## 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_binary_numeric_operator('+', root_module['ns3::Vector3D'], root_module['ns3::Vector3D'], param('ns3::Vector3D const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Vector3D'], root_module['ns3::Vector3D'], param('ns3::Vector3D const &', u'right')) cls.add_binary_comparison_operator('<') 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'): double ns3::Vector3D::GetLength() const [member function] cls.add_method('GetLength', 'double', [], is_const=True) ## 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_Ns3WaveformGeneratorHelper_methods(root_module, cls): ## waveform-generator-helper.h (module 'spectrum'): ns3::WaveformGeneratorHelper::WaveformGeneratorHelper(ns3::WaveformGeneratorHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::WaveformGeneratorHelper const &', 'arg0')]) ## waveform-generator-helper.h (module 'spectrum'): ns3::WaveformGeneratorHelper::WaveformGeneratorHelper() [constructor] cls.add_constructor([]) ## waveform-generator-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::WaveformGeneratorHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## waveform-generator-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::WaveformGeneratorHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## waveform-generator-helper.h (module 'spectrum'): ns3::NetDeviceContainer ns3::WaveformGeneratorHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'nodeName')], is_const=True) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetAntenna(std::string type, std::string n0="", ns3::AttributeValue const & v0=ns3::EmptyAttributeValue(), std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetAntenna', 'void', [param('std::string', 'type'), param('std::string', 'n0', default_value='""'), param('ns3::AttributeValue const &', 'v0', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetChannel(ns3::Ptr<ns3::SpectrumChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'channel')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetChannel(std::string channelName) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'channelName')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetPhyAttribute(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('SetPhyAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')]) ## waveform-generator-helper.h (module 'spectrum'): void ns3::WaveformGeneratorHelper::SetTxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> txPsd) [member function] cls.add_method('SetTxPowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'txPsd')]) return def register_Ns3WifiSpectrumValue5MhzFactory_methods(root_module, cls): ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValue5MhzFactory::WifiSpectrumValue5MhzFactory() [constructor] cls.add_constructor([]) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValue5MhzFactory::WifiSpectrumValue5MhzFactory(ns3::WifiSpectrumValue5MhzFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiSpectrumValue5MhzFactory const &', 'arg0')]) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValue5MhzFactory::CreateConstant(double psd) [member function] cls.add_method('CreateConstant', 'ns3::Ptr< ns3::SpectrumValue >', [param('double', 'psd')], is_virtual=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValue5MhzFactory::CreateRfFilter(uint8_t channel) [member function] cls.add_method('CreateRfFilter', 'ns3::Ptr< ns3::SpectrumValue >', [param('uint8_t', 'channel')], is_virtual=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValue5MhzFactory::CreateTxPowerSpectralDensity(double txPower, uint8_t channel) [member function] cls.add_method('CreateTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('double', 'txPower'), param('uint8_t', 'channel')], is_virtual=True) return def register_Ns3WifiSpectrumValueHelper_methods(root_module, cls): ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValueHelper::WifiSpectrumValueHelper() [constructor] cls.add_constructor([]) ## wifi-spectrum-value-helper.h (module 'spectrum'): ns3::WifiSpectrumValueHelper::WifiSpectrumValueHelper(ns3::WifiSpectrumValueHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiSpectrumValueHelper const &', 'arg0')]) ## wifi-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateDsssTxPowerSpectralDensity(uint32_t centerFrequency, double txPowerW, uint8_t guardBandwidth) [member function] cls.add_method('CreateDsssTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('uint32_t', 'centerFrequency'), param('double', 'txPowerW'), param('uint8_t', 'guardBandwidth')], is_static=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateHeOfdmTxPowerSpectralDensity(uint32_t centerFrequency, uint8_t channelWidth, double txPowerW, uint8_t guardBandwidth) [member function] cls.add_method('CreateHeOfdmTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('uint32_t', 'centerFrequency'), param('uint8_t', 'channelWidth'), param('double', 'txPowerW'), param('uint8_t', 'guardBandwidth')], is_static=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateHtOfdmTxPowerSpectralDensity(uint32_t centerFrequency, uint8_t channelWidth, double txPowerW, uint8_t guardBandwidth) [member function] cls.add_method('CreateHtOfdmTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('uint32_t', 'centerFrequency'), param('uint8_t', 'channelWidth'), param('double', 'txPowerW'), param('uint8_t', 'guardBandwidth')], is_static=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateNoisePowerSpectralDensity(uint32_t centerFrequency, uint8_t channelWidth, double bandBandwidth, double noiseFigure, uint8_t guardBandwidth) [member function] cls.add_method('CreateNoisePowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('uint32_t', 'centerFrequency'), param('uint8_t', 'channelWidth'), param('double', 'bandBandwidth'), param('double', 'noiseFigure'), param('uint8_t', 'guardBandwidth')], is_static=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateNoisePowerSpectralDensity(double noiseFigure, ns3::Ptr<ns3::SpectrumModel> spectrumModel) [member function] cls.add_method('CreateNoisePowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('double', 'noiseFigure'), param('ns3::Ptr< ns3::SpectrumModel >', 'spectrumModel')], is_static=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateOfdmTxPowerSpectralDensity(uint32_t centerFrequency, uint8_t channelWidth, double txPowerW, uint8_t guardBandwidth) [member function] cls.add_method('CreateOfdmTxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('uint32_t', 'centerFrequency'), param('uint8_t', 'channelWidth'), param('double', 'txPowerW'), param('uint8_t', 'guardBandwidth')], is_static=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumValue> ns3::WifiSpectrumValueHelper::CreateRfFilter(uint32_t centerFrequency, uint8_t channelWidth, double bandBandwidth, uint8_t guardBandwidth) [member function] cls.add_method('CreateRfFilter', 'ns3::Ptr< ns3::SpectrumValue >', [param('uint32_t', 'centerFrequency'), param('uint8_t', 'channelWidth'), param('double', 'bandBandwidth'), param('uint8_t', 'guardBandwidth')], is_static=True) ## wifi-spectrum-value-helper.h (module 'spectrum'): static ns3::Ptr<ns3::SpectrumModel> ns3::WifiSpectrumValueHelper::GetSpectrumModel(uint32_t centerFrequency, uint8_t channelWidth, double bandBandwidth, uint8_t guardBandwidth) [member function] cls.add_method('GetSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel >', [param('uint32_t', 'centerFrequency'), param('uint8_t', 'channelWidth'), param('double', 'bandBandwidth'), param('uint8_t', 'guardBandwidth')], is_static=True) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): bool ns3::Object::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3PropagationDelayModel_methods(root_module, cls): ## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel::PropagationDelayModel() [constructor] cls.add_constructor([]) ## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel::PropagationDelayModel(ns3::PropagationDelayModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::PropagationDelayModel const &', 'arg0')]) ## propagation-delay-model.h (module 'propagation'): int64_t ns3::PropagationDelayModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::PropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('GetDelay', 'ns3::Time', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_pure_virtual=True, is_const=True, is_virtual=True) ## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::PropagationDelayModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-delay-model.h (module 'propagation'): int64_t ns3::PropagationDelayModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3PropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::PropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::PropagationLossModel::PropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::PropagationLossModel::SetNext(ns3::Ptr<ns3::PropagationLossModel> next) [member function] cls.add_method('SetNext', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'next')]) ## propagation-loss-model.h (module 'propagation'): ns3::Ptr<ns3::PropagationLossModel> ns3::PropagationLossModel::GetNext() [member function] cls.add_method('GetNext', 'ns3::Ptr< ns3::PropagationLossModel >', []) ## propagation-loss-model.h (module 'propagation'): double ns3::PropagationLossModel::CalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('CalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::PropagationLossModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## propagation-loss-model.h (module 'propagation'): double ns3::PropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::PropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3QueueBase_methods(root_module, cls): ## queue.h (module 'network'): ns3::QueueBase::QueueBase(ns3::QueueBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::QueueBase const &', 'arg0')]) ## queue.h (module 'network'): ns3::QueueBase::QueueBase() [constructor] cls.add_constructor([]) ## queue.h (module 'network'): static void ns3::QueueBase::AppendItemTypeIfNotPresent(std::string & typeId, std::string const & itemType) [member function] cls.add_method('AppendItemTypeIfNotPresent', 'void', [param('std::string &', 'typeId'), param('std::string const &', 'itemType')], is_static=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetMaxBytes() const [member function] cls.add_method('GetMaxBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetMaxPackets() const [member function] cls.add_method('GetMaxPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): ns3::QueueBase::QueueMode ns3::QueueBase::GetMode() const [member function] cls.add_method('GetMode', 'ns3::QueueBase::QueueMode', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetNBytes() const [member function] cls.add_method('GetNBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedBytes() const [member function] cls.add_method('GetTotalDroppedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedBytesAfterDequeue() const [member function] cls.add_method('GetTotalDroppedBytesAfterDequeue', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedBytesBeforeEnqueue() const [member function] cls.add_method('GetTotalDroppedBytesBeforeEnqueue', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedPackets() const [member function] cls.add_method('GetTotalDroppedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedPacketsAfterDequeue() const [member function] cls.add_method('GetTotalDroppedPacketsAfterDequeue', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedPacketsBeforeEnqueue() const [member function] cls.add_method('GetTotalDroppedPacketsBeforeEnqueue', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalReceivedBytes() const [member function] cls.add_method('GetTotalReceivedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalReceivedPackets() const [member function] cls.add_method('GetTotalReceivedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): static ns3::TypeId ns3::QueueBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue.h (module 'network'): bool ns3::QueueBase::IsEmpty() const [member function] cls.add_method('IsEmpty', 'bool', [], is_const=True) ## queue.h (module 'network'): void ns3::QueueBase::ResetStatistics() [member function] cls.add_method('ResetStatistics', 'void', []) ## queue.h (module 'network'): void ns3::QueueBase::SetMaxBytes(uint32_t maxBytes) [member function] cls.add_method('SetMaxBytes', 'void', [param('uint32_t', 'maxBytes')]) ## queue.h (module 'network'): void ns3::QueueBase::SetMaxPackets(uint32_t maxPackets) [member function] cls.add_method('SetMaxPackets', 'void', [param('uint32_t', 'maxPackets')]) ## queue.h (module 'network'): void ns3::QueueBase::SetMode(ns3::QueueBase::QueueMode mode) [member function] cls.add_method('SetMode', 'void', [param('ns3::QueueBase::QueueMode', 'mode')]) ## queue.h (module 'network'): void ns3::QueueBase::DoNsLog(ns3::LogLevel const level, std::string str) const [member function] cls.add_method('DoNsLog', 'void', [param('ns3::LogLevel const', 'level'), param('std::string', 'str')], is_const=True, visibility='protected') return def register_Ns3RandomPropagationDelayModel_methods(root_module, cls): ## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel::RandomPropagationDelayModel(ns3::RandomPropagationDelayModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomPropagationDelayModel const &', 'arg0')]) ## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel::RandomPropagationDelayModel() [constructor] cls.add_constructor([]) ## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::RandomPropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('GetDelay', 'ns3::Time', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, is_virtual=True) ## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::RandomPropagationDelayModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-delay-model.h (module 'propagation'): int64_t ns3::RandomPropagationDelayModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3RandomPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::RandomPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::RandomPropagationLossModel::RandomPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): double ns3::RandomPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::RandomPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3RandomVariableStream_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function] cls.add_method('SetStream', 'void', [param('int64_t', 'stream')]) ## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function] cls.add_method('GetStream', 'int64_t', [], is_const=True) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function] cls.add_method('SetAntithetic', 'void', [param('bool', 'isAntithetic')]) ## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function] cls.add_method('IsAntithetic', 'bool', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function] cls.add_method('Peek', 'ns3::RngStream *', [], is_const=True, visibility='protected') return def register_Ns3RangePropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::RangePropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::RangePropagationLossModel::RangePropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): double ns3::RangePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::RangePropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3SequentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function] cls.add_method('GetIncrement', 'ns3::Ptr< ns3::RandomVariableStream >', [], is_const=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function] cls.add_method('GetConsecutive', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__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__Ns3SpectrumConverter_Ns3Empty_Ns3DefaultDeleter__lt__ns3SpectrumConverter__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter< ns3::SpectrumConverter > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SpectrumConverter, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumConverter> >::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_Ns3SpectrumConverter_methods(root_module, cls): ## spectrum-converter.h (module 'spectrum'): ns3::SpectrumConverter::SpectrumConverter(ns3::SpectrumConverter const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumConverter const &', 'arg0')]) ## spectrum-converter.h (module 'spectrum'): ns3::SpectrumConverter::SpectrumConverter(ns3::Ptr<ns3::SpectrumModel const> fromSpectrumModel, ns3::Ptr<ns3::SpectrumModel const> toSpectrumModel) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::SpectrumModel const >', 'fromSpectrumModel'), param('ns3::Ptr< ns3::SpectrumModel const >', 'toSpectrumModel')]) ## spectrum-converter.h (module 'spectrum'): ns3::SpectrumConverter::SpectrumConverter() [constructor] cls.add_constructor([]) ## spectrum-converter.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumConverter::Convert(ns3::Ptr<ns3::SpectrumValue const> vvf) const [member function] cls.add_method('Convert', 'ns3::Ptr< ns3::SpectrumValue >', [param('ns3::Ptr< ns3::SpectrumValue const >', 'vvf')], is_const=True) return def register_Ns3SpectrumErrorModel_methods(root_module, cls): ## spectrum-error-model.h (module 'spectrum'): ns3::SpectrumErrorModel::SpectrumErrorModel() [constructor] cls.add_constructor([]) ## spectrum-error-model.h (module 'spectrum'): ns3::SpectrumErrorModel::SpectrumErrorModel(ns3::SpectrumErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumErrorModel const &', 'arg0')]) ## spectrum-error-model.h (module 'spectrum'): void ns3::SpectrumErrorModel::EvaluateChunk(ns3::SpectrumValue const & sinr, ns3::Time duration) [member function] cls.add_method('EvaluateChunk', 'void', [param('ns3::SpectrumValue const &', 'sinr'), param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## spectrum-error-model.h (module 'spectrum'): bool ns3::SpectrumErrorModel::IsRxCorrect() [member function] cls.add_method('IsRxCorrect', 'bool', [], is_pure_virtual=True, is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): void ns3::SpectrumErrorModel::StartRx(ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')], is_pure_virtual=True, is_virtual=True) return def register_Ns3SpectrumInterference_methods(root_module, cls): ## spectrum-interference.h (module 'spectrum'): ns3::SpectrumInterference::SpectrumInterference(ns3::SpectrumInterference const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumInterference const &', 'arg0')]) ## spectrum-interference.h (module 'spectrum'): ns3::SpectrumInterference::SpectrumInterference() [constructor] cls.add_constructor([]) ## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::AbortRx() [member function] cls.add_method('AbortRx', 'void', []) ## spectrum-interference.h (module 'spectrum'): void ns3::SpectrumInterference::AddSignal(ns3::Ptr<ns3::SpectrumValue const> spd, ns3::Time const duration) [member function] cls.add_method('AddSignal', 'void', [param('ns3::Ptr< ns3::SpectrumValue const >', 'spd'), param('ns3::Time const', 'duration')]) ## spectrum-interference.h (module 'spectrum'): bool ns3::SpectrumInterference::EndRx() [member function] cls.add_method('EndRx', 'bool', []) ## spectrum-interference.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumInterference::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## 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) ## spectrum-model.h (module 'spectrum'): bool ns3::SpectrumModel::IsOrthogonal(ns3::SpectrumModel const & other) const [member function] cls.add_method('IsOrthogonal', 'bool', [param('ns3::SpectrumModel const &', 'other')], is_const=True) return def register_Ns3SpectrumPhy_methods(root_module, cls): ## spectrum-phy.h (module 'spectrum'): ns3::SpectrumPhy::SpectrumPhy() [constructor] cls.add_constructor([]) ## spectrum-phy.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'd')], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::SpectrumPhy::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'm')], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::SpectrumPhy::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::MobilityModel >', [], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::SpectrumPhy::GetRxSpectrumModel() const [member function] cls.add_method('GetRxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::SpectrumPhy::GetRxAntenna() [member function] cls.add_method('GetRxAntenna', 'ns3::Ptr< ns3::AntennaModel >', [], is_pure_virtual=True, is_virtual=True) ## spectrum-phy.h (module 'spectrum'): void ns3::SpectrumPhy::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_pure_virtual=True, is_virtual=True) return def register_Ns3SpectrumPropagationLossModel_methods(root_module, cls): ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::SpectrumPropagationLossModel::SpectrumPropagationLossModel(ns3::SpectrumPropagationLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SpectrumPropagationLossModel const &', 'arg0')]) ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::SpectrumPropagationLossModel::SpectrumPropagationLossModel() [constructor] cls.add_constructor([]) ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumPropagationLossModel::CalcRxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> txPsd, ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function] cls.add_method('CalcRxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('ns3::Ptr< ns3::SpectrumValue const >', 'txPsd'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')], is_const=True) ## spectrum-propagation-loss-model.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## spectrum-propagation-loss-model.h (module 'spectrum'): void ns3::SpectrumPropagationLossModel::SetNext(ns3::Ptr<ns3::SpectrumPropagationLossModel> next) [member function] cls.add_method('SetNext', 'void', [param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'next')]) ## spectrum-propagation-loss-model.h (module 'spectrum'): void ns3::SpectrumPropagationLossModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## spectrum-propagation-loss-model.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::SpectrumPropagationLossModel::DoCalcRxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> txPsd, ns3::Ptr<const ns3::MobilityModel> a, ns3::Ptr<const ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPowerSpectralDensity', 'ns3::Ptr< ns3::SpectrumValue >', [param('ns3::Ptr< ns3::SpectrumValue const >', 'txPsd'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3SpectrumSignalParameters_methods(root_module, cls): ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::SpectrumSignalParameters() [constructor] cls.add_constructor([]) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::SpectrumSignalParameters(ns3::SpectrumSignalParameters const & p) [copy constructor] cls.add_constructor([param('ns3::SpectrumSignalParameters const &', 'p')]) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumSignalParameters> ns3::SpectrumSignalParameters::Copy() [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::SpectrumSignalParameters >', [], is_virtual=True) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::duration [variable] cls.add_instance_attribute('duration', 'ns3::Time', is_const=False) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::psd [variable] cls.add_instance_attribute('psd', 'ns3::Ptr< ns3::SpectrumValue >', is_const=False) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::txAntenna [variable] cls.add_instance_attribute('txAntenna', 'ns3::Ptr< ns3::AntennaModel >', is_const=False) ## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters::txPhy [variable] cls.add_instance_attribute('txPhy', 'ns3::Ptr< ns3::SpectrumPhy >', is_const=False) return def register_Ns3SpectrumValue_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', u'right')) cls.add_binary_numeric_operator('*', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('-', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('double', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::SpectrumValue'], root_module['ns3::SpectrumValue'], param('ns3::SpectrumValue const &', u'right')) cls.add_output_stream_operator() cls.add_inplace_numeric_operator('*=', param('ns3::SpectrumValue const &', u'right')) cls.add_inplace_numeric_operator('*=', param('double', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::SpectrumValue const &', u'right')) cls.add_inplace_numeric_operator('+=', param('double', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::SpectrumValue const &', u'right')) cls.add_inplace_numeric_operator('-=', param('double', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::SpectrumValue const &', u'right')) cls.add_inplace_numeric_operator('/=', param('double', u'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_Ns3ThreeLogDistancePropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::ThreeLogDistancePropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::ThreeLogDistancePropagationLossModel::ThreeLogDistancePropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): double ns3::ThreeLogDistancePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::ThreeLogDistancePropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TriangularRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3TvSpectrumTransmitter_methods(root_module, cls): ## tv-spectrum-transmitter.h (module 'spectrum'): ns3::TvSpectrumTransmitter::TvSpectrumTransmitter() [constructor] cls.add_constructor([]) ## tv-spectrum-transmitter.h (module 'spectrum'): static ns3::TypeId ns3::TvSpectrumTransmitter::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tv-spectrum-transmitter.h (module 'spectrum'): void ns3::TvSpectrumTransmitter::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): void ns3::TvSpectrumTransmitter::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'm')], is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): void ns3::TvSpectrumTransmitter::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'd')], is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::TvSpectrumTransmitter::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::MobilityModel >', [], is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::TvSpectrumTransmitter::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True, is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::TvSpectrumTransmitter::GetRxSpectrumModel() const [member function] cls.add_method('GetRxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_const=True, is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::TvSpectrumTransmitter::GetRxAntenna() [member function] cls.add_method('GetRxAntenna', 'ns3::Ptr< ns3::AntennaModel >', [], is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): void ns3::TvSpectrumTransmitter::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumChannel> ns3::TvSpectrumTransmitter::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::SpectrumChannel >', [], is_const=True) ## tv-spectrum-transmitter.h (module 'spectrum'): void ns3::TvSpectrumTransmitter::CreateTvPsd() [member function] cls.add_method('CreateTvPsd', 'void', [], is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::TvSpectrumTransmitter::GetTxPsd() const [member function] cls.add_method('GetTxPsd', 'ns3::Ptr< ns3::SpectrumValue >', [], is_const=True) ## tv-spectrum-transmitter.h (module 'spectrum'): void ns3::TvSpectrumTransmitter::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): void ns3::TvSpectrumTransmitter::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## tv-spectrum-transmitter.h (module 'spectrum'): void ns3::TvSpectrumTransmitter::SetupTx() [member function] cls.add_method('SetupTx', 'void', [], visibility='private', is_virtual=True) return def register_Ns3TwoRayGroundPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::TwoRayGroundPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::TwoRayGroundPropagationLossModel::TwoRayGroundPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetFrequency(double frequency) [member function] cls.add_method('SetFrequency', 'void', [param('double', 'frequency')]) ## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetSystemLoss(double systemLoss) [member function] cls.add_method('SetSystemLoss', 'void', [param('double', 'systemLoss')]) ## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetMinDistance(double minDistance) [member function] cls.add_method('SetMinDistance', 'void', [param('double', 'minDistance')]) ## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetMinDistance() const [member function] cls.add_method('GetMinDistance', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetFrequency() const [member function] cls.add_method('GetFrequency', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetSystemLoss() const [member function] cls.add_method('GetSystemLoss', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetHeightAboveZ(double heightAboveZ) [member function] cls.add_method('SetHeightAboveZ', 'void', [param('double', 'heightAboveZ')]) ## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::TwoRayGroundPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WaveformGenerator_methods(root_module, cls): ## waveform-generator.h (module 'spectrum'): ns3::WaveformGenerator::WaveformGenerator() [constructor] cls.add_constructor([]) ## waveform-generator.h (module 'spectrum'): static ns3::TypeId ns3::WaveformGenerator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'm')], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'd')], is_virtual=True) ## waveform-generator.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::WaveformGenerator::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::MobilityModel >', [], is_virtual=True) ## waveform-generator.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::WaveformGenerator::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True, is_virtual=True) ## waveform-generator.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::WaveformGenerator::GetRxSpectrumModel() const [member function] cls.add_method('GetRxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_const=True, is_virtual=True) ## waveform-generator.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::WaveformGenerator::GetRxAntenna() [member function] cls.add_method('GetRxAntenna', 'ns3::Ptr< ns3::AntennaModel >', [], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetTxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> txs) [member function] cls.add_method('SetTxPowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'txs')]) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetPeriod(ns3::Time period) [member function] cls.add_method('SetPeriod', 'void', [param('ns3::Time', 'period')]) ## waveform-generator.h (module 'spectrum'): ns3::Time ns3::WaveformGenerator::GetPeriod() const [member function] cls.add_method('GetPeriod', 'ns3::Time', [], is_const=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetDutyCycle(double value) [member function] cls.add_method('SetDutyCycle', 'void', [param('double', 'value')]) ## waveform-generator.h (module 'spectrum'): double ns3::WaveformGenerator::GetDutyCycle() const [member function] cls.add_method('GetDutyCycle', 'double', [], is_const=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::SetAntenna(ns3::Ptr<ns3::AntennaModel> a) [member function] cls.add_method('SetAntenna', 'void', [param('ns3::Ptr< ns3::AntennaModel >', 'a')]) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## waveform-generator.h (module 'spectrum'): void ns3::WaveformGenerator::GenerateWaveform() [member function] cls.add_method('GenerateWaveform', 'void', [], visibility='private', is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3AlohaNoackMacHeader_methods(root_module, cls): ## aloha-noack-mac-header.h (module 'spectrum'): ns3::AlohaNoackMacHeader::AlohaNoackMacHeader() [constructor] cls.add_constructor([]) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::AlohaNoackMacHeader::AlohaNoackMacHeader(ns3::AlohaNoackMacHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::AlohaNoackMacHeader const &', 'arg0')]) ## aloha-noack-mac-header.h (module 'spectrum'): uint32_t ns3::AlohaNoackMacHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::Mac48Address ns3::AlohaNoackMacHeader::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Mac48Address', [], is_const=True) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::TypeId ns3::AlohaNoackMacHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): uint32_t ns3::AlohaNoackMacHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): ns3::Mac48Address ns3::AlohaNoackMacHeader::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Mac48Address', [], is_const=True) ## aloha-noack-mac-header.h (module 'spectrum'): static ns3::TypeId ns3::AlohaNoackMacHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aloha-noack-mac-header.h (module 'spectrum'): void ns3::AlohaNoackMacHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): void ns3::AlohaNoackMacHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## aloha-noack-mac-header.h (module 'spectrum'): void ns3::AlohaNoackMacHeader::SetDestination(ns3::Mac48Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Mac48Address', 'destination')]) ## aloha-noack-mac-header.h (module 'spectrum'): void ns3::AlohaNoackMacHeader::SetSource(ns3::Mac48Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Mac48Address', 'source')]) return def register_Ns3AntennaModel_methods(root_module, cls): ## antenna-model.h (module 'antenna'): ns3::AntennaModel::AntennaModel(ns3::AntennaModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::AntennaModel const &', 'arg0')]) ## antenna-model.h (module 'antenna'): ns3::AntennaModel::AntennaModel() [constructor] cls.add_constructor([]) ## antenna-model.h (module 'antenna'): double ns3::AntennaModel::GetGainDb(ns3::Angles a) [member function] cls.add_method('GetGainDb', 'double', [param('ns3::Angles', 'a')], is_pure_virtual=True, is_virtual=True) ## antenna-model.h (module 'antenna'): static ns3::TypeId ns3::AntennaModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3BooleanChecker_methods(root_module, cls): ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')]) return def register_Ns3BooleanValue_methods(root_module, cls): cls.add_output_stream_operator() ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor] cls.add_constructor([param('bool', 'value')]) ## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function] cls.add_method('Get', 'bool', [], is_const=True) ## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function] cls.add_method('Set', 'void', [param('bool', 'value')]) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3ConstantRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function] cls.add_method('GetConstant', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function] cls.add_method('GetValue', 'double', [param('double', 'constant')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'constant')]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ConstantSpectrumPropagationLossModel_methods(root_module, cls): ## constant-spectrum-propagation-loss.h (module 'spectrum'): ns3::ConstantSpectrumPropagationLossModel::ConstantSpectrumPropagationLossModel(ns3::ConstantSpectrumPropagationLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantSpectrumPropagationLossModel const &', 'arg0')]) ## constant-spectrum-propagation-loss.h (module 'spectrum'): ns3::ConstantSpectrumPropagationLossModel::ConstantSpectrumPropagationLossModel() [constructor] cls.add_constructor([]) ## constant-spectrum-propagation-loss.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::ConstantSpectrumPropagationLossModel::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, is_virtual=True) ## constant-spectrum-propagation-loss.h (module 'spectrum'): double ns3::ConstantSpectrumPropagationLossModel::GetLossDb() const [member function] cls.add_method('GetLossDb', 'double', [], is_const=True) ## constant-spectrum-propagation-loss.h (module 'spectrum'): static ns3::TypeId ns3::ConstantSpectrumPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## constant-spectrum-propagation-loss.h (module 'spectrum'): void ns3::ConstantSpectrumPropagationLossModel::SetLossDb(double lossDb) [member function] cls.add_method('SetLossDb', 'void', [param('double', 'lossDb')]) return def register_Ns3ConstantSpeedPropagationDelayModel_methods(root_module, cls): ## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel::ConstantSpeedPropagationDelayModel(ns3::ConstantSpeedPropagationDelayModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantSpeedPropagationDelayModel const &', 'arg0')]) ## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel::ConstantSpeedPropagationDelayModel() [constructor] cls.add_constructor([]) ## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::ConstantSpeedPropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('GetDelay', 'ns3::Time', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, is_virtual=True) ## propagation-delay-model.h (module 'propagation'): double ns3::ConstantSpeedPropagationDelayModel::GetSpeed() const [member function] cls.add_method('GetSpeed', 'double', [], is_const=True) ## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::ConstantSpeedPropagationDelayModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-delay-model.h (module 'propagation'): void ns3::ConstantSpeedPropagationDelayModel::SetSpeed(double speed) [member function] cls.add_method('SetSpeed', 'void', [param('double', 'speed')]) ## propagation-delay-model.h (module 'propagation'): int64_t ns3::ConstantSpeedPropagationDelayModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3DataRateChecker_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')]) return def register_Ns3DataRateValue_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor] cls.add_constructor([param('ns3::DataRate const &', 'value')]) ## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): bool ns3::DataRateValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function] cls.add_method('Get', 'ns3::DataRate', [], is_const=True) ## data-rate.h (module 'network'): std::string ns3::DataRateValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function] cls.add_method('Set', 'void', [param('ns3::DataRate const &', 'value')]) return def register_Ns3DeterministicRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function] cls.add_method('SetValueArray', 'void', [param('double *', 'values'), param('uint64_t', 'length')]) ## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3DoubleValue_methods(root_module, cls): ## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor] cls.add_constructor([]) ## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')]) ## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor] cls.add_constructor([param('double const &', 'value')]) ## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## double.h (module 'core'): bool ns3::DoubleValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function] cls.add_method('Get', 'double', [], is_const=True) ## double.h (module 'core'): std::string ns3::DoubleValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function] cls.add_method('Set', 'void', [param('double const &', 'value')]) return def register_Ns3EmpiricalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function] cls.add_method('CDF', 'void', [param('double', 'v'), param('double', 'c')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double c1, double c2, double v1, double v2, double r) [member function] cls.add_method('Interpolate', 'double', [param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')], visibility='private', is_virtual=True) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function] cls.add_method('Validate', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EmptyAttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EnumChecker_methods(root_module, cls): ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')]) ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor] cls.add_constructor([]) ## enum.h (module 'core'): void ns3::EnumChecker::Add(int value, std::string name) [member function] cls.add_method('Add', 'void', [param('int', 'value'), param('std::string', 'name')]) ## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int value, std::string name) [member function] cls.add_method('AddDefault', 'void', [param('int', 'value'), param('std::string', 'name')]) ## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')], is_const=True, is_virtual=True) ## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EnumValue_methods(root_module, cls): ## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnumValue const &', 'arg0')]) ## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor] cls.add_constructor([]) ## enum.h (module 'core'): ns3::EnumValue::EnumValue(int value) [constructor] cls.add_constructor([param('int', 'value')]) ## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function] cls.add_method('Get', 'int', [], is_const=True) ## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## enum.h (module 'core'): void ns3::EnumValue::Set(int value) [member function] cls.add_method('Set', 'void', [param('int', 'value')]) return def register_Ns3ErlangRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function] cls.add_method('GetK', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function] cls.add_method('GetLambda', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'k'), param('double', 'lambda')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'k'), param('uint32_t', 'lambda')]) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3ExponentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3FixedRssLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::FixedRssLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::FixedRssLossModel::FixedRssLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::FixedRssLossModel::SetRss(double rss) [member function] cls.add_method('SetRss', 'void', [param('double', 'rss')]) ## propagation-loss-model.h (module 'propagation'): double ns3::FixedRssLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::FixedRssLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3FriisPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::FriisPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::FriisPropagationLossModel::FriisPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetFrequency(double frequency) [member function] cls.add_method('SetFrequency', 'void', [param('double', 'frequency')]) ## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetSystemLoss(double systemLoss) [member function] cls.add_method('SetSystemLoss', 'void', [param('double', 'systemLoss')]) ## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetMinLoss(double minLoss) [member function] cls.add_method('SetMinLoss', 'void', [param('double', 'minLoss')]) ## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetMinLoss() const [member function] cls.add_method('GetMinLoss', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetFrequency() const [member function] cls.add_method('GetFrequency', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetSystemLoss() const [member function] cls.add_method('GetSystemLoss', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::FriisPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3FriisSpectrumPropagationLossModel_methods(root_module, cls): ## friis-spectrum-propagation-loss.h (module 'spectrum'): ns3::FriisSpectrumPropagationLossModel::FriisSpectrumPropagationLossModel(ns3::FriisSpectrumPropagationLossModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::FriisSpectrumPropagationLossModel const &', 'arg0')]) ## friis-spectrum-propagation-loss.h (module 'spectrum'): ns3::FriisSpectrumPropagationLossModel::FriisSpectrumPropagationLossModel() [constructor] cls.add_constructor([]) ## friis-spectrum-propagation-loss.h (module 'spectrum'): double ns3::FriisSpectrumPropagationLossModel::CalculateLoss(double f, double d) const [member function] cls.add_method('CalculateLoss', 'double', [param('double', 'f'), param('double', 'd')], is_const=True) ## friis-spectrum-propagation-loss.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumValue> ns3::FriisSpectrumPropagationLossModel::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, is_virtual=True) ## friis-spectrum-propagation-loss.h (module 'spectrum'): static ns3::TypeId ns3::FriisSpectrumPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3GammaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function] cls.add_method('GetBeta', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha'), param('double', 'beta')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha'), param('uint32_t', 'beta')]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3HalfDuplexIdealPhy_methods(root_module, cls): ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::HalfDuplexIdealPhy::HalfDuplexIdealPhy() [constructor] cls.add_constructor([]) ## half-duplex-ideal-phy.h (module 'spectrum'): static ns3::TypeId ns3::HalfDuplexIdealPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'm')], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'd')], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::HalfDuplexIdealPhy::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::MobilityModel >', [], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::HalfDuplexIdealPhy::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True, is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::HalfDuplexIdealPhy::GetRxSpectrumModel() const [member function] cls.add_method('GetRxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_const=True, is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::HalfDuplexIdealPhy::GetRxAntenna() [member function] cls.add_method('GetRxAntenna', 'ns3::Ptr< ns3::AntennaModel >', [], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetTxPowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue> txPsd) [member function] cls.add_method('SetTxPowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue >', 'txPsd')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetNoisePowerSpectralDensity(ns3::Ptr<ns3::SpectrumValue const> noisePsd) [member function] cls.add_method('SetNoisePowerSpectralDensity', 'void', [param('ns3::Ptr< ns3::SpectrumValue const >', 'noisePsd')]) ## half-duplex-ideal-phy.h (module 'spectrum'): bool ns3::HalfDuplexIdealPhy::StartTx(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('StartTx', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetRate(ns3::DataRate rate) [member function] cls.add_method('SetRate', 'void', [param('ns3::DataRate', 'rate')]) ## half-duplex-ideal-phy.h (module 'spectrum'): ns3::DataRate ns3::HalfDuplexIdealPhy::GetRate() const [member function] cls.add_method('GetRate', 'ns3::DataRate', [], is_const=True) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetGenericPhyTxEndCallback(ns3::GenericPhyTxEndCallback c) [member function] cls.add_method('SetGenericPhyTxEndCallback', 'void', [param('ns3::GenericPhyTxEndCallback', 'c')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetGenericPhyRxStartCallback(ns3::GenericPhyRxStartCallback c) [member function] cls.add_method('SetGenericPhyRxStartCallback', 'void', [param('ns3::GenericPhyRxStartCallback', 'c')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetGenericPhyRxEndErrorCallback(ns3::GenericPhyRxEndErrorCallback c) [member function] cls.add_method('SetGenericPhyRxEndErrorCallback', 'void', [param('ns3::GenericPhyRxEndErrorCallback', 'c')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetGenericPhyRxEndOkCallback(ns3::GenericPhyRxEndOkCallback c) [member function] cls.add_method('SetGenericPhyRxEndOkCallback', 'void', [param('ns3::GenericPhyRxEndOkCallback', 'c')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::SetAntenna(ns3::Ptr<ns3::AntennaModel> a) [member function] cls.add_method('SetAntenna', 'void', [param('ns3::Ptr< ns3::AntennaModel >', 'a')]) ## half-duplex-ideal-phy.h (module 'spectrum'): void ns3::HalfDuplexIdealPhy::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3HalfDuplexIdealPhySignalParameters_methods(root_module, cls): ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::HalfDuplexIdealPhySignalParameters::HalfDuplexIdealPhySignalParameters() [constructor] cls.add_constructor([]) ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::HalfDuplexIdealPhySignalParameters::HalfDuplexIdealPhySignalParameters(ns3::HalfDuplexIdealPhySignalParameters const & p) [copy constructor] cls.add_constructor([param('ns3::HalfDuplexIdealPhySignalParameters const &', 'p')]) ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumSignalParameters> ns3::HalfDuplexIdealPhySignalParameters::Copy() [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::SpectrumSignalParameters >', [], is_virtual=True) ## half-duplex-ideal-phy-signal-parameters.h (module 'spectrum'): ns3::HalfDuplexIdealPhySignalParameters::data [variable] cls.add_instance_attribute('data', 'ns3::Ptr< ns3::Packet >', is_const=False) return def register_Ns3IntegerValue_methods(root_module, cls): ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor] cls.add_constructor([]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor] cls.add_constructor([param('int64_t const &', 'value')]) ## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## integer.h (module 'core'): bool ns3::IntegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function] cls.add_method('Get', 'int64_t', [], is_const=True) ## integer.h (module 'core'): std::string ns3::IntegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function] cls.add_method('Set', 'void', [param('int64_t const &', 'value')]) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3LogDistancePropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::LogDistancePropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::LogDistancePropagationLossModel::LogDistancePropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::LogDistancePropagationLossModel::SetPathLossExponent(double n) [member function] cls.add_method('SetPathLossExponent', 'void', [param('double', 'n')]) ## propagation-loss-model.h (module 'propagation'): double ns3::LogDistancePropagationLossModel::GetPathLossExponent() const [member function] cls.add_method('GetPathLossExponent', 'double', [], is_const=True) ## propagation-loss-model.h (module 'propagation'): void ns3::LogDistancePropagationLossModel::SetReference(double referenceDistance, double referenceLoss) [member function] cls.add_method('SetReference', 'void', [param('double', 'referenceDistance'), param('double', 'referenceLoss')]) ## propagation-loss-model.h (module 'propagation'): double ns3::LogDistancePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::LogDistancePropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3LogNormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function] cls.add_method('GetMu', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function] cls.add_method('GetSigma', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function] cls.add_method('GetValue', 'double', [param('double', 'mu'), param('double', 'sigma')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mu'), param('uint32_t', 'sigma')]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3Mac16AddressChecker_methods(root_module, cls): ## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker() [constructor] cls.add_constructor([]) ## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker(ns3::Mac16AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac16AddressChecker const &', 'arg0')]) return def register_Ns3Mac16AddressValue_methods(root_module, cls): ## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue() [constructor] cls.add_constructor([]) ## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac16AddressValue const &', 'arg0')]) ## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16Address const & value) [constructor] cls.add_constructor([param('ns3::Mac16Address const &', 'value')]) ## mac16-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac16AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac16-address.h (module 'network'): bool ns3::Mac16AddressValue::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) ## mac16-address.h (module 'network'): ns3::Mac16Address ns3::Mac16AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac16Address', [], is_const=True) ## mac16-address.h (module 'network'): std::string ns3::Mac16AddressValue::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) ## mac16-address.h (module 'network'): void ns3::Mac16AddressValue::Set(ns3::Mac16Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac16Address const &', 'value')]) 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_Ns3Mac64AddressChecker_methods(root_module, cls): ## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker() [constructor] cls.add_constructor([]) ## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker(ns3::Mac64AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac64AddressChecker const &', 'arg0')]) return def register_Ns3Mac64AddressValue_methods(root_module, cls): ## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue() [constructor] cls.add_constructor([]) ## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac64AddressValue const &', 'arg0')]) ## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64Address const & value) [constructor] cls.add_constructor([param('ns3::Mac64Address const &', 'value')]) ## mac64-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac64AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac64-address.h (module 'network'): bool ns3::Mac64AddressValue::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) ## mac64-address.h (module 'network'): ns3::Mac64Address ns3::Mac64AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac64Address', [], is_const=True) ## mac64-address.h (module 'network'): std::string ns3::Mac64AddressValue::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) ## mac64-address.h (module 'network'): void ns3::Mac64AddressValue::Set(ns3::Mac64Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac64Address const &', 'value')]) return def register_Ns3MatrixPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::MatrixPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::MatrixPropagationLossModel::MatrixPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): void ns3::MatrixPropagationLossModel::SetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, double loss, bool symmetric=true) [member function] cls.add_method('SetLoss', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('double', 'loss'), param('bool', 'symmetric', default_value='true')]) ## propagation-loss-model.h (module 'propagation'): void ns3::MatrixPropagationLossModel::SetDefaultLoss(double defaultLoss) [member function] cls.add_method('SetDefaultLoss', 'void', [param('double', 'defaultLoss')]) ## propagation-loss-model.h (module 'propagation'): double ns3::MatrixPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::MatrixPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], visibility='private', is_virtual=True) return def register_Ns3MobilityModel_methods(root_module, cls): ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel(ns3::MobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::MobilityModel const &', 'arg0')]) ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel() [constructor] cls.add_constructor([]) ## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr<const ns3::MobilityModel> position) const [member function] cls.add_method('GetDistanceFrom', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'position')], is_const=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetPosition() const [member function] cls.add_method('GetPosition', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetRelativeSpeed(ns3::Ptr<const ns3::MobilityModel> other) const [member function] cls.add_method('GetRelativeSpeed', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'other')], is_const=True) ## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function] cls.add_method('GetVelocity', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function] cls.add_method('SetPosition', 'void', [param('ns3::Vector const &', 'position')]) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function] cls.add_method('NotifyCourseChange', 'void', [], is_const=True, visibility='protected') ## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::DoAssignStreams(int64_t start) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'start')], visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3NakagamiPropagationLossModel_methods(root_module, cls): ## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::NakagamiPropagationLossModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## propagation-loss-model.h (module 'propagation'): ns3::NakagamiPropagationLossModel::NakagamiPropagationLossModel() [constructor] cls.add_constructor([]) ## propagation-loss-model.h (module 'propagation'): double ns3::NakagamiPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function] cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')], is_const=True, visibility='private', is_virtual=True) ## propagation-loss-model.h (module 'propagation'): int64_t ns3::NakagamiPropagationLossModel::DoAssignStreams(int64_t stream) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'stream')], 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'): ns3::Time ns3::Node::GetLocalTime() const [member function] cls.add_method('GetLocalTime', 'ns3::Time', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NonCommunicatingNetDevice_methods(root_module, cls): ## non-communicating-net-device.h (module 'spectrum'): ns3::NonCommunicatingNetDevice::NonCommunicatingNetDevice(ns3::NonCommunicatingNetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NonCommunicatingNetDevice const &', 'arg0')]) ## non-communicating-net-device.h (module 'spectrum'): ns3::NonCommunicatingNetDevice::NonCommunicatingNetDevice() [constructor] cls.add_constructor([]) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): ns3::Address ns3::NonCommunicatingNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Address ns3::NonCommunicatingNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Channel> ns3::NonCommunicatingNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): uint32_t ns3::NonCommunicatingNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): uint16_t ns3::NonCommunicatingNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Address ns3::NonCommunicatingNetDevice::GetMulticast(ns3::Ipv4Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Address ns3::NonCommunicatingNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Node> ns3::NonCommunicatingNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Object> ns3::NonCommunicatingNetDevice::GetPhy() const [member function] cls.add_method('GetPhy', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## non-communicating-net-device.h (module 'spectrum'): static ns3::TypeId ns3::NonCommunicatingNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetChannel(ns3::Ptr<ns3::Channel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::Channel >', 'c')]) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::SetPhy(ns3::Ptr<ns3::Object> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::Object >', 'phy')]) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::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) ## non-communicating-net-device.h (module 'spectrum'): bool ns3::NonCommunicatingNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## non-communicating-net-device.h (module 'spectrum'): void ns3::NonCommunicatingNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3NormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable] cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function] cls.add_method('GetVariance', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) ## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function] cls.add_method('ToString', 'std::string', [], is_const=True) return def register_Ns3ParetoRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], deprecated=True, is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ShannonSpectrumErrorModel_methods(root_module, cls): ## spectrum-error-model.h (module 'spectrum'): ns3::ShannonSpectrumErrorModel::ShannonSpectrumErrorModel() [constructor] cls.add_constructor([]) ## spectrum-error-model.h (module 'spectrum'): ns3::ShannonSpectrumErrorModel::ShannonSpectrumErrorModel(ns3::ShannonSpectrumErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ShannonSpectrumErrorModel const &', 'arg0')]) ## spectrum-error-model.h (module 'spectrum'): void ns3::ShannonSpectrumErrorModel::EvaluateChunk(ns3::SpectrumValue const & sinr, ns3::Time duration) [member function] cls.add_method('EvaluateChunk', 'void', [param('ns3::SpectrumValue const &', 'sinr'), param('ns3::Time', 'duration')], is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): static ns3::TypeId ns3::ShannonSpectrumErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## spectrum-error-model.h (module 'spectrum'): bool ns3::ShannonSpectrumErrorModel::IsRxCorrect() [member function] cls.add_method('IsRxCorrect', 'bool', [], is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): void ns3::ShannonSpectrumErrorModel::StartRx(ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')], is_virtual=True) ## spectrum-error-model.h (module 'spectrum'): void ns3::ShannonSpectrumErrorModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3SpectrumAnalyzer_methods(root_module, cls): ## spectrum-analyzer.h (module 'spectrum'): ns3::SpectrumAnalyzer::SpectrumAnalyzer() [constructor] cls.add_constructor([]) ## spectrum-analyzer.h (module 'spectrum'): static ns3::TypeId ns3::SpectrumAnalyzer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetChannel(ns3::Ptr<ns3::SpectrumChannel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetMobility(ns3::Ptr<ns3::MobilityModel> m) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'm')], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetDevice(ns3::Ptr<ns3::NetDevice> d) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'd')], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): ns3::Ptr<ns3::MobilityModel> ns3::SpectrumAnalyzer::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::MobilityModel >', [], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::SpectrumAnalyzer::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True, is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumModel const> ns3::SpectrumAnalyzer::GetRxSpectrumModel() const [member function] cls.add_method('GetRxSpectrumModel', 'ns3::Ptr< ns3::SpectrumModel const >', [], is_const=True, is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): ns3::Ptr<ns3::AntennaModel> ns3::SpectrumAnalyzer::GetRxAntenna() [member function] cls.add_method('GetRxAntenna', 'ns3::Ptr< ns3::AntennaModel >', [], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetRxSpectrumModel(ns3::Ptr<ns3::SpectrumModel> m) [member function] cls.add_method('SetRxSpectrumModel', 'void', [param('ns3::Ptr< ns3::SpectrumModel >', 'm')]) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::SetAntenna(ns3::Ptr<ns3::AntennaModel> a) [member function] cls.add_method('SetAntenna', 'void', [param('ns3::Ptr< ns3::AntennaModel >', 'a')]) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## spectrum-analyzer.h (module 'spectrum'): void ns3::SpectrumAnalyzer::GenerateReport() [member function] cls.add_method('GenerateReport', 'void', [], visibility='private', is_virtual=True) 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_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3UintegerValue_methods(root_module, cls): ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor] cls.add_constructor([]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor] cls.add_constructor([param('uint64_t const &', 'value')]) ## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function] cls.add_method('Get', 'uint64_t', [], is_const=True) ## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function] cls.add_method('Set', 'void', [param('uint64_t const &', 'value')]) return def register_Ns3Vector2DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')]) return def register_Ns3Vector2DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor] cls.add_constructor([param('ns3::Vector2D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector2DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector2DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector2D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector2DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector2D const &', 'value')]) return def register_Ns3Vector3DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')]) return def register_Ns3Vector3DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor] cls.add_constructor([param('ns3::Vector3D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector3DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector3DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector3D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector3DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector3D const &', 'value')]) return def register_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_Ns3AlohaNoackNetDevice_methods(root_module, cls): ## aloha-noack-net-device.h (module 'spectrum'): ns3::AlohaNoackNetDevice::AlohaNoackNetDevice(ns3::AlohaNoackNetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::AlohaNoackNetDevice const &', 'arg0')]) ## aloha-noack-net-device.h (module 'spectrum'): ns3::AlohaNoackNetDevice::AlohaNoackNetDevice() [constructor] cls.add_constructor([]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Address ns3::AlohaNoackNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Address ns3::AlohaNoackNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Channel> ns3::AlohaNoackNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): uint32_t ns3::AlohaNoackNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): uint16_t ns3::AlohaNoackNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Address ns3::AlohaNoackNetDevice::GetMulticast(ns3::Ipv4Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Address ns3::AlohaNoackNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Node> ns3::AlohaNoackNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): ns3::Ptr<ns3::Object> ns3::AlohaNoackNetDevice::GetPhy() const [member function] cls.add_method('GetPhy', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## aloha-noack-net-device.h (module 'spectrum'): static ns3::TypeId ns3::AlohaNoackNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::NotifyReceptionEndError() [member function] cls.add_method('NotifyReceptionEndError', 'void', []) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::NotifyReceptionEndOk(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('NotifyReceptionEndOk', 'void', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::NotifyReceptionStart() [member function] cls.add_method('NotifyReceptionStart', 'void', []) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::NotifyTransmissionEnd(ns3::Ptr<const ns3::Packet> arg0) [member function] cls.add_method('NotifyTransmissionEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'arg0')]) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetChannel(ns3::Ptr<ns3::Channel> c) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::Channel >', 'c')]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetGenericPhyTxStartCallback(ns3::GenericPhyTxStartCallback c) [member function] cls.add_method('SetGenericPhyTxStartCallback', 'void', [param('ns3::GenericPhyTxStartCallback', 'c')]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetPhy(ns3::Ptr<ns3::Object> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::Object >', 'phy')]) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::SetQueue(ns3::Ptr<ns3::Queue<ns3::Packet> > queue) [member function] cls.add_method('SetQueue', 'void', [param('ns3::Ptr< ns3::Queue< ns3::Packet > >', 'queue')], is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::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) ## aloha-noack-net-device.h (module 'spectrum'): bool ns3::AlohaNoackNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## aloha-noack-net-device.h (module 'spectrum'): void ns3::AlohaNoackNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3MultiModelSpectrumChannel_methods(root_module, cls): ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::MultiModelSpectrumChannel::MultiModelSpectrumChannel(ns3::MultiModelSpectrumChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::MultiModelSpectrumChannel const &', 'arg0')]) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::MultiModelSpectrumChannel::MultiModelSpectrumChannel() [constructor] cls.add_constructor([]) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::AddPropagationLossModel(ns3::Ptr<ns3::PropagationLossModel> loss) [member function] cls.add_method('AddPropagationLossModel', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'loss')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::AddRx(ns3::Ptr<ns3::SpectrumPhy> phy) [member function] cls.add_method('AddRx', 'void', [param('ns3::Ptr< ns3::SpectrumPhy >', 'phy')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::AddSpectrumPropagationLossModel(ns3::Ptr<ns3::SpectrumPropagationLossModel> loss) [member function] cls.add_method('AddSpectrumPropagationLossModel', 'void', [param('ns3::Ptr< ns3::SpectrumPropagationLossModel >', 'loss')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::Ptr<ns3::NetDevice> ns3::MultiModelSpectrumChannel::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) ## multi-model-spectrum-channel.h (module 'spectrum'): uint32_t ns3::MultiModelSpectrumChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): ns3::Ptr<ns3::SpectrumPropagationLossModel> ns3::MultiModelSpectrumChannel::GetSpectrumPropagationLossModel() [member function] cls.add_method('GetSpectrumPropagationLossModel', 'ns3::Ptr< ns3::SpectrumPropagationLossModel >', [], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): static ns3::TypeId ns3::MultiModelSpectrumChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::SetPropagationDelayModel(ns3::Ptr<ns3::PropagationDelayModel> delay) [member function] cls.add_method('SetPropagationDelayModel', 'void', [param('ns3::Ptr< ns3::PropagationDelayModel >', 'delay')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::StartTx(ns3::Ptr<ns3::SpectrumSignalParameters> params) [member function] cls.add_method('StartTx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params')], is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## multi-model-spectrum-channel.h (module 'spectrum'): void ns3::MultiModelSpectrumChannel::StartRx(ns3::Ptr<ns3::SpectrumSignalParameters> params, ns3::Ptr<ns3::SpectrumPhy> receiver) [member function] cls.add_method('StartRx', 'void', [param('ns3::Ptr< ns3::SpectrumSignalParameters >', 'params'), param('ns3::Ptr< ns3::SpectrumPhy >', 'receiver')], 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_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module ## spectrum-value.h (module 'spectrum'): extern double ns3::Integral(ns3::SpectrumValue const & arg) [free function] module.add_function('Integral', 'double', [param('ns3::SpectrumValue const &', 'arg')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Log(ns3::SpectrumValue const & arg) [free function] module.add_function('Log', 'ns3::SpectrumValue', [param('ns3::SpectrumValue const &', 'arg')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Log10(ns3::SpectrumValue const & arg) [free function] module.add_function('Log10', 'ns3::SpectrumValue', [param('ns3::SpectrumValue const &', 'arg')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Log2(ns3::SpectrumValue const & arg) [free function] module.add_function('Log2', 'ns3::SpectrumValue', [param('ns3::SpectrumValue const &', 'arg')]) ## spectrum-value.h (module 'spectrum'): extern double ns3::Norm(ns3::SpectrumValue const & x) [free function] module.add_function('Norm', 'double', [param('ns3::SpectrumValue const &', 'x')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Pow(ns3::SpectrumValue const & lhs, double rhs) [free function] module.add_function('Pow', 'ns3::SpectrumValue', [param('ns3::SpectrumValue const &', 'lhs'), param('double', 'rhs')]) ## spectrum-value.h (module 'spectrum'): extern ns3::SpectrumValue ns3::Pow(double lhs, ns3::SpectrumValue const & rhs) [free function] module.add_function('Pow', 'ns3::SpectrumValue', [param('double', 'lhs'), param('ns3::SpectrumValue const &', 'rhs')]) ## spectrum-value.h (module 'spectrum'): extern double ns3::Prod(ns3::SpectrumValue const & x) [free function] module.add_function('Prod', 'double', [param('ns3::SpectrumValue const &', 'x')]) ## spectrum-value.h (module 'spectrum'): extern double ns3::Sum(ns3::SpectrumValue const & x) [free function] module.add_function('Sum', 'double', [param('ns3::SpectrumValue const &', 'x')]) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module) register_functions_ns3_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_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def register_functions_ns3_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
mhaessig/servo
tests/wpt/css-tests/tools/pytest/_pytest/mark.py
168
11093
""" generic mechanism for marking and selecting python functions. """ import inspect class MarkerError(Exception): """Error in use of a pytest marker/attribute.""" def pytest_namespace(): return {'mark': MarkGenerator()} def pytest_addoption(parser): group = parser.getgroup("general") group._addoption( '-k', action="store", dest="keyword", default='', metavar="EXPRESSION", help="only run tests which match the given substring expression. " "An expression is a python evaluatable expression " "where all names are substring-matched against test names " "and their parent classes. Example: -k 'test_method or test " "other' matches all test functions and classes whose name " "contains 'test_method' or 'test_other'. " "Additionally keywords are matched to classes and functions " "containing extra names in their 'extra_keyword_matches' set, " "as well as functions which have names assigned directly to them." ) group._addoption( "-m", action="store", dest="markexpr", default="", metavar="MARKEXPR", help="only run tests matching given mark expression. " "example: -m 'mark1 and not mark2'." ) group.addoption( "--markers", action="store_true", help="show markers (builtin, plugin and per-project ones)." ) parser.addini("markers", "markers for test functions", 'linelist') def pytest_cmdline_main(config): import _pytest.config if config.option.markers: config._do_configure() tw = _pytest.config.create_terminal_writer(config) for line in config.getini("markers"): name, rest = line.split(":", 1) tw.write("@pytest.mark.%s:" % name, bold=True) tw.line(rest) tw.line() config._ensure_unconfigure() return 0 pytest_cmdline_main.tryfirst = True def pytest_collection_modifyitems(items, config): keywordexpr = config.option.keyword matchexpr = config.option.markexpr if not keywordexpr and not matchexpr: return # pytest used to allow "-" for negating # but today we just allow "-" at the beginning, use "not" instead # we probably remove "-" alltogether soon if keywordexpr.startswith("-"): keywordexpr = "not " + keywordexpr[1:] selectuntil = False if keywordexpr[-1:] == ":": selectuntil = True keywordexpr = keywordexpr[:-1] remaining = [] deselected = [] for colitem in items: if keywordexpr and not matchkeyword(colitem, keywordexpr): deselected.append(colitem) else: if selectuntil: keywordexpr = None if matchexpr: if not matchmark(colitem, matchexpr): deselected.append(colitem) continue remaining.append(colitem) if deselected: config.hook.pytest_deselected(items=deselected) items[:] = remaining class MarkMapping: """Provides a local mapping for markers where item access resolves to True if the marker is present. """ def __init__(self, keywords): mymarks = set() for key, value in keywords.items(): if isinstance(value, MarkInfo) or isinstance(value, MarkDecorator): mymarks.add(key) self._mymarks = mymarks def __getitem__(self, name): return name in self._mymarks class KeywordMapping: """Provides a local mapping for keywords. Given a list of names, map any substring of one of these names to True. """ def __init__(self, names): self._names = names def __getitem__(self, subname): for name in self._names: if subname in name: return True return False def matchmark(colitem, markexpr): """Tries to match on any marker names, attached to the given colitem.""" return eval(markexpr, {}, MarkMapping(colitem.keywords)) def matchkeyword(colitem, keywordexpr): """Tries to match given keyword expression to given collector item. Will match on the name of colitem, including the names of its parents. Only matches names of items which are either a :class:`Class` or a :class:`Function`. Additionally, matches on names in the 'extra_keyword_matches' set of any item, as well as names directly assigned to test functions. """ mapped_names = set() # Add the names of the current item and any parent items import pytest for item in colitem.listchain(): if not isinstance(item, pytest.Instance): mapped_names.add(item.name) # Add the names added as extra keywords to current or parent items for name in colitem.listextrakeywords(): mapped_names.add(name) # Add the names attached to the current function through direct assignment if hasattr(colitem, 'function'): for name in colitem.function.__dict__: mapped_names.add(name) mapping = KeywordMapping(mapped_names) if " " not in keywordexpr: # special case to allow for simple "-k pass" and "-k 1.3" return mapping[keywordexpr] elif keywordexpr.startswith("not ") and " " not in keywordexpr[4:]: return not mapping[keywordexpr[4:]] return eval(keywordexpr, {}, mapping) def pytest_configure(config): import pytest if config.option.strict: pytest.mark._config = config class MarkGenerator: """ Factory for :class:`MarkDecorator` objects - exposed as a ``pytest.mark`` singleton instance. Example:: import pytest @pytest.mark.slowtest def test_function(): pass will set a 'slowtest' :class:`MarkInfo` object on the ``test_function`` object. """ def __getattr__(self, name): if name[0] == "_": raise AttributeError("Marker name must NOT start with underscore") if hasattr(self, '_config'): self._check(name) return MarkDecorator(name) def _check(self, name): try: if name in self._markers: return except AttributeError: pass self._markers = l = set() for line in self._config.getini("markers"): beginning = line.split(":", 1) x = beginning[0].split("(", 1)[0] l.add(x) if name not in self._markers: raise AttributeError("%r not a registered marker" % (name,)) def istestfunc(func): return hasattr(func, "__call__") and \ getattr(func, "__name__", "<lambda>") != "<lambda>" class MarkDecorator: """ A decorator for test functions and test classes. When applied it will create :class:`MarkInfo` objects which may be :ref:`retrieved by hooks as item keywords <excontrolskip>`. MarkDecorator instances are often created like this:: mark1 = pytest.mark.NAME # simple MarkDecorator mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator and can then be applied as decorators to test functions:: @mark2 def test_function(): pass When a MarkDecorator instance is called it does the following: 1. If called with a single class as its only positional argument and no additional keyword arguments, it attaches itself to the class so it gets applied automatically to all test cases found in that class. 2. If called with a single function as its only positional argument and no additional keyword arguments, it attaches a MarkInfo object to the function, containing all the arguments already stored internally in the MarkDecorator. 3. When called in any other case, it performs a 'fake construction' call, i.e. it returns a new MarkDecorator instance with the original MarkDecorator's content updated with the arguments passed to this call. Note: The rules above prevent MarkDecorator objects from storing only a single function or class reference as their positional argument with no additional keyword or positional arguments. """ def __init__(self, name, args=None, kwargs=None): self.name = name self.args = args or () self.kwargs = kwargs or {} @property def markname(self): return self.name # for backward-compat (2.4.1 had this attr) def __repr__(self): d = self.__dict__.copy() name = d.pop('name') return "<MarkDecorator %r %r>" % (name, d) def __call__(self, *args, **kwargs): """ if passed a single callable argument: decorate it with mark info. otherwise add *args/**kwargs in-place to mark information. """ if args and not kwargs: func = args[0] is_class = inspect.isclass(func) if len(args) == 1 and (istestfunc(func) or is_class): if is_class: if hasattr(func, 'pytestmark'): mark_list = func.pytestmark if not isinstance(mark_list, list): mark_list = [mark_list] # always work on a copy to avoid updating pytestmark # from a superclass by accident mark_list = mark_list + [self] func.pytestmark = mark_list else: func.pytestmark = [self] else: holder = getattr(func, self.name, None) if holder is None: holder = MarkInfo( self.name, self.args, self.kwargs ) setattr(func, self.name, holder) else: holder.add(self.args, self.kwargs) return func kw = self.kwargs.copy() kw.update(kwargs) args = self.args + args return self.__class__(self.name, args=args, kwargs=kw) class MarkInfo: """ Marking object created by :class:`MarkDecorator` instances. """ def __init__(self, name, args, kwargs): #: name of attribute self.name = name #: positional argument list, empty if none specified self.args = args #: keyword argument dictionary, empty if nothing specified self.kwargs = kwargs.copy() self._arglist = [(args, kwargs.copy())] def __repr__(self): return "<MarkInfo %r args=%r kwargs=%r>" % ( self.name, self.args, self.kwargs ) def add(self, args, kwargs): """ add a MarkInfo with the given args and kwargs. """ self._arglist.append((args, kwargs)) self.args += args self.kwargs.update(kwargs) def __iter__(self): """ yield MarkInfo objects each relating to a marking-call. """ for args, kwargs in self._arglist: yield MarkInfo(self.name, args, kwargs)
mpl-2.0
larsbutler/coveragepy
tests/test_python.py
3
1065
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt """Tests of coverage/python.py""" import os import sys from coverage.python import get_zip_bytes from tests.coveragetest import CoverageTest class GetZipBytesTest(CoverageTest): """Tests of `get_zip_bytes`.""" run_in_temp_dir = False def test_get_encoded_zip_files(self): # See igor.py, do_zipmods, for the text of these files. zip_file = "tests/zipmods.zip" sys.path.append(zip_file) # So we can import the files. for encoding in ["utf8", "gb2312", "hebrew", "shift_jis"]: filename = zip_file + "/encoded_" + encoding + ".py" filename = filename.replace("/", os.sep) zip_data = get_zip_bytes(filename) zip_text = zip_data.decode(encoding) self.assertIn('All OK', zip_text) # Run the code to see that we really got it encoded properly. __import__("encoded_"+encoding)
apache-2.0
liangazhou/django-rdp
packages/PyDev/plugins/org.python.pydev.jython_4.4.0.201510052309/Lib/encodings/mac_romanian.py
593
13917
""" Python Character Mapping Codec mac_romanian generated from 'MAPPINGS/VENDORS/APPLE/ROMANIAN.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_table) 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_table)[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='mac-romanian', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> CONTROL CHARACTER u'\x01' # 0x01 -> CONTROL CHARACTER u'\x02' # 0x02 -> CONTROL CHARACTER u'\x03' # 0x03 -> CONTROL CHARACTER u'\x04' # 0x04 -> CONTROL CHARACTER u'\x05' # 0x05 -> CONTROL CHARACTER u'\x06' # 0x06 -> CONTROL CHARACTER u'\x07' # 0x07 -> CONTROL CHARACTER u'\x08' # 0x08 -> CONTROL CHARACTER u'\t' # 0x09 -> CONTROL CHARACTER u'\n' # 0x0A -> CONTROL CHARACTER u'\x0b' # 0x0B -> CONTROL CHARACTER u'\x0c' # 0x0C -> CONTROL CHARACTER u'\r' # 0x0D -> CONTROL CHARACTER u'\x0e' # 0x0E -> CONTROL CHARACTER u'\x0f' # 0x0F -> CONTROL CHARACTER u'\x10' # 0x10 -> CONTROL CHARACTER u'\x11' # 0x11 -> CONTROL CHARACTER u'\x12' # 0x12 -> CONTROL CHARACTER u'\x13' # 0x13 -> CONTROL CHARACTER u'\x14' # 0x14 -> CONTROL CHARACTER u'\x15' # 0x15 -> CONTROL CHARACTER u'\x16' # 0x16 -> CONTROL CHARACTER u'\x17' # 0x17 -> CONTROL CHARACTER u'\x18' # 0x18 -> CONTROL CHARACTER u'\x19' # 0x19 -> CONTROL CHARACTER u'\x1a' # 0x1A -> CONTROL CHARACTER u'\x1b' # 0x1B -> CONTROL CHARACTER u'\x1c' # 0x1C -> CONTROL CHARACTER u'\x1d' # 0x1D -> CONTROL CHARACTER u'\x1e' # 0x1E -> CONTROL CHARACTER u'\x1f' # 0x1F -> CONTROL CHARACTER u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> CONTROL CHARACTER u'\xc4' # 0x80 -> LATIN CAPITAL LETTER A WITH DIAERESIS u'\xc5' # 0x81 -> LATIN CAPITAL LETTER A WITH RING ABOVE u'\xc7' # 0x82 -> LATIN CAPITAL LETTER C WITH CEDILLA u'\xc9' # 0x83 -> LATIN CAPITAL LETTER E WITH ACUTE u'\xd1' # 0x84 -> LATIN CAPITAL LETTER N WITH TILDE u'\xd6' # 0x85 -> LATIN CAPITAL LETTER O WITH DIAERESIS u'\xdc' # 0x86 -> LATIN CAPITAL LETTER U WITH DIAERESIS u'\xe1' # 0x87 -> LATIN SMALL LETTER A WITH ACUTE u'\xe0' # 0x88 -> LATIN SMALL LETTER A WITH GRAVE u'\xe2' # 0x89 -> LATIN SMALL LETTER A WITH CIRCUMFLEX u'\xe4' # 0x8A -> LATIN SMALL LETTER A WITH DIAERESIS u'\xe3' # 0x8B -> LATIN SMALL LETTER A WITH TILDE u'\xe5' # 0x8C -> LATIN SMALL LETTER A WITH RING ABOVE u'\xe7' # 0x8D -> LATIN SMALL LETTER C WITH CEDILLA u'\xe9' # 0x8E -> LATIN SMALL LETTER E WITH ACUTE u'\xe8' # 0x8F -> LATIN SMALL LETTER E WITH GRAVE u'\xea' # 0x90 -> LATIN SMALL LETTER E WITH CIRCUMFLEX u'\xeb' # 0x91 -> LATIN SMALL LETTER E WITH DIAERESIS u'\xed' # 0x92 -> LATIN SMALL LETTER I WITH ACUTE u'\xec' # 0x93 -> LATIN SMALL LETTER I WITH GRAVE u'\xee' # 0x94 -> LATIN SMALL LETTER I WITH CIRCUMFLEX u'\xef' # 0x95 -> LATIN SMALL LETTER I WITH DIAERESIS u'\xf1' # 0x96 -> LATIN SMALL LETTER N WITH TILDE u'\xf3' # 0x97 -> LATIN SMALL LETTER O WITH ACUTE u'\xf2' # 0x98 -> LATIN SMALL LETTER O WITH GRAVE u'\xf4' # 0x99 -> LATIN SMALL LETTER O WITH CIRCUMFLEX u'\xf6' # 0x9A -> LATIN SMALL LETTER O WITH DIAERESIS u'\xf5' # 0x9B -> LATIN SMALL LETTER O WITH TILDE u'\xfa' # 0x9C -> LATIN SMALL LETTER U WITH ACUTE u'\xf9' # 0x9D -> LATIN SMALL LETTER U WITH GRAVE u'\xfb' # 0x9E -> LATIN SMALL LETTER U WITH CIRCUMFLEX u'\xfc' # 0x9F -> LATIN SMALL LETTER U WITH DIAERESIS u'\u2020' # 0xA0 -> DAGGER u'\xb0' # 0xA1 -> DEGREE SIGN u'\xa2' # 0xA2 -> CENT SIGN u'\xa3' # 0xA3 -> POUND SIGN u'\xa7' # 0xA4 -> SECTION SIGN u'\u2022' # 0xA5 -> BULLET u'\xb6' # 0xA6 -> PILCROW SIGN u'\xdf' # 0xA7 -> LATIN SMALL LETTER SHARP S u'\xae' # 0xA8 -> REGISTERED SIGN u'\xa9' # 0xA9 -> COPYRIGHT SIGN u'\u2122' # 0xAA -> TRADE MARK SIGN u'\xb4' # 0xAB -> ACUTE ACCENT u'\xa8' # 0xAC -> DIAERESIS u'\u2260' # 0xAD -> NOT EQUAL TO u'\u0102' # 0xAE -> LATIN CAPITAL LETTER A WITH BREVE u'\u0218' # 0xAF -> LATIN CAPITAL LETTER S WITH COMMA BELOW # for Unicode 3.0 and later u'\u221e' # 0xB0 -> INFINITY u'\xb1' # 0xB1 -> PLUS-MINUS SIGN u'\u2264' # 0xB2 -> LESS-THAN OR EQUAL TO u'\u2265' # 0xB3 -> GREATER-THAN OR EQUAL TO u'\xa5' # 0xB4 -> YEN SIGN u'\xb5' # 0xB5 -> MICRO SIGN u'\u2202' # 0xB6 -> PARTIAL DIFFERENTIAL u'\u2211' # 0xB7 -> N-ARY SUMMATION u'\u220f' # 0xB8 -> N-ARY PRODUCT u'\u03c0' # 0xB9 -> GREEK SMALL LETTER PI u'\u222b' # 0xBA -> INTEGRAL u'\xaa' # 0xBB -> FEMININE ORDINAL INDICATOR u'\xba' # 0xBC -> MASCULINE ORDINAL INDICATOR u'\u03a9' # 0xBD -> GREEK CAPITAL LETTER OMEGA u'\u0103' # 0xBE -> LATIN SMALL LETTER A WITH BREVE u'\u0219' # 0xBF -> LATIN SMALL LETTER S WITH COMMA BELOW # for Unicode 3.0 and later u'\xbf' # 0xC0 -> INVERTED QUESTION MARK u'\xa1' # 0xC1 -> INVERTED EXCLAMATION MARK u'\xac' # 0xC2 -> NOT SIGN u'\u221a' # 0xC3 -> SQUARE ROOT u'\u0192' # 0xC4 -> LATIN SMALL LETTER F WITH HOOK u'\u2248' # 0xC5 -> ALMOST EQUAL TO u'\u2206' # 0xC6 -> INCREMENT u'\xab' # 0xC7 -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbb' # 0xC8 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\u2026' # 0xC9 -> HORIZONTAL ELLIPSIS u'\xa0' # 0xCA -> NO-BREAK SPACE u'\xc0' # 0xCB -> LATIN CAPITAL LETTER A WITH GRAVE u'\xc3' # 0xCC -> LATIN CAPITAL LETTER A WITH TILDE u'\xd5' # 0xCD -> LATIN CAPITAL LETTER O WITH TILDE u'\u0152' # 0xCE -> LATIN CAPITAL LIGATURE OE u'\u0153' # 0xCF -> LATIN SMALL LIGATURE OE u'\u2013' # 0xD0 -> EN DASH u'\u2014' # 0xD1 -> EM DASH u'\u201c' # 0xD2 -> LEFT DOUBLE QUOTATION MARK u'\u201d' # 0xD3 -> RIGHT DOUBLE QUOTATION MARK u'\u2018' # 0xD4 -> LEFT SINGLE QUOTATION MARK u'\u2019' # 0xD5 -> RIGHT SINGLE QUOTATION MARK u'\xf7' # 0xD6 -> DIVISION SIGN u'\u25ca' # 0xD7 -> LOZENGE u'\xff' # 0xD8 -> LATIN SMALL LETTER Y WITH DIAERESIS u'\u0178' # 0xD9 -> LATIN CAPITAL LETTER Y WITH DIAERESIS u'\u2044' # 0xDA -> FRACTION SLASH u'\u20ac' # 0xDB -> EURO SIGN u'\u2039' # 0xDC -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK u'\u203a' # 0xDD -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK u'\u021a' # 0xDE -> LATIN CAPITAL LETTER T WITH COMMA BELOW # for Unicode 3.0 and later u'\u021b' # 0xDF -> LATIN SMALL LETTER T WITH COMMA BELOW # for Unicode 3.0 and later u'\u2021' # 0xE0 -> DOUBLE DAGGER u'\xb7' # 0xE1 -> MIDDLE DOT u'\u201a' # 0xE2 -> SINGLE LOW-9 QUOTATION MARK u'\u201e' # 0xE3 -> DOUBLE LOW-9 QUOTATION MARK u'\u2030' # 0xE4 -> PER MILLE SIGN u'\xc2' # 0xE5 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX u'\xca' # 0xE6 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX u'\xc1' # 0xE7 -> LATIN CAPITAL LETTER A WITH ACUTE u'\xcb' # 0xE8 -> LATIN CAPITAL LETTER E WITH DIAERESIS u'\xc8' # 0xE9 -> LATIN CAPITAL LETTER E WITH GRAVE u'\xcd' # 0xEA -> LATIN CAPITAL LETTER I WITH ACUTE u'\xce' # 0xEB -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX u'\xcf' # 0xEC -> LATIN CAPITAL LETTER I WITH DIAERESIS u'\xcc' # 0xED -> LATIN CAPITAL LETTER I WITH GRAVE u'\xd3' # 0xEE -> LATIN CAPITAL LETTER O WITH ACUTE u'\xd4' # 0xEF -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX u'\uf8ff' # 0xF0 -> Apple logo u'\xd2' # 0xF1 -> LATIN CAPITAL LETTER O WITH GRAVE u'\xda' # 0xF2 -> LATIN CAPITAL LETTER U WITH ACUTE u'\xdb' # 0xF3 -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX u'\xd9' # 0xF4 -> LATIN CAPITAL LETTER U WITH GRAVE u'\u0131' # 0xF5 -> LATIN SMALL LETTER DOTLESS I u'\u02c6' # 0xF6 -> MODIFIER LETTER CIRCUMFLEX ACCENT u'\u02dc' # 0xF7 -> SMALL TILDE u'\xaf' # 0xF8 -> MACRON u'\u02d8' # 0xF9 -> BREVE u'\u02d9' # 0xFA -> DOT ABOVE u'\u02da' # 0xFB -> RING ABOVE u'\xb8' # 0xFC -> CEDILLA u'\u02dd' # 0xFD -> DOUBLE ACUTE ACCENT u'\u02db' # 0xFE -> OGONEK u'\u02c7' # 0xFF -> CARON ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
apache-2.0
jensreeder/scikit-bio
skbio/diversity/beta/__init__.py
1
6898
""" Beta diversity measures (:mod:`skbio.diversity.beta`) ===================================================== .. currentmodule:: skbio.diversity.beta This package contains helper functions for working with scipy's pairwise distance (``pdist``) functions in scikit-bio, and will eventually be expanded to contain pairwise distance/dissimilarity methods that are not implemented (or planned to be implemented) in scipy. The functions in this package currently support applying ``pdist`` functions to all pairs of samples in a sample by observation count or abundance matrix and returning an ``skbio.DistanceMatrix`` object. This application is illustrated below for a few different forms of input. Functions --------- .. autosummary:: :toctree: generated/ pw_distances pw_distances_from_table Examples -------- Create a table containing 7 OTUs and 6 samples: .. plot:: :context: >>> from skbio.diversity.beta import pw_distances >>> import numpy as np >>> data = [[23, 64, 14, 0, 0, 3, 1], ... [0, 3, 35, 42, 0, 12, 1], ... [0, 5, 5, 0, 40, 40, 0], ... [44, 35, 9, 0, 1, 0, 0], ... [0, 2, 8, 0, 35, 45, 1], ... [0, 0, 25, 35, 0, 19, 0]] >>> ids = list('ABCDEF') Compute Bray-Curtis distances between all pairs of samples and return a ``DistanceMatrix`` object: >>> bc_dm = pw_distances(data, ids, "braycurtis") >>> print(bc_dm) 6x6 distance matrix IDs: 'A', 'B', 'C', 'D', 'E', 'F' Data: [[ 0. 0.78787879 0.86666667 0.30927835 0.85714286 0.81521739] [ 0.78787879 0. 0.78142077 0.86813187 0.75 0.1627907 ] [ 0.86666667 0.78142077 0. 0.87709497 0.09392265 0.71597633] [ 0.30927835 0.86813187 0.87709497 0. 0.87777778 0.89285714] [ 0.85714286 0.75 0.09392265 0.87777778 0. 0.68235294] [ 0.81521739 0.1627907 0.71597633 0.89285714 0.68235294 0. ]] Compute Jaccard distances between all pairs of samples and return a ``DistanceMatrix`` object: >>> j_dm = pw_distances(data, ids, "jaccard") >>> print(j_dm) 6x6 distance matrix IDs: 'A', 'B', 'C', 'D', 'E', 'F' Data: [[ 0. 0.83333333 1. 1. 0.83333333 1. ] [ 0.83333333 0. 1. 1. 0.83333333 1. ] [ 1. 1. 0. 1. 1. 1. ] [ 1. 1. 1. 0. 1. 1. ] [ 0.83333333 0.83333333 1. 1. 0. 1. ] [ 1. 1. 1. 1. 1. 0. ]] Determine if the resulting distance matrices are significantly correlated by computing the Mantel correlation between them. Then determine if the p-value is significant based on an alpha of 0.05: >>> from skbio.stats.distance import mantel >>> r, p_value, n = mantel(j_dm, bc_dm) >>> print(r) -0.209362157621 >>> print(p_value < 0.05) False Compute PCoA for both distance matrices, and then find the Procrustes M-squared value that results from comparing the coordinate matrices. >>> from skbio.stats.ordination import PCoA >>> bc_pc = PCoA(bc_dm).scores() >>> j_pc = PCoA(j_dm).scores() >>> from skbio.stats.spatial import procrustes >>> print(procrustes(bc_pc.site, j_pc.site)[2]) 0.466134984787 All of this only gets interesting in the context of sample metadata, so let's define some: >>> import pandas as pd >>> try: ... # not necessary for normal use ... pd.set_option('show_dimensions', True) ... except KeyError: ... pass >>> sample_md = { ... 'A': {'body_site': 'gut', 'subject': 's1'}, ... 'B': {'body_site': 'skin', 'subject': 's1'}, ... 'C': {'body_site': 'tongue', 'subject': 's1'}, ... 'D': {'body_site': 'gut', 'subject': 's2'}, ... 'E': {'body_site': 'tongue', 'subject': 's2'}, ... 'F': {'body_site': 'skin', 'subject': 's2'}} >>> sample_md = pd.DataFrame.from_dict(sample_md, orient='index') >>> sample_md subject body_site A s1 gut B s1 skin C s1 tongue D s2 gut E s2 tongue F s2 skin <BLANKLINE> [6 rows x 2 columns] Now let's plot our PCoA results, coloring each sample by the subject it was taken from: >>> fig = bc_pc.plot(sample_md, 'subject', ... axis_labels=('PC 1', 'PC 2', 'PC 3'), ... title='Samples colored by subject', cmap='jet', s=50) .. plot:: :context: We don't see any clustering/grouping of samples. If we were to instead color the samples by the body site they were taken from, we see that the samples form three separate groups: >>> import matplotlib.pyplot as plt >>> plt.close('all') # not necessary for normal use >>> fig = bc_pc.plot(sample_md, 'body_site', ... axis_labels=('PC 1', 'PC 2', 'PC 3'), ... title='Samples colored by body site', cmap='jet', s=50) Ordination techniques, such as PCoA, are useful for exploratory analysis. The next step is to quantify the strength of the grouping/clustering that we see in ordination plots. There are many statistical methods available to accomplish this; many operate on distance matrices. Let's use ANOSIM to quantify the strength of the clustering we see in the ordination plots above, using our Bray-Curtis distance matrix and sample metadata. First test the grouping of samples by subject: >>> from skbio.stats.distance import anosim >>> results = anosim(bc_dm, sample_md, column='subject', permutations=999) >>> results['test statistic'] -0.4074074074074075 >>> results['p-value'] < 0.1 False The negative value of ANOSIM's R statistic indicates anti-clustering and the p-value is insignificant at an alpha of 0.1. Now let's test the grouping of samples by body site: >>> results = anosim(bc_dm, sample_md, column='body_site', permutations=999) >>> results['test statistic'] 1.0 >>> results['p-value'] < 0.1 True The R statistic of 1.0 indicates strong separation of samples based on body site. The p-value is significant at an alpha of 0.1. References ---------- .. [1] http://matplotlib.org/examples/mplot3d/scatter3d_demo.html """ # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from skbio.util import TestRunner from ._base import pw_distances, pw_distances_from_table __all__ = ["pw_distances", "pw_distances_from_table"] test = TestRunner(__file__).test
bsd-3-clause