repo_name
stringlengths
5
92
path
stringlengths
4
221
copies
stringclasses
19 values
size
stringlengths
4
6
content
stringlengths
766
896k
license
stringclasses
15 values
hash
int64
-9,223,277,421,539,062,000
9,223,102,107B
line_mean
float64
6.51
99.9
line_max
int64
32
997
alpha_frac
float64
0.25
0.96
autogenerated
bool
1 class
ratio
float64
1.5
13.6
config_test
bool
2 classes
has_no_keywords
bool
2 classes
few_assignments
bool
1 class
CriticalD20/Sine-Cosine
sinecosine.py
1
2215
""" sinecosine.py Author: James Napier Credit: http://www.discoveryplayground.com/computer-programming-for-kids/rgb-colors/, Mr. Dennison Assignment: In this assignment you must use *list comprehensions* to generate sprites that show the behavior of certain mathematical functions: sine and cosine. The sine and cosine functions are provided in the Python math library. These functions are used to relate *angles* to *rectangular* (x,y) coordinate systems and can be very useful in computer game design. Unlike the last assignment using ggame`, this one will not provide any "skeleton" code to fill in. You should use your submission for the Picture assignment (https://github.com/HHS-IntroProgramming/Picture) as a reference for starting this assignment. See: https://github.com/HHS-IntroProgramming/Sine-Cosine/blob/master/README.md for a detailed list of requirements for this assignment. https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Displaying-Graphics for general information on how to use ggame. https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Programmed-Graphics for general information on using list comprehensions to generate graphics. http://brythonserver.github.io/ggame/ for detailed information on ggame. """ from ggame import App, Color, CircleAsset, LineStyle, Sprite from math import sin, cos, radians blue=Color(0x0000ff, 1.0) red=Color(0xff0000, 1.0) purple=Color(0xa020f0, 1.00) black=Color(0x000000, 1.0) thinline=LineStyle(1, black) mycircle=CircleAsset(5, thinline, blue) mycircle2=CircleAsset(5, thinline, red) mycircle3=CircleAsset(5, thinline, purple) xcoordinates=range(0, 360, 10) ycoordinates=[100+100*sin(radians(x))for x in xcoordinates] y2coordinates=[100+100*cos(radians(x))for x in xcoordinates] x2coordinates=[100+100*cos(radians(x))for x in xcoordinates] y3coordinates=[400+100*sin(radians(x))for x in xcoordinates] xy=zip(xcoordinates, ycoordinates) xy2=zip(xcoordinates, y2coordinates) x2y3=zip(x2coordinates, y3coordinates) #use ziping for lists tomorrow of Friday sprites=[Sprite(mycircle, x)for x in xy] sprites=[Sprite(mycircle2, x)for x in xy2] sprites=[Sprite(mycircle3, x)for x in x2y3] myapp=App() myapp.run()
mit
-7,328,395,108,479,366,000
35.311475
98
0.792777
false
3.124118
false
false
false
brendandc/multilingual-google-image-scraper
create-language-zip.py
1
3067
import optparse import os optparser = optparse.OptionParser() optparser.add_option("-l", "--language", dest="language", default="French", help="Language to package") optparser.add_option("-b", "--bucket", dest="bucket", default="brendan.callahan.thesis", help="S3 bucket name") optparser.add_option("-p", "--prefix", dest="prefix", help="Alternate prefix for the filenames, default is lower case language name") optparser.add_option("-S", action="store_true", dest="skip_completed_words", help="Allows multiple passes so we can resume if any failures") (opts, _) = optparser.parse_args() # TODO: un-hard code the base destination and source paths BASE_DESTINATION_PATH = '/mnt/storage2/intermediate/' BASE_SOURCE_PATH = '/mnt/storage/'+opts.language+'/' BASE_TAR_PATH = BASE_DESTINATION_PATH + opts.language.lower() file_prefix = opts.prefix or opts.language.lower() big_tar_file_name = file_prefix+"-package.tar" sample_tar_file_name = file_prefix+"-sample.tar" big_tar_path = BASE_DESTINATION_PATH + big_tar_file_name sample_tar_path = BASE_DESTINATION_PATH + sample_tar_file_name if not os.path.exists(BASE_DESTINATION_PATH): os.makedirs(BASE_DESTINATION_PATH) if not opts.skip_completed_words: tar_cmd = "tar cvf "+ big_tar_path+" --files-from /dev/null" os.system(tar_cmd) sample_cmd = "tar cvf "+ sample_tar_path+" --files-from /dev/null" os.system(sample_cmd) os.system("cd " + BASE_SOURCE_PATH + " && tar rf "+big_tar_path+" all_errors.json") targz_files = [] for folder_name in os.listdir(BASE_SOURCE_PATH): print(folder_name) targz_file = folder_name + '.tar.gz' targz_path = BASE_DESTINATION_PATH + targz_file targz_files.append(targz_file) # if skip completed words param was passed, and the filepath exists skip this and move onto the next # assume there are no incomplete files (that they are cleaned up manually) if opts.skip_completed_words and os.path.isfile(targz_path): continue add_folder_cmd = "cd " + BASE_SOURCE_PATH + " && tar -czf "+targz_path+" "+folder_name print(add_folder_cmd) os.system(add_folder_cmd) add_folders_cmd = "cd " + BASE_DESTINATION_PATH + " && tar rf "+big_tar_file_name+" "+" ".join(targz_files) print(add_folders_cmd) os.system(add_folders_cmd) sample_files = sorted(targz_files)[0:100] add_folders_cmd_sample = "cd " + BASE_DESTINATION_PATH + " && tar rf "+sample_tar_file_name+" "+" ".join(sample_files) print(add_folders_cmd_sample) os.system(add_folders_cmd_sample) os.system("cd " + BASE_DESTINATION_PATH + " && mv " + big_tar_file_name + " ..") os.system("cd " + BASE_DESTINATION_PATH + " && mv " + sample_tar_file_name + " ..") # TODO make aws upload optional package_upload_cmd = "aws s3 cp /mnt/storage2/" + big_tar_file_name + " s3://" + opts.bucket + "/packages/" + \ big_tar_file_name sample_upload_cmd = "aws s3 cp /mnt/storage2/" + sample_tar_file_name + " s3://" + opts.bucket + "/samples/" + \ sample_tar_file_name os.system(package_upload_cmd) os.system(sample_upload_cmd)
mit
-8,948,385,637,682,369,000
41.597222
140
0.681774
false
3.067
false
false
false
hadim/spindle_tracker
spindle_tracker/io/trackmate.py
1
5663
import itertools import xml.etree.cElementTree as et import networkx as nx import pandas as pd import numpy as np def trackmate_peak_import(trackmate_xml_path, get_tracks=False): """Import detected peaks with TrackMate Fiji plugin. Parameters ---------- trackmate_xml_path : str TrackMate XML file path. get_tracks : boolean Add tracks to label """ root = et.fromstring(open(trackmate_xml_path).read()) objects = [] object_labels = {'FRAME': 't_stamp', 'POSITION_T': 't', 'POSITION_X': 'x', 'POSITION_Y': 'y', 'POSITION_Z': 'z', 'MEAN_INTENSITY': 'I', 'ESTIMATED_DIAMETER': 'w', 'QUALITY': 'q', 'ID': 'spot_id', 'MEAN_INTENSITY': 'mean_intensity', 'MEDIAN_INTENSITY': 'median_intensity', 'MIN_INTENSITY': 'min_intensity', 'MAX_INTENSITY': 'max_intensity', 'TOTAL_INTENSITY': 'total_intensity', 'STANDARD_DEVIATION': 'std_intensity', 'CONTRAST': 'contrast', 'SNR': 'snr'} features = root.find('Model').find('FeatureDeclarations').find('SpotFeatures') features = [c.get('feature') for c in features.getchildren()] + ['ID'] spots = root.find('Model').find('AllSpots') trajs = pd.DataFrame([]) objects = [] for frame in spots.findall('SpotsInFrame'): for spot in frame.findall('Spot'): single_object = [] for label in features: single_object.append(spot.get(label)) objects.append(single_object) trajs = pd.DataFrame(objects, columns=features) trajs = trajs.astype(np.float) # Apply initial filtering initial_filter = root.find("Settings").find("InitialSpotFilter") trajs = filter_spots(trajs, name=initial_filter.get('feature'), value=float(initial_filter.get('value')), isabove=True if initial_filter.get('isabove') == 'true' else False) # Apply filters spot_filters = root.find("Settings").find("SpotFilterCollection") for spot_filter in spot_filters.findall('Filter'): trajs = filter_spots(trajs, name=spot_filter.get('feature'), value=float(spot_filter.get('value')), isabove=True if spot_filter.get('isabove') == 'true' else False) trajs = trajs.loc[:, object_labels.keys()] trajs.columns = [object_labels[k] for k in object_labels.keys()] trajs['label'] = np.arange(trajs.shape[0]) # Get tracks if get_tracks: filtered_track_ids = [int(track.get('TRACK_ID')) for track in root.find('Model').find('FilteredTracks').findall('TrackID')] new_trajs = pd.DataFrame() label_id = 0 trajs = trajs.set_index('spot_id') tracks = root.find('Model').find('AllTracks') for track in tracks.findall('Track'): track_id = int(track.get("TRACK_ID")) if track_id in filtered_track_ids: spot_ids = [(edge.get('SPOT_SOURCE_ID'), edge.get('SPOT_TARGET_ID'), edge.get('EDGE_TIME')) for edge in track.findall('Edge')] spot_ids = np.array(spot_ids).astype('float') spot_ids = pd.DataFrame(spot_ids, columns=['source', 'target', 'time']) spot_ids = spot_ids.sort_values(by='time') spot_ids = spot_ids.set_index('time') # Build graph graph = nx.Graph() for t, spot in spot_ids.iterrows(): graph.add_edge(int(spot['source']), int(spot['target']), attr_dict=dict(t=t)) # Find graph extremities by checking if number of neighbors is equal to 1 tracks_extremities = [node for node in graph.nodes() if len(graph.neighbors(node)) == 1] paths = [] # Find all possible paths between extremities for source, target in itertools.combinations(tracks_extremities, 2): # Find all path between two nodes for path in nx.all_simple_paths(graph, source=source, target=target): # Now we need to check wether this path respect the time logic contraint # edges can only go in one direction of the time # Build times vector according to path t = [] for i, node_srce in enumerate(path[:-1]): node_trgt = path[i+1] t.append(graph.edge[node_srce][node_trgt]['t']) # Will be equal to 1 if going to one time direction if len(np.unique(np.sign(np.diff(t)))) == 1: paths.append(path) # Add each individual trajectory to a new DataFrame called new_trajs for path in paths: traj = trajs.loc[path].copy() traj['label'] = label_id label_id += 1 new_trajs = new_trajs.append(traj) trajs = new_trajs trajs.set_index(['t_stamp', 'label'], inplace=True) trajs = trajs.sort_index() return trajs def filter_spots(spots, name, value, isabove): if isabove: spots = spots[spots[name] > value] else: spots = spots[spots[name] < value] return spots
bsd-3-clause
6,876,808,598,429,822,000
36.753333
142
0.529931
false
4.019163
false
false
false
kronat/ns-3-dev-git
src/network/bindings/modulegen__gcc_ILP32.py
1
773065
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.network', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## packetbb.h (module 'network'): ns3::PbbAddressLength [enumeration] module.add_enum('PbbAddressLength', ['IPV4', 'IPV6']) ## ethernet-header.h (module 'network'): ns3::ethernet_header_t [enumeration] module.add_enum('ethernet_header_t', ['LENGTH', 'VLAN', 'QINQ']) ## queue-size.h (module 'network'): ns3::QueueSizeUnit [enumeration] module.add_enum('QueueSizeUnit', ['PACKETS', 'BYTES']) ## 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') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address']) ## application-container.h (module 'network'): ns3::ApplicationContainer [class] module.add_class('ApplicationContainer') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Application > > const_iterator', u'ns3::ApplicationContainer::Iterator') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Application > > const_iterator*', u'ns3::ApplicationContainer::Iterator*') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Application > > const_iterator&', u'ns3::ApplicationContainer::Iterator&') ## ascii-file.h (module 'network'): ns3::AsciiFile [class] module.add_class('AsciiFile') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class] module.add_class('AsciiTraceHelper') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class] module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True) ## 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']) typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator', u'ns3::AttributeConstructionList::CIterator') typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator*', u'ns3::AttributeConstructionList::CIterator*') typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator&', u'ns3::AttributeConstructionList::CIterator&') ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## channel-list.h (module 'network'): ns3::ChannelList [class] module.add_class('ChannelList') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Channel > > const_iterator', u'ns3::ChannelList::Iterator') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Channel > > const_iterator*', u'ns3::ChannelList::Iterator*') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Channel > > const_iterator&', u'ns3::ChannelList::Iterator&') ## data-output-interface.h (module 'stats'): ns3::DataOutputCallback [class] module.add_class('DataOutputCallback', allow_subclassing=True, import_from_module='ns.stats') ## data-rate.h (module 'network'): ns3::DataRate [class] module.add_class('DataRate') ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeChecker']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeValue']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::EventImpl']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NetDeviceQueue> [struct] module.add_class('DefaultDeleter', template_parameters=['ns3::NetDeviceQueue']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector> [struct] module.add_class('DefaultDeleter', template_parameters=['ns3::NixVector']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::OutputStreamWrapper> [struct] module.add_class('DefaultDeleter', template_parameters=['ns3::OutputStreamWrapper']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet> [struct] module.add_class('DefaultDeleter', template_parameters=['ns3::Packet']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::PbbAddressBlock> [struct] module.add_class('DefaultDeleter', template_parameters=['ns3::PbbAddressBlock']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::PbbMessage> [struct] module.add_class('DefaultDeleter', template_parameters=['ns3::PbbMessage']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::PbbTlv> [struct] module.add_class('DefaultDeleter', template_parameters=['ns3::PbbTlv']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::QueueItem> [struct] module.add_class('DefaultDeleter', template_parameters=['ns3::QueueItem']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor']) ## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation [class] module.add_class('DelayJitterEstimation') ## 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') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address') ## 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') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address') ## 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') ## log.h (module 'core'): ns3::LogComponent [class] module.add_class('LogComponent', import_from_module='ns.core') typehandlers.add_type_alias(u'std::map< std::string, ns3::LogComponent * >', u'ns3::LogComponent::ComponentList') typehandlers.add_type_alias(u'std::map< std::string, ns3::LogComponent * >*', u'ns3::LogComponent::ComponentList*') typehandlers.add_type_alias(u'std::map< std::string, ns3::LogComponent * >&', u'ns3::LogComponent::ComponentList&') ## mac16-address.h (module 'network'): ns3::Mac16Address [class] module.add_class('Mac16Address') ## 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') typehandlers.add_type_alias(u'void ( * ) ( ns3::Mac48Address )', u'ns3::Mac48Address::TracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Mac48Address )*', u'ns3::Mac48Address::TracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Mac48Address )&', u'ns3::Mac48Address::TracedCallback&') ## 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') ## mac64-address.h (module 'network'): ns3::Mac64Address [class] root_module['ns3::Mac64Address'].implicitly_converts_to(root_module['ns3::Address']) ## mac8-address.h (module 'network'): ns3::Mac8Address [class] module.add_class('Mac8Address') ## mac8-address.h (module 'network'): ns3::Mac8Address [class] root_module['ns3::Mac8Address'].implicitly_converts_to(root_module['ns3::Address']) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::NetDevice > > const_iterator', u'ns3::NetDeviceContainer::Iterator') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::NetDevice > > const_iterator*', u'ns3::NetDeviceContainer::Iterator*') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::NetDevice > > const_iterator&', u'ns3::NetDeviceContainer::Iterator&') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator', u'ns3::NodeContainer::Iterator') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator*', u'ns3::NodeContainer::Iterator*') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator&', u'ns3::NodeContainer::Iterator&') ## node-list.h (module 'network'): ns3::NodeList [class] module.add_class('NodeList') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator', u'ns3::NodeList::Iterator') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator*', u'ns3::NodeList::Iterator*') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator&', u'ns3::NodeList::Iterator&') ## 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') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::ItemType [enumeration] module.add_enum('ItemType', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', outer_class=root_module['ns3::PacketMetadata']) ## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class] module.add_class('PacketSocketAddress') ## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class] root_module['ns3::PacketSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper [class] module.add_class('PacketSocketHelper') ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', outer_class=root_module['ns3::PacketTagList']) ## log.h (module 'core'): ns3::ParameterLogger [class] module.add_class('ParameterLogger', import_from_module='ns.core') ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock [class] module.add_class('PbbAddressTlvBlock') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressTlv > > iterator', u'ns3::PbbAddressTlvBlock::Iterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressTlv > > iterator*', u'ns3::PbbAddressTlvBlock::Iterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressTlv > > iterator&', u'ns3::PbbAddressTlvBlock::Iterator&') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressTlv > > const_iterator', u'ns3::PbbAddressTlvBlock::ConstIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressTlv > > const_iterator*', u'ns3::PbbAddressTlvBlock::ConstIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressTlv > > const_iterator&', u'ns3::PbbAddressTlvBlock::ConstIterator&') ## packetbb.h (module 'network'): ns3::PbbTlvBlock [class] module.add_class('PbbTlvBlock') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > iterator', u'ns3::PbbTlvBlock::Iterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > iterator*', u'ns3::PbbTlvBlock::Iterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > iterator&', u'ns3::PbbTlvBlock::Iterator&') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > const_iterator', u'ns3::PbbTlvBlock::ConstIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > const_iterator*', u'ns3::PbbTlvBlock::ConstIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > const_iterator&', u'ns3::PbbTlvBlock::ConstIterator&') ## pcap-file.h (module 'network'): ns3::PcapFile [class] module.add_class('PcapFile') ## trace-helper.h (module 'network'): ns3::PcapHelper [class] module.add_class('PcapHelper') ## trace-helper.h (module 'network'): ns3::PcapHelper::DataLinkType [enumeration] module.add_enum('DataLinkType', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_LINUX_SLL', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO', 'DLT_IEEE802_15_4', 'DLT_NETLINK'], outer_class=root_module['ns3::PcapHelper']) ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class] module.add_class('PcapHelperForDevice', allow_subclassing=True) ## queue-size.h (module 'network'): ns3::QueueSize [class] module.add_class('QueueSize') ## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned int, int> [class] module.add_class('SequenceNumber32') ## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned short, short> [class] module.add_class('SequenceNumber16') ## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper [class] module.add_class('SimpleNetDeviceHelper') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## data-calculator.h (module 'stats'): ns3::StatisticalSummary [class] module.add_class('StatisticalSummary', allow_subclassing=True, import_from_module='ns.stats') ## 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', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer') ## 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']) ## 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']) typehandlers.add_type_alias(u'uint32_t', u'ns3::TypeId::hash_t') typehandlers.add_type_alias(u'uint32_t*', u'ns3::TypeId::hash_t*') typehandlers.add_type_alias(u'uint32_t&', u'ns3::TypeId::hash_t&') ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-128.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-128.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', parent=root_module['ns3::ObjectBase']) ## packet-socket.h (module 'network'): ns3::DeviceNameTag [class] module.add_class('DeviceNameTag', parent=root_module['ns3::Tag']) ## flow-id-tag.h (module 'network'): ns3::FlowIdTag [class] module.add_class('FlowIdTag', parent=root_module['ns3::Tag']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', parent=root_module['ns3::Chunk']) ## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader [class] module.add_class('LlcSnapHeader', parent=root_module['ns3::Header']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## packet-burst.h (module 'network'): ns3::PacketBurst [class] module.add_class('PacketBurst', parent=root_module['ns3::Object']) typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::PacketBurst const > )', u'ns3::PacketBurst::TracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::PacketBurst const > )*', u'ns3::PacketBurst::TracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::PacketBurst const > )&', u'ns3::PacketBurst::TracedCallback&') ## packet-socket.h (module 'network'): ns3::PacketSocketTag [class] module.add_class('PacketSocketTag', parent=root_module['ns3::Tag']) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class] module.add_class('PcapFileWrapper', parent=root_module['ns3::Object']) ## queue.h (module 'network'): ns3::QueueBase [class] module.add_class('QueueBase', parent=root_module['ns3::Object']) ## queue-limits.h (module 'network'): ns3::QueueLimits [class] module.add_class('QueueLimits', parent=root_module['ns3::Object']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader [class] module.add_class('RadiotapHeader', parent=root_module['ns3::Header']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::FrameFlag [enumeration] module.add_enum('FrameFlag', ['FRAME_FLAG_NONE', 'FRAME_FLAG_CFP', 'FRAME_FLAG_SHORT_PREAMBLE', 'FRAME_FLAG_WEP', 'FRAME_FLAG_FRAGMENTED', 'FRAME_FLAG_FCS_INCLUDED', 'FRAME_FLAG_DATA_PADDING', 'FRAME_FLAG_BAD_FCS', 'FRAME_FLAG_SHORT_GUARD'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::ChannelFlags [enumeration] module.add_enum('ChannelFlags', ['CHANNEL_FLAG_NONE', 'CHANNEL_FLAG_TURBO', 'CHANNEL_FLAG_CCK', 'CHANNEL_FLAG_OFDM', 'CHANNEL_FLAG_SPECTRUM_2GHZ', 'CHANNEL_FLAG_SPECTRUM_5GHZ', 'CHANNEL_FLAG_PASSIVE', 'CHANNEL_FLAG_DYNAMIC', 'CHANNEL_FLAG_GFSK'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::McsKnown [enumeration] module.add_enum('McsKnown', ['MCS_KNOWN_NONE', 'MCS_KNOWN_BANDWIDTH', 'MCS_KNOWN_INDEX', 'MCS_KNOWN_GUARD_INTERVAL', 'MCS_KNOWN_HT_FORMAT', 'MCS_KNOWN_FEC_TYPE', 'MCS_KNOWN_STBC', 'MCS_KNOWN_NESS', 'MCS_KNOWN_NESS_BIT_1'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::McsFlags [enumeration] module.add_enum('McsFlags', ['MCS_FLAGS_NONE', 'MCS_FLAGS_BANDWIDTH_40', 'MCS_FLAGS_BANDWIDTH_20L', 'MCS_FLAGS_BANDWIDTH_20U', 'MCS_FLAGS_GUARD_INTERVAL', 'MCS_FLAGS_HT_GREENFIELD', 'MCS_FLAGS_FEC_TYPE', 'MCS_FLAGS_STBC_STREAMS', 'MCS_FLAGS_NESS_BIT_0'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::AmpduFlags [enumeration] module.add_enum('AmpduFlags', ['A_MPDU_STATUS_NONE', 'A_MPDU_STATUS_REPORT_ZERO_LENGTH', 'A_MPDU_STATUS_IS_ZERO_LENGTH', 'A_MPDU_STATUS_LAST_KNOWN', 'A_MPDU_STATUS_LAST', 'A_MPDU_STATUS_DELIMITER_CRC_ERROR', 'A_MPDU_STATUS_DELIMITER_CRC_KNOWN'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::VhtKnown [enumeration] module.add_enum('VhtKnown', ['VHT_KNOWN_NONE', 'VHT_KNOWN_STBC', 'VHT_KNOWN_TXOP_PS_NOT_ALLOWED', 'VHT_KNOWN_GUARD_INTERVAL', 'VHT_KNOWN_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_KNOWN_LDPC_EXTRA_OFDM_SYMBOL', 'VHT_KNOWN_BEAMFORMED', 'VHT_KNOWN_BANDWIDTH', 'VHT_KNOWN_GROUP_ID', 'VHT_KNOWN_PARTIAL_AID'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::VhtFlags [enumeration] module.add_enum('VhtFlags', ['VHT_FLAGS_NONE', 'VHT_FLAGS_STBC', 'VHT_FLAGS_TXOP_PS_NOT_ALLOWED', 'VHT_FLAGS_GUARD_INTERVAL', 'VHT_FLAGS_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_FLAGS_LDPC_EXTRA_OFDM_SYMBOL', 'VHT_FLAGS_BEAMFORMED'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::HeData1 [enumeration] module.add_enum('HeData1', ['HE_DATA1_FORMAT_EXT_SU', 'HE_DATA1_FORMAT_MU', 'HE_DATA1_FORMAT_TRIG', 'HE_DATA1_BSS_COLOR_KNOWN', 'HE_DATA1_BEAM_CHANGE_KNOWN', 'HE_DATA1_UL_DL_KNOWN', 'HE_DATA1_DATA_MCS_KNOWN', 'HE_DATA1_DATA_DCM_KNOWN', 'HE_DATA1_CODING_KNOWN', 'HE_DATA1_LDPC_XSYMSEG_KNOWN', 'HE_DATA1_STBC_KNOWN', 'HE_DATA1_SPTL_REUSE_KNOWN', 'HE_DATA1_SPTL_REUSE2_KNOWN', 'HE_DATA1_SPTL_REUSE3_KNOWN', 'HE_DATA1_SPTL_REUSE4_KNOWN', 'HE_DATA1_BW_RU_ALLOC_KNOWN', 'HE_DATA1_DOPPLER_KNOWN'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::HeData2 [enumeration] module.add_enum('HeData2', ['HE_DATA2_PRISEC_80_KNOWN', 'HE_DATA2_GI_KNOWN', 'HE_DATA2_NUM_LTF_SYMS_KNOWN', 'HE_DATA2_PRE_FEC_PAD_KNOWN', 'HE_DATA2_TXBF_KNOWN', 'HE_DATA2_PE_DISAMBIG_KNOWN', 'HE_DATA2_TXOP_KNOWN', 'HE_DATA2_MIDAMBLE_KNOWN', 'HE_DATA2_RU_OFFSET', 'HE_DATA2_RU_OFFSET_KNOWN', 'HE_DATA2_PRISEC_80_SEC'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::HeData3 [enumeration] module.add_enum('HeData3', ['HE_DATA3_BSS_COLOR', 'HE_DATA3_BEAM_CHANGE', 'HE_DATA3_UL_DL', 'HE_DATA3_DATA_MCS', 'HE_DATA3_DATA_DCM', 'HE_DATA3_CODING', 'HE_DATA3_LDPC_XSYMSEG', 'HE_DATA3_STBC'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::HeData5 [enumeration] module.add_enum('HeData5', ['HE_DATA5_DATA_BW_RU_ALLOC_40MHZ', 'HE_DATA5_DATA_BW_RU_ALLOC_80MHZ', 'HE_DATA5_DATA_BW_RU_ALLOC_160MHZ', 'HE_DATA5_DATA_BW_RU_ALLOC_26T', 'HE_DATA5_DATA_BW_RU_ALLOC_52T', 'HE_DATA5_DATA_BW_RU_ALLOC_106T', 'HE_DATA5_DATA_BW_RU_ALLOC_242T', 'HE_DATA5_DATA_BW_RU_ALLOC_484T', 'HE_DATA5_DATA_BW_RU_ALLOC_996T', 'HE_DATA5_DATA_BW_RU_ALLOC_2x996T', 'HE_DATA5_GI_1_6', 'HE_DATA5_GI_3_2', 'HE_DATA5_LTF_SYM_SIZE', 'HE_DATA5_NUM_LTF_SYMS', 'HE_DATA5_PRE_FEC_PAD', 'HE_DATA5_TXBF', 'HE_DATA5_PE_DISAMBIG'], outer_class=root_module['ns3::RadiotapHeader']) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, 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::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbAddressBlock', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbAddressBlock>'], 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::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbMessage', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbMessage>'], 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::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbPacket', 'ns3::Header', 'ns3::DefaultDeleter<ns3::PbbPacket>'], parent=root_module['ns3::Header'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbTlv', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbTlv>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## sll-header.h (module 'network'): ns3::SllHeader [class] module.add_class('SllHeader', parent=root_module['ns3::Header']) ## sll-header.h (module 'network'): ns3::SllHeader::PacketType [enumeration] module.add_enum('PacketType', ['UNICAST_FROM_PEER_TO_ME', 'BROADCAST_BY_PEER', 'MULTICAST_BY_PEER', 'INTERCEPTED_PACKET', 'SENT_BY_US'], outer_class=root_module['ns3::SllHeader']) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket']) ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket']) ## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration] module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket']) ## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration] module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket']) ## socket-factory.h (module 'network'): ns3::SocketFactory [class] module.add_class('SocketFactory', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketPriorityTag [class] module.add_class('SocketPriorityTag', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', parent=root_module['ns3::Tag']) ## 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') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time )', u'ns3::Time::TracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time )*', u'ns3::Time::TracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time )&', u'ns3::Time::TracedCallback&') ## 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', 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']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## application.h (module 'network'): ns3::Application [class] module.add_class('Application', parent=root_module['ns3::Object']) typehandlers.add_type_alias(u'void ( * ) ( ns3::Time const &, ns3::Address const & )', u'ns3::Application::DelayAddressCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time const &, ns3::Address const & )*', u'ns3::Application::DelayAddressCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time const &, ns3::Address const & )&', u'ns3::Application::DelayAddressCallback&') typehandlers.add_type_alias(u'void ( * ) ( std::string const &, std::string const & )', u'ns3::Application::StateTransitionCallback') typehandlers.add_type_alias(u'void ( * ) ( std::string const &, std::string const & )*', u'ns3::Application::StateTransitionCallback*') typehandlers.add_type_alias(u'void ( * ) ( std::string const &, std::string const & )&', u'ns3::Application::StateTransitionCallback&') ## 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', 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']) ## data-calculator.h (module 'stats'): ns3::DataCalculator [class] module.add_class('DataCalculator', import_from_module='ns.stats', parent=root_module['ns3::Object']) ## data-collection-object.h (module 'stats'): ns3::DataCollectionObject [class] module.add_class('DataCollectionObject', import_from_module='ns.stats', parent=root_module['ns3::Object']) ## data-output-interface.h (module 'stats'): ns3::DataOutputInterface [class] module.add_class('DataOutputInterface', import_from_module='ns.stats', parent=root_module['ns3::Object']) ## data-rate.h (module 'network'): ns3::DataRateChecker [class] module.add_class('DataRateChecker', parent=root_module['ns3::AttributeChecker']) ## data-rate.h (module 'network'): ns3::DataRateValue [class] module.add_class('DataRateValue', 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']) ## dynamic-queue-limits.h (module 'network'): ns3::DynamicQueueLimits [class] module.add_class('DynamicQueueLimits', parent=root_module['ns3::QueueLimits']) ## 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']) ## error-model.h (module 'network'): ns3::ErrorModel [class] module.add_class('ErrorModel', parent=root_module['ns3::Object']) ## ethernet-header.h (module 'network'): ns3::EthernetHeader [class] module.add_class('EthernetHeader', parent=root_module['ns3::Header']) ## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer [class] module.add_class('EthernetTrailer', parent=root_module['ns3::Trailer']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class] module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## integer.h (module 'core'): ns3::IntegerValue [class] module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', parent=root_module['ns3::AttributeValue']) ## error-model.h (module 'network'): ns3::ListErrorModel [class] module.add_class('ListErrorModel', parent=root_module['ns3::ErrorModel']) ## 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', parent=root_module['ns3::AttributeChecker']) ## mac16-address.h (module 'network'): ns3::Mac16AddressValue [class] module.add_class('Mac16AddressValue', parent=root_module['ns3::AttributeValue']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', parent=root_module['ns3::AttributeValue']) ## mac64-address.h (module 'network'): ns3::Mac64AddressChecker [class] module.add_class('Mac64AddressChecker', parent=root_module['ns3::AttributeChecker']) ## mac64-address.h (module 'network'): ns3::Mac64AddressValue [class] module.add_class('Mac64AddressValue', parent=root_module['ns3::AttributeValue']) ## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int> [class] module.add_class('MinMaxAvgTotalCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=[root_module['ns3::DataCalculator'], root_module['ns3::StatisticalSummary']]) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', 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']) typehandlers.add_type_alias(u'void ( * ) ( )', u'ns3::NetDevice::LinkChangeTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( )*', u'ns3::NetDevice::LinkChangeTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( )&', u'ns3::NetDevice::LinkChangeTracedCallback&') typehandlers.add_type_alias(u'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 >', u'ns3::NetDevice::ReceiveCallback') typehandlers.add_type_alias(u'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 >*', u'ns3::NetDevice::ReceiveCallback*') typehandlers.add_type_alias(u'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 >&', u'ns3::NetDevice::ReceiveCallback&') typehandlers.add_type_alias(u'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 >', u'ns3::NetDevice::PromiscReceiveCallback') typehandlers.add_type_alias(u'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 >*', u'ns3::NetDevice::PromiscReceiveCallback*') typehandlers.add_type_alias(u'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 >&', u'ns3::NetDevice::PromiscReceiveCallback&') ## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueue [class] module.add_class('NetDeviceQueue', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) 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::NetDeviceQueue::WakeCallback') 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::NetDeviceQueue::WakeCallback*') 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::NetDeviceQueue::WakeCallback&') ## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface [class] module.add_class('NetDeviceQueueInterface', parent=root_module['ns3::Object']) typehandlers.add_type_alias(u'std::function< unsigned long long ( ns3::Ptr< ns3::QueueItem > ) >', u'ns3::NetDeviceQueueInterface::SelectQueueCallback') typehandlers.add_type_alias(u'std::function< unsigned long long ( ns3::Ptr< ns3::QueueItem > ) >*', u'ns3::NetDeviceQueueInterface::SelectQueueCallback*') typehandlers.add_type_alias(u'std::function< unsigned long long ( ns3::Ptr< ns3::QueueItem > ) >&', u'ns3::NetDeviceQueueInterface::SelectQueueCallback&') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', parent=root_module['ns3::Object']) typehandlers.add_type_alias(u'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 >', u'ns3::Node::ProtocolHandler') typehandlers.add_type_alias(u'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 >*', u'ns3::Node::ProtocolHandler*') typehandlers.add_type_alias(u'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 >&', u'ns3::Node::ProtocolHandler&') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Node::DeviceAdditionListener') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Node::DeviceAdditionListener*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Node::DeviceAdditionListener&') ## 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']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > )', u'ns3::Packet::TracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > )*', u'ns3::Packet::TracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > )&', u'ns3::Packet::TracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )', u'ns3::Packet::AddressTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )*', u'ns3::Packet::AddressTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )&', u'ns3::Packet::AddressTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )', u'ns3::Packet::TwoAddressTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )*', u'ns3::Packet::TwoAddressTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )&', u'ns3::Packet::TwoAddressTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )', u'ns3::Packet::Mac48AddressTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )*', u'ns3::Packet::Mac48AddressTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )&', u'ns3::Packet::Mac48AddressTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t )', u'ns3::Packet::SizeTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t )*', u'ns3::Packet::SizeTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t )&', u'ns3::Packet::SizeTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, double )', u'ns3::Packet::SinrTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, double )*', u'ns3::Packet::SinrTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, double )&', u'ns3::Packet::SinrTracedCallback&') ## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator [class] module.add_class('PacketSizeMinMaxAvgTotalCalculator', parent=root_module['ns3::MinMaxAvgTotalCalculator< unsigned int >']) ## packet-socket.h (module 'network'): ns3::PacketSocket [class] module.add_class('PacketSocket', parent=root_module['ns3::Socket']) ## packet-socket-client.h (module 'network'): ns3::PacketSocketClient [class] module.add_class('PacketSocketClient', parent=root_module['ns3::Application']) ## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory [class] module.add_class('PacketSocketFactory', parent=root_module['ns3::SocketFactory']) ## packet-socket-server.h (module 'network'): ns3::PacketSocketServer [class] module.add_class('PacketSocketServer', parent=root_module['ns3::Application']) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## packetbb.h (module 'network'): ns3::PbbAddressBlock [class] module.add_class('PbbAddressBlock', parent=root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >']) typehandlers.add_type_alias(u'std::list< ns3::Address > iterator', u'ns3::PbbAddressBlock::AddressIterator') typehandlers.add_type_alias(u'std::list< ns3::Address > iterator*', u'ns3::PbbAddressBlock::AddressIterator*') typehandlers.add_type_alias(u'std::list< ns3::Address > iterator&', u'ns3::PbbAddressBlock::AddressIterator&') typehandlers.add_type_alias(u'std::list< ns3::Address > const_iterator', u'ns3::PbbAddressBlock::ConstAddressIterator') typehandlers.add_type_alias(u'std::list< ns3::Address > const_iterator*', u'ns3::PbbAddressBlock::ConstAddressIterator*') typehandlers.add_type_alias(u'std::list< ns3::Address > const_iterator&', u'ns3::PbbAddressBlock::ConstAddressIterator&') typehandlers.add_type_alias(u'std::list< unsigned char > iterator', u'ns3::PbbAddressBlock::PrefixIterator') typehandlers.add_type_alias(u'std::list< unsigned char > iterator*', u'ns3::PbbAddressBlock::PrefixIterator*') typehandlers.add_type_alias(u'std::list< unsigned char > iterator&', u'ns3::PbbAddressBlock::PrefixIterator&') typehandlers.add_type_alias(u'std::list< unsigned char > const_iterator', u'ns3::PbbAddressBlock::ConstPrefixIterator') typehandlers.add_type_alias(u'std::list< unsigned char > const_iterator*', u'ns3::PbbAddressBlock::ConstPrefixIterator*') typehandlers.add_type_alias(u'std::list< unsigned char > const_iterator&', u'ns3::PbbAddressBlock::ConstPrefixIterator&') typehandlers.add_type_alias(u'ns3::PbbAddressTlvBlock::Iterator', u'ns3::PbbAddressBlock::TlvIterator') typehandlers.add_type_alias(u'ns3::PbbAddressTlvBlock::Iterator*', u'ns3::PbbAddressBlock::TlvIterator*') typehandlers.add_type_alias(u'ns3::PbbAddressTlvBlock::Iterator&', u'ns3::PbbAddressBlock::TlvIterator&') typehandlers.add_type_alias(u'ns3::PbbAddressTlvBlock::ConstIterator', u'ns3::PbbAddressBlock::ConstTlvIterator') typehandlers.add_type_alias(u'ns3::PbbAddressTlvBlock::ConstIterator*', u'ns3::PbbAddressBlock::ConstTlvIterator*') typehandlers.add_type_alias(u'ns3::PbbAddressTlvBlock::ConstIterator&', u'ns3::PbbAddressBlock::ConstTlvIterator&') ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4 [class] module.add_class('PbbAddressBlockIpv4', parent=root_module['ns3::PbbAddressBlock']) ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6 [class] module.add_class('PbbAddressBlockIpv6', parent=root_module['ns3::PbbAddressBlock']) ## packetbb.h (module 'network'): ns3::PbbMessage [class] module.add_class('PbbMessage', parent=root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >']) typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > iterator', u'ns3::PbbMessage::TlvIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > iterator*', u'ns3::PbbMessage::TlvIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > iterator&', u'ns3::PbbMessage::TlvIterator&') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > const_iterator', u'ns3::PbbMessage::ConstTlvIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > const_iterator*', u'ns3::PbbMessage::ConstTlvIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > const_iterator&', u'ns3::PbbMessage::ConstTlvIterator&') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressBlock > > iterator', u'ns3::PbbMessage::AddressBlockIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressBlock > > iterator*', u'ns3::PbbMessage::AddressBlockIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressBlock > > iterator&', u'ns3::PbbMessage::AddressBlockIterator&') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressBlock > > const_iterator', u'ns3::PbbMessage::ConstAddressBlockIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressBlock > > const_iterator*', u'ns3::PbbMessage::ConstAddressBlockIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbAddressBlock > > const_iterator&', u'ns3::PbbMessage::ConstAddressBlockIterator&') ## packetbb.h (module 'network'): ns3::PbbMessageIpv4 [class] module.add_class('PbbMessageIpv4', parent=root_module['ns3::PbbMessage']) ## packetbb.h (module 'network'): ns3::PbbMessageIpv6 [class] module.add_class('PbbMessageIpv6', parent=root_module['ns3::PbbMessage']) ## packetbb.h (module 'network'): ns3::PbbPacket [class] module.add_class('PbbPacket', parent=root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >']) typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > iterator', u'ns3::PbbPacket::TlvIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > iterator*', u'ns3::PbbPacket::TlvIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > iterator&', u'ns3::PbbPacket::TlvIterator&') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > const_iterator', u'ns3::PbbPacket::ConstTlvIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > const_iterator*', u'ns3::PbbPacket::ConstTlvIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbTlv > > const_iterator&', u'ns3::PbbPacket::ConstTlvIterator&') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbMessage > > iterator', u'ns3::PbbPacket::MessageIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbMessage > > iterator*', u'ns3::PbbPacket::MessageIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbMessage > > iterator&', u'ns3::PbbPacket::MessageIterator&') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbMessage > > const_iterator', u'ns3::PbbPacket::ConstMessageIterator') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbMessage > > const_iterator*', u'ns3::PbbPacket::ConstMessageIterator*') typehandlers.add_type_alias(u'std::list< ns3::Ptr< ns3::PbbMessage > > const_iterator&', u'ns3::PbbPacket::ConstMessageIterator&') ## packetbb.h (module 'network'): ns3::PbbTlv [class] module.add_class('PbbTlv', parent=root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >']) ## probe.h (module 'stats'): ns3::Probe [class] module.add_class('Probe', import_from_module='ns.stats', parent=root_module['ns3::DataCollectionObject']) ## queue.h (module 'network'): ns3::Queue<ns3::Packet> [class] module.add_class('Queue', template_parameters=['ns3::Packet'], parent=root_module['ns3::QueueBase']) typehandlers.add_type_alias(u'ns3::Packet', u'ns3::Queue< ns3::Packet > ItemType') typehandlers.add_type_alias(u'ns3::Packet*', u'ns3::Queue< ns3::Packet > ItemType*') typehandlers.add_type_alias(u'ns3::Packet&', u'ns3::Queue< ns3::Packet > ItemType&') module.add_typedef(root_module['ns3::Packet'], 'ItemType') ## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem> [class] module.add_class('Queue', template_parameters=['ns3::QueueDiscItem'], parent=root_module['ns3::QueueBase']) typehandlers.add_type_alias(u'ns3::QueueDiscItem', u'ns3::Queue< ns3::QueueDiscItem > ItemType') typehandlers.add_type_alias(u'ns3::QueueDiscItem*', u'ns3::Queue< ns3::QueueDiscItem > ItemType*') typehandlers.add_type_alias(u'ns3::QueueDiscItem&', u'ns3::Queue< ns3::QueueDiscItem > ItemType&') ## queue-item.h (module 'network'): ns3::QueueItem [class] module.add_class('QueueItem', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) ## queue-item.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration] module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem']) typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::QueueItem const > )', u'ns3::QueueItem::TracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::QueueItem const > )*', u'ns3::QueueItem::TracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::QueueItem const > )&', u'ns3::QueueItem::TracedCallback&') ## queue-size.h (module 'network'): ns3::QueueSizeChecker [class] module.add_class('QueueSizeChecker', parent=root_module['ns3::AttributeChecker']) ## queue-size.h (module 'network'): ns3::QueueSizeValue [class] module.add_class('QueueSizeValue', parent=root_module['ns3::AttributeValue']) ## error-model.h (module 'network'): ns3::RateErrorModel [class] module.add_class('RateErrorModel', parent=root_module['ns3::ErrorModel']) ## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit [enumeration] module.add_enum('ErrorUnit', ['ERROR_UNIT_BIT', 'ERROR_UNIT_BYTE', 'ERROR_UNIT_PACKET'], outer_class=root_module['ns3::RateErrorModel']) ## error-model.h (module 'network'): ns3::ReceiveListErrorModel [class] module.add_class('ReceiveListErrorModel', parent=root_module['ns3::ErrorModel']) ## simple-channel.h (module 'network'): ns3::SimpleChannel [class] module.add_class('SimpleChannel', parent=root_module['ns3::Channel']) ## simple-net-device.h (module 'network'): ns3::SimpleNetDevice [class] module.add_class('SimpleNetDevice', parent=root_module['ns3::NetDevice']) ## 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']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', parent=root_module['ns3::AttributeValue']) ## error-model.h (module 'network'): ns3::BinaryErrorModel [class] module.add_class('BinaryErrorModel', parent=root_module['ns3::ErrorModel']) ## error-model.h (module 'network'): ns3::BurstErrorModel [class] module.add_class('BurstErrorModel', parent=root_module['ns3::ErrorModel']) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', template_parameters=['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'const ns3::Address &', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['bool', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::QueueDiscItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::QueueDiscItem>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'const ns3::Address &', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'unsigned int', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int> [class] module.add_class('CounterCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=root_module['ns3::DataCalculator']) ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue<ns3::Packet> [class] module.add_class('DropTailQueue', template_parameters=['ns3::Packet'], parent=root_module['ns3::Queue< ns3::Packet >']) ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue<ns3::QueueDiscItem> [class] module.add_class('DropTailQueue', template_parameters=['ns3::QueueDiscItem'], parent=root_module['ns3::Queue< ns3::QueueDiscItem >']) ## error-channel.h (module 'network'): ns3::ErrorChannel [class] module.add_class('ErrorChannel', parent=root_module['ns3::SimpleChannel']) ## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator [class] module.add_class('PacketCounterCalculator', parent=root_module['ns3::CounterCalculator< unsigned int >']) ## packet-probe.h (module 'network'): ns3::PacketProbe [class] module.add_class('PacketProbe', parent=root_module['ns3::Probe']) ## packetbb.h (module 'network'): ns3::PbbAddressTlv [class] module.add_class('PbbAddressTlv', parent=root_module['ns3::PbbTlv']) ## queue-item.h (module 'network'): ns3::QueueDiscItem [class] module.add_class('QueueDiscItem', parent=root_module['ns3::QueueItem']) module.add_container('std::map< std::string, ns3::LogComponent * >', ('std::string', 'ns3::LogComponent *'), container_type=u'map') module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type=u'list') module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector') module.add_container('std::list< unsigned int >', 'unsigned int', container_type=u'list') typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >', u'ns3::SequenceNumber32') typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >*', u'ns3::SequenceNumber32*') typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >&', u'ns3::SequenceNumber32&') typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned short, short >', u'ns3::SequenceNumber16') typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned short, short >*', u'ns3::SequenceNumber16*') typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned short, short >&', u'ns3::SequenceNumber16&') typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >', u'ns3::SequenceNumber8') typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >*', u'ns3::SequenceNumber8*') typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >&', u'ns3::SequenceNumber8&') 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'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::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'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'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'void ( * ) ( std::ostream & )', u'ns3::TimePrinter') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )*', u'ns3::TimePrinter*') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )&', u'ns3::TimePrinter&') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )', u'ns3::NodePrinter') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )*', u'ns3::NodePrinter*') typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )&', u'ns3::NodePrinter&') ## 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) ## Register a nested module for the namespace tests nested_module = module.add_cpp_namespace('tests') register_types_ns3_tests(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 *, std::size_t const )', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, std::size_t const )*', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, std::size_t const )&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, std::size_t const )', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, std::size_t const )*', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, std::size_t const )&', 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 ( * ) ( 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 ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 )', u'ns3::TracedValueCallback::SequenceNumber32') typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 )*', u'ns3::TracedValueCallback::SequenceNumber32*') typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 )&', u'ns3::TracedValueCallback::SequenceNumber32&') 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 ( * ) ( 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 ( * ) ( 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 ( * ) ( 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&') 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 ( * ) ( 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 ( * ) ( 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 ( * ) ( )', u'ns3::TracedValueCallback::Void') typehandlers.add_type_alias(u'void ( * ) ( )*', u'ns3::TracedValueCallback::Void*') typehandlers.add_type_alias(u'void ( * ) ( )&', u'ns3::TracedValueCallback::Void&') def register_types_ns3_addressUtils(module): root_module = module.get_root() def register_types_ns3_internal(module): root_module = module.get_root() def register_types_ns3_tests(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3ApplicationContainer_methods(root_module, root_module['ns3::ApplicationContainer']) register_Ns3AsciiFile_methods(root_module, root_module['ns3::AsciiFile']) register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper']) register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3ChannelList_methods(root_module, root_module['ns3::ChannelList']) register_Ns3DataOutputCallback_methods(root_module, root_module['ns3::DataOutputCallback']) register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate']) register_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeAccessor >']) register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeChecker >']) register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeValue >']) register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, root_module['ns3::DefaultDeleter< ns3::CallbackImplBase >']) register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, root_module['ns3::DefaultDeleter< ns3::EventImpl >']) register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Hash::Implementation >']) register_Ns3DefaultDeleter__Ns3NetDeviceQueue_methods(root_module, root_module['ns3::DefaultDeleter< ns3::NetDeviceQueue >']) register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, root_module['ns3::DefaultDeleter< ns3::NixVector >']) register_Ns3DefaultDeleter__Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::DefaultDeleter< ns3::OutputStreamWrapper >']) register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Packet >']) register_Ns3DefaultDeleter__Ns3PbbAddressBlock_methods(root_module, root_module['ns3::DefaultDeleter< ns3::PbbAddressBlock >']) register_Ns3DefaultDeleter__Ns3PbbMessage_methods(root_module, root_module['ns3::DefaultDeleter< ns3::PbbMessage >']) register_Ns3DefaultDeleter__Ns3PbbTlv_methods(root_module, root_module['ns3::DefaultDeleter< ns3::PbbTlv >']) register_Ns3DefaultDeleter__Ns3QueueItem_methods(root_module, root_module['ns3::DefaultDeleter< ns3::QueueItem >']) register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::TraceSourceAccessor >']) register_Ns3DelayJitterEstimation_methods(root_module, root_module['ns3::DelayJitterEstimation']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) 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_Ns3Mac8Address_methods(root_module, root_module['ns3::Mac8Address']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3NodeList_methods(root_module, root_module['ns3::NodeList']) 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_Ns3PacketSocketAddress_methods(root_module, root_module['ns3::PacketSocketAddress']) register_Ns3PacketSocketHelper_methods(root_module, root_module['ns3::PacketSocketHelper']) 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_Ns3PbbAddressTlvBlock_methods(root_module, root_module['ns3::PbbAddressTlvBlock']) register_Ns3PbbTlvBlock_methods(root_module, root_module['ns3::PbbTlvBlock']) register_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile']) register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper']) register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice']) register_Ns3QueueSize_methods(root_module, root_module['ns3::QueueSize']) register_Ns3SequenceNumber32_methods(root_module, root_module['ns3::SequenceNumber32']) register_Ns3SequenceNumber16_methods(root_module, root_module['ns3::SequenceNumber16']) register_Ns3SimpleNetDeviceHelper_methods(root_module, root_module['ns3::SimpleNetDeviceHelper']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3StatisticalSummary_methods(root_module, root_module['ns3::StatisticalSummary']) register_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_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_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_Ns3DeviceNameTag_methods(root_module, root_module['ns3::DeviceNameTag']) register_Ns3FlowIdTag_methods(root_module, root_module['ns3::FlowIdTag']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3LlcSnapHeader_methods(root_module, root_module['ns3::LlcSnapHeader']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PacketBurst_methods(root_module, root_module['ns3::PacketBurst']) register_Ns3PacketSocketTag_methods(root_module, root_module['ns3::PacketSocketTag']) register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper']) register_Ns3QueueBase_methods(root_module, root_module['ns3::QueueBase']) register_Ns3QueueLimits_methods(root_module, root_module['ns3::QueueLimits']) register_Ns3RadiotapHeader_methods(root_module, root_module['ns3::RadiotapHeader']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >']) register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >']) register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >']) register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >']) register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3SllHeader_methods(root_module, root_module['ns3::SllHeader']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketFactory_methods(root_module, root_module['ns3::SocketFactory']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) 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_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_Ns3Application_methods(root_module, root_module['ns3::Application']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker']) register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DataCalculator_methods(root_module, root_module['ns3::DataCalculator']) register_Ns3DataCollectionObject_methods(root_module, root_module['ns3::DataCollectionObject']) register_Ns3DataOutputInterface_methods(root_module, root_module['ns3::DataOutputInterface']) register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker']) register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue']) register_Ns3DynamicQueueLimits_methods(root_module, root_module['ns3::DynamicQueueLimits']) 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_Ns3ErrorModel_methods(root_module, root_module['ns3::ErrorModel']) register_Ns3EthernetHeader_methods(root_module, root_module['ns3::EthernetHeader']) register_Ns3EthernetTrailer_methods(root_module, root_module['ns3::EthernetTrailer']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3ListErrorModel_methods(root_module, root_module['ns3::ListErrorModel']) 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_Ns3MinMaxAvgTotalCalculator__Unsigned_int_methods(root_module, root_module['ns3::MinMaxAvgTotalCalculator< unsigned int >']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue']) register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3PacketSizeMinMaxAvgTotalCalculator_methods(root_module, root_module['ns3::PacketSizeMinMaxAvgTotalCalculator']) register_Ns3PacketSocket_methods(root_module, root_module['ns3::PacketSocket']) register_Ns3PacketSocketClient_methods(root_module, root_module['ns3::PacketSocketClient']) register_Ns3PacketSocketFactory_methods(root_module, root_module['ns3::PacketSocketFactory']) register_Ns3PacketSocketServer_methods(root_module, root_module['ns3::PacketSocketServer']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3PbbAddressBlock_methods(root_module, root_module['ns3::PbbAddressBlock']) register_Ns3PbbAddressBlockIpv4_methods(root_module, root_module['ns3::PbbAddressBlockIpv4']) register_Ns3PbbAddressBlockIpv6_methods(root_module, root_module['ns3::PbbAddressBlockIpv6']) register_Ns3PbbMessage_methods(root_module, root_module['ns3::PbbMessage']) register_Ns3PbbMessageIpv4_methods(root_module, root_module['ns3::PbbMessageIpv4']) register_Ns3PbbMessageIpv6_methods(root_module, root_module['ns3::PbbMessageIpv6']) register_Ns3PbbPacket_methods(root_module, root_module['ns3::PbbPacket']) register_Ns3PbbTlv_methods(root_module, root_module['ns3::PbbTlv']) register_Ns3Probe_methods(root_module, root_module['ns3::Probe']) register_Ns3Queue__Ns3Packet_methods(root_module, root_module['ns3::Queue< ns3::Packet >']) register_Ns3Queue__Ns3QueueDiscItem_methods(root_module, root_module['ns3::Queue< ns3::QueueDiscItem >']) register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem']) register_Ns3QueueSizeChecker_methods(root_module, root_module['ns3::QueueSizeChecker']) register_Ns3QueueSizeValue_methods(root_module, root_module['ns3::QueueSizeValue']) register_Ns3RateErrorModel_methods(root_module, root_module['ns3::RateErrorModel']) register_Ns3ReceiveListErrorModel_methods(root_module, root_module['ns3::ReceiveListErrorModel']) register_Ns3SimpleChannel_methods(root_module, root_module['ns3::SimpleChannel']) register_Ns3SimpleNetDevice_methods(root_module, root_module['ns3::SimpleNetDevice']) 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_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3BinaryErrorModel_methods(root_module, root_module['ns3::BinaryErrorModel']) register_Ns3BurstErrorModel_methods(root_module, root_module['ns3::BurstErrorModel']) register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3QueueDiscItem__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::QueueDiscItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Unsigned_int_Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CounterCalculator__Unsigned_int_methods(root_module, root_module['ns3::CounterCalculator< unsigned int >']) register_Ns3DropTailQueue__Ns3Packet_methods(root_module, root_module['ns3::DropTailQueue< ns3::Packet >']) register_Ns3DropTailQueue__Ns3QueueDiscItem_methods(root_module, root_module['ns3::DropTailQueue< ns3::QueueDiscItem >']) register_Ns3ErrorChannel_methods(root_module, root_module['ns3::ErrorChannel']) register_Ns3PacketCounterCalculator_methods(root_module, root_module['ns3::PacketCounterCalculator']) register_Ns3PacketProbe_methods(root_module, root_module['ns3::PacketProbe']) register_Ns3PbbAddressTlv_methods(root_module, root_module['ns3::PbbAddressTlv']) register_Ns3QueueDiscItem_methods(root_module, root_module['ns3::QueueDiscItem']) 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_binary_comparison_operator('<') cls.add_output_stream_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) [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_Ns3ApplicationContainer_methods(root_module, cls): ## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::ApplicationContainer const & arg0) [constructor] cls.add_constructor([param('ns3::ApplicationContainer const &', 'arg0')]) ## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer() [constructor] cls.add_constructor([]) ## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::Ptr<ns3::Application> application) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Application >', 'application')]) ## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(std::string name) [constructor] cls.add_constructor([param('std::string', 'name')]) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::ApplicationContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::ApplicationContainer', 'other')]) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Application >', 'application')]) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(std::string name) [member function] cls.add_method('Add', 'void', [param('std::string', 'name')]) ## application-container.h (module 'network'): ns3::ApplicationContainer::Iterator ns3::ApplicationContainer::Begin() const [member function] cls.add_method('Begin', 'ns3::ApplicationContainer::Iterator', [], is_const=True) ## application-container.h (module 'network'): ns3::ApplicationContainer::Iterator ns3::ApplicationContainer::End() const [member function] cls.add_method('End', 'ns3::ApplicationContainer::Iterator', [], is_const=True) ## application-container.h (module 'network'): ns3::Ptr<ns3::Application> ns3::ApplicationContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'i')], is_const=True) ## application-container.h (module 'network'): uint32_t ns3::ApplicationContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Start(ns3::Time start) [member function] cls.add_method('Start', 'void', [param('ns3::Time', 'start')]) ## application-container.h (module 'network'): void ns3::ApplicationContainer::StartWithJitter(ns3::Time start, ns3::Ptr<ns3::RandomVariableStream> rv) [member function] cls.add_method('StartWithJitter', 'void', [param('ns3::Time', 'start'), param('ns3::Ptr< ns3::RandomVariableStream >', 'rv')]) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Stop(ns3::Time stop) [member function] cls.add_method('Stop', 'void', [param('ns3::Time', 'stop')]) return def register_Ns3AsciiFile_methods(root_module, cls): ## ascii-file.h (module 'network'): ns3::AsciiFile::AsciiFile() [constructor] cls.add_constructor([]) ## ascii-file.h (module 'network'): bool ns3::AsciiFile::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## ascii-file.h (module 'network'): bool ns3::AsciiFile::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## ascii-file.h (module 'network'): void ns3::AsciiFile::Open(std::string const & filename, std::ios_base::openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::ios_base::openmode', 'mode')]) ## ascii-file.h (module 'network'): void ns3::AsciiFile::Close() [member function] cls.add_method('Close', 'void', []) ## ascii-file.h (module 'network'): void ns3::AsciiFile::Read(std::string & line) [member function] cls.add_method('Read', 'void', [param('std::string &', 'line')]) ## ascii-file.h (module 'network'): static bool ns3::AsciiFile::Diff(std::string const & f1, std::string const & f2, uint64_t & lineNumber) [member function] cls.add_method('Diff', 'bool', [param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint64_t &', 'lineNumber')], is_static=True) return def register_Ns3AsciiTraceHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [constructor] cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::ios_base::openmode filemode=std::ios_base::out) [member function] cls.add_method('CreateFileStream', 'ns3::Ptr< ns3::OutputStreamWrapper >', [param('std::string', 'filename'), param('std::ios_base::openmode', 'filemode', default_value='std::ios_base::out')]) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3AsciiTraceHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice(ns3::AsciiTraceHelperForDevice const & arg0) [constructor] cls.add_constructor([param('ns3::AsciiTraceHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::NetDevice> nd) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::NetDevice >', 'nd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, std::string ndName, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ndName) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ndName')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t deviceid) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(std::string prefix) [member function] cls.add_method('EnableAsciiAll', 'void', [param('std::string', 'prefix')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiAll', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function] cls.add_method('EnableAsciiInternal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [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<const ns3::AttributeChecker> 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'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<const ns3::AttributeChecker> 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) [constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## 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'): 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) [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) [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) [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) [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) [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) [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) [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_Ns3ChannelList_methods(root_module, cls): ## channel-list.h (module 'network'): ns3::ChannelList::ChannelList() [constructor] cls.add_constructor([]) ## channel-list.h (module 'network'): ns3::ChannelList::ChannelList(ns3::ChannelList const & arg0) [constructor] cls.add_constructor([param('ns3::ChannelList const &', 'arg0')]) ## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::Add(ns3::Ptr<ns3::Channel> channel) [member function] cls.add_method('Add', 'uint32_t', [param('ns3::Ptr< ns3::Channel >', 'channel')], is_static=True) ## channel-list.h (module 'network'): static ns3::ChannelList::Iterator ns3::ChannelList::Begin() [member function] cls.add_method('Begin', 'ns3::ChannelList::Iterator', [], is_static=True) ## channel-list.h (module 'network'): static ns3::ChannelList::Iterator ns3::ChannelList::End() [member function] cls.add_method('End', 'ns3::ChannelList::Iterator', [], is_static=True) ## channel-list.h (module 'network'): static ns3::Ptr<ns3::Channel> ns3::ChannelList::GetChannel(uint32_t n) [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [param('uint32_t', 'n')], is_static=True) ## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::GetNChannels() [member function] cls.add_method('GetNChannels', 'uint32_t', [], is_static=True) return def register_Ns3DataOutputCallback_methods(root_module, cls): ## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback() [constructor] cls.add_constructor([]) ## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback(ns3::DataOutputCallback const & arg0) [constructor] cls.add_constructor([param('ns3::DataOutputCallback const &', 'arg0')]) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, int val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('int', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, uint32_t val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('uint32_t', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, double val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('double', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, std::string val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('std::string', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, ns3::Time val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('ns3::Time', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputStatistic(std::string key, std::string variable, ns3::StatisticalSummary const * statSum) [member function] cls.add_method('OutputStatistic', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('ns3::StatisticalSummary const *', 'statSum')], is_pure_virtual=True, is_virtual=True) return def register_Ns3DataRate_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('>=') ## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [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_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeAccessor> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeAccessor > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeAccessor>::Delete(ns3::AttributeAccessor * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeAccessor *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeChecker> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeChecker > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeChecker>::Delete(ns3::AttributeChecker * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeChecker *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeValue> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeValue > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeValue>::Delete(ns3::AttributeValue * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeValue *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter(ns3::DefaultDeleter<ns3::CallbackImplBase> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::CallbackImplBase > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::CallbackImplBase>::Delete(ns3::CallbackImplBase * object) [member function] cls.add_method('Delete', 'void', [param('ns3::CallbackImplBase *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter(ns3::DefaultDeleter<ns3::EventImpl> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::EventImpl > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::EventImpl>::Delete(ns3::EventImpl * object) [member function] cls.add_method('Delete', 'void', [param('ns3::EventImpl *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter(ns3::DefaultDeleter<ns3::Hash::Implementation> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Hash::Implementation > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Hash::Implementation>::Delete(ns3::Hash::Implementation * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Hash::Implementation *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3NetDeviceQueue_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NetDeviceQueue>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NetDeviceQueue>::DefaultDeleter(ns3::DefaultDeleter<ns3::NetDeviceQueue> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::NetDeviceQueue > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::NetDeviceQueue>::Delete(ns3::NetDeviceQueue * object) [member function] cls.add_method('Delete', 'void', [param('ns3::NetDeviceQueue *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter(ns3::DefaultDeleter<ns3::NixVector> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::NixVector > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::NixVector>::Delete(ns3::NixVector * object) [member function] cls.add_method('Delete', 'void', [param('ns3::NixVector *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3OutputStreamWrapper_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::OutputStreamWrapper>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::OutputStreamWrapper>::DefaultDeleter(ns3::DefaultDeleter<ns3::OutputStreamWrapper> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::OutputStreamWrapper > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::OutputStreamWrapper>::Delete(ns3::OutputStreamWrapper * object) [member function] cls.add_method('Delete', 'void', [param('ns3::OutputStreamWrapper *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter(ns3::DefaultDeleter<ns3::Packet> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Packet > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Packet>::Delete(ns3::Packet * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Packet *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3PbbAddressBlock_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::PbbAddressBlock>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::PbbAddressBlock>::DefaultDeleter(ns3::DefaultDeleter<ns3::PbbAddressBlock> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::PbbAddressBlock > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::PbbAddressBlock>::Delete(ns3::PbbAddressBlock * object) [member function] cls.add_method('Delete', 'void', [param('ns3::PbbAddressBlock *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3PbbMessage_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::PbbMessage>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::PbbMessage>::DefaultDeleter(ns3::DefaultDeleter<ns3::PbbMessage> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::PbbMessage > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::PbbMessage>::Delete(ns3::PbbMessage * object) [member function] cls.add_method('Delete', 'void', [param('ns3::PbbMessage *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3PbbTlv_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::PbbTlv>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::PbbTlv>::DefaultDeleter(ns3::DefaultDeleter<ns3::PbbTlv> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::PbbTlv > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::PbbTlv>::Delete(ns3::PbbTlv * object) [member function] cls.add_method('Delete', 'void', [param('ns3::PbbTlv *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3QueueItem_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::QueueItem>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::QueueItem>::DefaultDeleter(ns3::DefaultDeleter<ns3::QueueItem> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::QueueItem > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::QueueItem>::Delete(ns3::QueueItem * object) [member function] cls.add_method('Delete', 'void', [param('ns3::QueueItem *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::TraceSourceAccessor> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::TraceSourceAccessor > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::TraceSourceAccessor>::Delete(ns3::TraceSourceAccessor * object) [member function] cls.add_method('Delete', 'void', [param('ns3::TraceSourceAccessor *', 'object')], is_static=True) return def register_Ns3DelayJitterEstimation_methods(root_module, cls): ## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation::DelayJitterEstimation(ns3::DelayJitterEstimation const & arg0) [constructor] cls.add_constructor([param('ns3::DelayJitterEstimation const &', 'arg0')]) ## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation::DelayJitterEstimation() [constructor] cls.add_constructor([]) ## delay-jitter-estimation.h (module 'network'): ns3::Time ns3::DelayJitterEstimation::GetLastDelay() const [member function] cls.add_method('GetLastDelay', 'ns3::Time', [], is_const=True) ## delay-jitter-estimation.h (module 'network'): uint64_t ns3::DelayJitterEstimation::GetLastJitter() const [member function] cls.add_method('GetLastJitter', 'uint64_t', [], is_const=True) ## delay-jitter-estimation.h (module 'network'): static void ns3::DelayJitterEstimation::PrepareTx(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('PrepareTx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')], is_static=True) ## delay-jitter-estimation.h (module 'network'): void ns3::DelayJitterEstimation::RecordRx(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('RecordRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [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) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::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, std::size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('std::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_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): uint8_t ns3::InetSocketAddress::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [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_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [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_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_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) [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::MakeAutoconfiguredAddress(ns3::Mac8Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac8Address', '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::MakeAutoconfiguredLinkLocalAddress(ns3::Mac8Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac8Address', '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_output_stream_operator() cls.add_binary_comparison_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) [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) [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::LogLevel::LOG_NONE) [constructor] cls.add_constructor([param('std::string const &', 'name'), param('std::string const &', 'file'), param('ns3::LogLevel const', 'mask', default_value='::ns3::LogLevel::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 ns3::LogComponent::ComponentList * ns3::LogComponent::GetComponentList() [member function] cls.add_method('GetComponentList', 'ns3::LogComponent::ComponentList *', [], 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_binary_comparison_operator('<') cls.add_output_stream_operator() ## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(ns3::Mac16Address const & arg0) [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_binary_comparison_operator('<') cls.add_output_stream_operator() ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [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_binary_comparison_operator('<') cls.add_output_stream_operator() ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(ns3::Mac64Address const & arg0) [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_Ns3Mac8Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() ## mac8-address.h (module 'network'): ns3::Mac8Address::Mac8Address(ns3::Mac8Address const & arg0) [constructor] cls.add_constructor([param('ns3::Mac8Address const &', 'arg0')]) ## mac8-address.h (module 'network'): ns3::Mac8Address::Mac8Address() [constructor] cls.add_constructor([]) ## mac8-address.h (module 'network'): ns3::Mac8Address::Mac8Address(uint8_t addr) [constructor] cls.add_constructor([param('uint8_t', 'addr')]) ## mac8-address.h (module 'network'): static ns3::Mac8Address ns3::Mac8Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac8Address', [], is_static=True) ## mac8-address.h (module 'network'): static ns3::Mac8Address ns3::Mac8Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac8Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac8-address.h (module 'network'): void ns3::Mac8Address::CopyFrom(uint8_t const * pBuffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'pBuffer')]) ## mac8-address.h (module 'network'): void ns3::Mac8Address::CopyTo(uint8_t * pBuffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'pBuffer')], is_const=True) ## mac8-address.h (module 'network'): static ns3::Mac8Address ns3::Mac8Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac8Address', [], is_static=True) ## mac8-address.h (module 'network'): static bool ns3::Mac8Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [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'): ns3::NetDeviceContainer::Iterator ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', 'ns3::NetDeviceContainer::Iterator', [], is_const=True) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::Iterator ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', 'ns3::NetDeviceContainer::Iterator', [], 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) [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'): ns3::NodeContainer::Iterator ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', 'ns3::NodeContainer::Iterator', [], is_const=True) ## node-container.h (module 'network'): bool ns3::NodeContainer::Contains(uint32_t id) const [member function] cls.add_method('Contains', 'bool', [param('uint32_t', 'id')], 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'): ns3::NodeContainer::Iterator ns3::NodeContainer::End() const [member function] cls.add_method('End', 'ns3::NodeContainer::Iterator', [], 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_Ns3NodeList_methods(root_module, cls): ## node-list.h (module 'network'): ns3::NodeList::NodeList() [constructor] cls.add_constructor([]) ## node-list.h (module 'network'): ns3::NodeList::NodeList(ns3::NodeList const & arg0) [constructor] cls.add_constructor([param('ns3::NodeList const &', 'arg0')]) ## node-list.h (module 'network'): static uint32_t ns3::NodeList::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'uint32_t', [param('ns3::Ptr< ns3::Node >', 'node')], is_static=True) ## node-list.h (module 'network'): static ns3::NodeList::Iterator ns3::NodeList::Begin() [member function] cls.add_method('Begin', 'ns3::NodeList::Iterator', [], is_static=True) ## node-list.h (module 'network'): static ns3::NodeList::Iterator ns3::NodeList::End() [member function] cls.add_method('End', 'ns3::NodeList::Iterator', [], is_static=True) ## node-list.h (module 'network'): static uint32_t ns3::NodeList::GetNNodes() [member function] cls.add_method('GetNNodes', 'uint32_t', [], is_static=True) ## node-list.h (module 'network'): static ns3::Ptr<ns3::Node> ns3::NodeList::GetNode(uint32_t n) [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'n')], is_static=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) [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) [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) [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) [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) [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) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::type [variable] cls.add_instance_attribute('type', 'ns3::PacketMetadata::Item::ItemType', 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) [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_Ns3PacketSocketAddress_methods(root_module, cls): ## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress(ns3::PacketSocketAddress const & arg0) [constructor] cls.add_constructor([param('ns3::PacketSocketAddress const &', 'arg0')]) ## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress() [constructor] cls.add_constructor([]) ## packet-socket-address.h (module 'network'): static ns3::PacketSocketAddress ns3::PacketSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::PacketSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## packet-socket-address.h (module 'network'): ns3::Address ns3::PacketSocketAddress::GetPhysicalAddress() const [member function] cls.add_method('GetPhysicalAddress', 'ns3::Address', [], is_const=True) ## packet-socket-address.h (module 'network'): uint16_t ns3::PacketSocketAddress::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint16_t', [], is_const=True) ## packet-socket-address.h (module 'network'): uint32_t ns3::PacketSocketAddress::GetSingleDevice() const [member function] cls.add_method('GetSingleDevice', 'uint32_t', [], is_const=True) ## packet-socket-address.h (module 'network'): static bool ns3::PacketSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## packet-socket-address.h (module 'network'): bool ns3::PacketSocketAddress::IsSingleDevice() const [member function] cls.add_method('IsSingleDevice', 'bool', [], is_const=True) ## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetAllDevices() [member function] cls.add_method('SetAllDevices', 'void', []) ## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetPhysicalAddress(ns3::Address const address) [member function] cls.add_method('SetPhysicalAddress', 'void', [param('ns3::Address const', 'address')]) ## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetProtocol(uint16_t protocol) [member function] cls.add_method('SetProtocol', 'void', [param('uint16_t', 'protocol')]) ## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetSingleDevice(uint32_t device) [member function] cls.add_method('SetSingleDevice', 'void', [param('uint32_t', 'device')]) return def register_Ns3PacketSocketHelper_methods(root_module, cls): ## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper() [constructor] cls.add_constructor([]) ## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper(ns3::PacketSocketHelper const & arg0) [constructor] cls.add_constructor([param('ns3::PacketSocketHelper const &', 'arg0')]) ## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'void', [param('std::string', 'nodeName')], is_const=True) ## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'void', [param('ns3::NodeContainer', 'c')], is_const=True) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [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) [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) [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) [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) [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_Ns3PbbAddressTlvBlock_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock(ns3::PbbAddressTlvBlock const & arg0) [constructor] cls.add_constructor([param('ns3::PbbAddressTlvBlock const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Back() const [member function] cls.add_method('Back', 'ns3::Ptr< ns3::PbbAddressTlv >', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::Iterator ns3::PbbAddressTlvBlock::Begin() [member function] cls.add_method('Begin', 'ns3::PbbAddressTlvBlock::Iterator', []) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::ConstIterator ns3::PbbAddressTlvBlock::Begin() const [member function] cls.add_method('Begin', 'ns3::PbbAddressTlvBlock::ConstIterator', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Clear() [member function] cls.add_method('Clear', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): bool ns3::PbbAddressTlvBlock::Empty() const [member function] cls.add_method('Empty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::Iterator ns3::PbbAddressTlvBlock::End() [member function] cls.add_method('End', 'ns3::PbbAddressTlvBlock::Iterator', []) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::ConstIterator ns3::PbbAddressTlvBlock::End() const [member function] cls.add_method('End', 'ns3::PbbAddressTlvBlock::ConstIterator', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::Iterator ns3::PbbAddressTlvBlock::Erase(ns3::PbbAddressTlvBlock::Iterator position) [member function] cls.add_method('Erase', 'ns3::PbbAddressTlvBlock::Iterator', [param('std::list< ns3::Ptr< ns3::PbbAddressTlv > > iterator', 'position')]) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::Iterator ns3::PbbAddressTlvBlock::Erase(ns3::PbbAddressTlvBlock::Iterator first, ns3::PbbAddressTlvBlock::Iterator last) [member function] cls.add_method('Erase', 'ns3::PbbAddressTlvBlock::Iterator', [param('std::list< ns3::Ptr< ns3::PbbAddressTlv > > iterator', 'first'), param('std::list< ns3::Ptr< ns3::PbbAddressTlv > > iterator', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Front() const [member function] cls.add_method('Front', 'ns3::Ptr< ns3::PbbAddressTlv >', [], is_const=True) ## packetbb.h (module 'network'): uint32_t ns3::PbbAddressTlvBlock::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::Iterator ns3::PbbAddressTlvBlock::Insert(ns3::PbbAddressTlvBlock::Iterator position, ns3::Ptr<ns3::PbbAddressTlv> const tlv) [member function] cls.add_method('Insert', 'ns3::PbbAddressTlvBlock::Iterator', [param('std::list< ns3::Ptr< ns3::PbbAddressTlv > > iterator', 'position'), param('ns3::Ptr< ns3::PbbAddressTlv > const', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopBack() [member function] cls.add_method('PopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopFront() [member function] cls.add_method('PopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushBack(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function] cls.add_method('PushBack', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushFront(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function] cls.add_method('PushFront', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): int ns3::PbbAddressTlvBlock::Size() const [member function] cls.add_method('Size', 'int', [], is_const=True) return def register_Ns3PbbTlvBlock_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock(ns3::PbbTlvBlock const & arg0) [constructor] cls.add_constructor([param('ns3::PbbTlvBlock const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Back() const [member function] cls.add_method('Back', 'ns3::Ptr< ns3::PbbTlv >', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbTlvBlock::Iterator ns3::PbbTlvBlock::Begin() [member function] cls.add_method('Begin', 'ns3::PbbTlvBlock::Iterator', []) ## packetbb.h (module 'network'): ns3::PbbTlvBlock::ConstIterator ns3::PbbTlvBlock::Begin() const [member function] cls.add_method('Begin', 'ns3::PbbTlvBlock::ConstIterator', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Clear() [member function] cls.add_method('Clear', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): bool ns3::PbbTlvBlock::Empty() const [member function] cls.add_method('Empty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbTlvBlock::Iterator ns3::PbbTlvBlock::End() [member function] cls.add_method('End', 'ns3::PbbTlvBlock::Iterator', []) ## packetbb.h (module 'network'): ns3::PbbTlvBlock::ConstIterator ns3::PbbTlvBlock::End() const [member function] cls.add_method('End', 'ns3::PbbTlvBlock::ConstIterator', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbTlvBlock::Iterator ns3::PbbTlvBlock::Erase(ns3::PbbTlvBlock::Iterator position) [member function] cls.add_method('Erase', 'ns3::PbbTlvBlock::Iterator', [param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'position')]) ## packetbb.h (module 'network'): ns3::PbbTlvBlock::Iterator ns3::PbbTlvBlock::Erase(ns3::PbbTlvBlock::Iterator first, ns3::PbbTlvBlock::Iterator last) [member function] cls.add_method('Erase', 'ns3::PbbTlvBlock::Iterator', [param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'first'), param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Front() const [member function] cls.add_method('Front', 'ns3::Ptr< ns3::PbbTlv >', [], is_const=True) ## packetbb.h (module 'network'): uint32_t ns3::PbbTlvBlock::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbTlvBlock::Iterator ns3::PbbTlvBlock::Insert(ns3::PbbTlvBlock::Iterator position, ns3::Ptr<ns3::PbbTlv> const tlv) [member function] cls.add_method('Insert', 'ns3::PbbTlvBlock::Iterator', [param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopBack() [member function] cls.add_method('PopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopFront() [member function] cls.add_method('PopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('PushBack', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('PushFront', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): int ns3::PbbTlvBlock::Size() const [member function] cls.add_method('Size', 'int', [], is_const=True) return def register_Ns3PcapFile_methods(root_module, cls): ## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor] cls.add_constructor([]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t & packets, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT) [member function] cls.add_method('Diff', 'bool', [param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint32_t &', 'sec'), param('uint32_t &', 'usec'), param('uint32_t &', 'packets'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT')], is_static=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file.h (module 'network'): bool ns3::PcapFile::GetSwapMode() [member function] cls.add_method('GetSwapMode', 'bool', []) ## pcap-file.h (module 'network'): int32_t ns3::PcapFile::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Init(uint32_t dataLinkType, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT, int32_t timeZoneCorrection=ns3::PcapFile::ZONE_DEFAULT, bool swapMode=false, bool nanosecMode=false) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT'), param('int32_t', 'timeZoneCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT'), param('bool', 'swapMode', default_value='false'), param('bool', 'nanosecMode', default_value='false')]) ## pcap-file.h (module 'network'): bool ns3::PcapFile::IsNanoSecMode() [member function] cls.add_method('IsNanoSecMode', 'bool', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Open(std::string const & filename, std::ios_base::openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::ios_base::openmode', 'mode')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Read(uint8_t * const data, uint32_t maxBytes, uint32_t & tsSec, uint32_t & tsUsec, uint32_t & inclLen, uint32_t & origLen, uint32_t & readLen) [member function] cls.add_method('Read', 'void', [param('uint8_t * const', 'data'), param('uint32_t', 'maxBytes'), param('uint32_t &', 'tsSec'), param('uint32_t &', 'tsUsec'), param('uint32_t &', 'inclLen'), param('uint32_t &', 'origLen'), param('uint32_t &', 'readLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, uint8_t const * const data, uint32_t totalLen) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('uint8_t const * const', 'data'), param('uint32_t', 'totalLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Header const & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header const &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): ns3::PcapFile::SNAPLEN_DEFAULT [variable] cls.add_static_attribute('SNAPLEN_DEFAULT', 'uint32_t const', is_const=True) ## pcap-file.h (module 'network'): ns3::PcapFile::ZONE_DEFAULT [variable] cls.add_static_attribute('ZONE_DEFAULT', 'int32_t const', is_const=True) return def register_Ns3PcapHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper(ns3::PcapHelper const & arg0) [constructor] cls.add_constructor([param('ns3::PcapHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::PcapFileWrapper> ns3::PcapHelper::CreateFile(std::string filename, std::ios_base::openmode filemode, ns3::PcapHelper::DataLinkType dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=0) [member function] cls.add_method('CreateFile', 'ns3::Ptr< ns3::PcapFileWrapper >', [param('std::string', 'filename'), param('std::ios_base::openmode', 'filemode'), param('ns3::PcapHelper::DataLinkType', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='0')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3PcapHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [constructor] cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function] cls.add_method('EnablePcapAll', 'void', [param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3QueueSize_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('>=') ## queue-size.h (module 'network'): ns3::QueueSize::QueueSize(ns3::QueueSize const & arg0) [constructor] cls.add_constructor([param('ns3::QueueSize const &', 'arg0')]) ## queue-size.h (module 'network'): ns3::QueueSize::QueueSize() [constructor] cls.add_constructor([]) ## queue-size.h (module 'network'): ns3::QueueSize::QueueSize(ns3::QueueSizeUnit unit, uint32_t value) [constructor] cls.add_constructor([param('ns3::QueueSizeUnit', 'unit'), param('uint32_t', 'value')]) ## queue-size.h (module 'network'): ns3::QueueSize::QueueSize(std::string size) [constructor] cls.add_constructor([param('std::string', 'size')]) ## queue-size.h (module 'network'): ns3::QueueSizeUnit ns3::QueueSize::GetUnit() const [member function] cls.add_method('GetUnit', 'ns3::QueueSizeUnit', [], is_const=True) ## queue-size.h (module 'network'): uint32_t ns3::QueueSize::GetValue() const [member function] cls.add_method('GetValue', 'uint32_t', [], is_const=True) return def register_Ns3SequenceNumber32_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_numeric_operator('+', root_module['ns3::SequenceNumber32'], root_module['ns3::SequenceNumber32'], param('ns3::SequenceNumber< unsigned int, int > const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::SequenceNumber32'], root_module['ns3::SequenceNumber32'], param('int', u'right')) cls.add_inplace_numeric_operator('+=', param('int', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::SequenceNumber32'], root_module['ns3::SequenceNumber32'], param('int', u'right')) cls.add_inplace_numeric_operator('-=', param('int', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('>=') ## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned int, int>::SequenceNumber() [constructor] cls.add_constructor([]) ## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned int, int>::SequenceNumber(unsigned int value) [constructor] cls.add_constructor([param('unsigned int', 'value')]) ## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned int, int>::SequenceNumber(ns3::SequenceNumber<unsigned int, int> const & value) [constructor] cls.add_constructor([param('ns3::SequenceNumber< unsigned int, int > const &', 'value')]) ## sequence-number.h (module 'network'): unsigned int ns3::SequenceNumber<unsigned int, int>::GetValue() const [member function] cls.add_method('GetValue', 'unsigned int', [], is_const=True) return def register_Ns3SequenceNumber16_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_numeric_operator('+', root_module['ns3::SequenceNumber16'], root_module['ns3::SequenceNumber16'], param('ns3::SequenceNumber< unsigned short, short > const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::SequenceNumber16'], root_module['ns3::SequenceNumber16'], param('short int', u'right')) cls.add_inplace_numeric_operator('+=', param('short int', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::SequenceNumber16'], root_module['ns3::SequenceNumber16'], param('short int', u'right')) cls.add_inplace_numeric_operator('-=', param('short int', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('>=') ## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned short, short>::SequenceNumber() [constructor] cls.add_constructor([]) ## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned short, short>::SequenceNumber(short unsigned int value) [constructor] cls.add_constructor([param('short unsigned int', 'value')]) ## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned short, short>::SequenceNumber(ns3::SequenceNumber<unsigned short, short> const & value) [constructor] cls.add_constructor([param('ns3::SequenceNumber< unsigned short, short > const &', 'value')]) ## sequence-number.h (module 'network'): short unsigned int ns3::SequenceNumber<unsigned short, short>::GetValue() const [member function] cls.add_method('GetValue', 'short unsigned int', [], is_const=True) return def register_Ns3SimpleNetDeviceHelper_methods(root_module, cls): ## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper::SimpleNetDeviceHelper(ns3::SimpleNetDeviceHelper const & arg0) [constructor] cls.add_constructor([param('ns3::SimpleNetDeviceHelper const &', 'arg0')]) ## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper::SimpleNetDeviceHelper() [constructor] cls.add_constructor([]) ## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::SimpleChannel> channel) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::SimpleChannel >', 'channel')], is_const=True) ## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::NodeContainer const & c) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer const &', 'c')], is_const=True) ## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::NodeContainer const & c, ns3::Ptr<ns3::SimpleChannel> channel) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer const &', 'c'), param('ns3::Ptr< ns3::SimpleChannel >', 'channel')], is_const=True) ## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetChannel(std::string type, 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()) [member function] cls.add_method('SetChannel', 'void', [param('std::string', 'type'), 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()')]) ## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetChannelAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetChannelAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetNetDevicePointToPointMode(bool pointToPointMode) [member function] cls.add_method('SetNetDevicePointToPointMode', 'void', [param('bool', 'pointToPointMode')]) ## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetQueue(std::string type, 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()) [member function] cls.add_method('SetQueue', 'void', [param('std::string', 'type'), 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()')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static uint64_t ns3::Simulator::GetEventCount() [member function] cls.add_method('GetEventCount', 'uint64_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'delay')], is_static=True) return def register_Ns3StatisticalSummary_methods(root_module, cls): ## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary() [constructor] cls.add_constructor([]) ## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary(ns3::StatisticalSummary const & arg0) [constructor] cls.add_constructor([param('ns3::StatisticalSummary const &', 'arg0')]) ## data-calculator.h (module 'stats'): long int ns3::StatisticalSummary::getCount() const [member function] cls.add_method('getCount', 'long int', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMax() const [member function] cls.add_method('getMax', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMean() const [member function] cls.add_method('getMean', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMin() const [member function] cls.add_method('getMin', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSqrSum() const [member function] cls.add_method('getSqrSum', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getStddev() const [member function] cls.add_method('getStddev', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSum() const [member function] cls.add_method('getSum', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getVariance() const [member function] cls.add_method('getVariance', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3SystemWallClockMs_methods(root_module, cls): ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [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) [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) [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 v) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t v) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'v')]) ## 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) [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) [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'): ns3::TracedValue<unsigned int>::TracedValue(ns3::TracedValue<unsigned int> const & other) [constructor] cls.add_constructor([param('ns3::TracedValue< unsigned int > const &', 'other')]) ## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue(ns3::TracedValue<unsigned int> const & other) [constructor] cls.add_constructor([param('ns3::TracedValue< unsigned int > const &', 'other')]) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Connect(ns3::CallbackBase const & cb, std::string 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::string 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_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) [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<const ns3::AttributeAccessor> accessor, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::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::SupportLevel::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<const ns3::AttributeAccessor> accessor, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::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::SupportLevel::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<const ns3::TraceSourceAccessor> 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<const ns3::TraceSourceAccessor> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::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::SupportLevel::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(std::size_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('std::size_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(std::size_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('std::size_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'std::size_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'): ns3::TypeId::hash_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'ns3::TypeId::hash_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(uint16_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint16_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint16_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint16_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(std::size_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('std::size_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'std::size_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(ns3::TypeId::hash_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(ns3::TypeId::hash_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<const ns3::TraceSourceAccessor> 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<const ns3::TraceSourceAccessor> 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(std::size_t i, ns3::Ptr<const ns3::AttributeValue> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('std::size_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=[u'ns3::QueueBase']) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent() [member function] cls.add_method('SetParent', 'ns3::TypeId', [], template_parameters=[u'ns3::Object']) ## 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) [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) 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) [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_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) [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::Time'], root_module['ns3::int64x64_t'], param('ns3::Time 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_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_comparison_operator('!=') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('>=') cls.add_output_stream_operator() 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_unary_numeric_operator('-') ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(double const value) [constructor] cls.add_constructor([param('double const', 'value')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long double const value) [constructor] cls.add_constructor([param('long double const', 'value')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(int const v) [constructor] cls.add_constructor([param('int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long int const v) [constructor] cls.add_constructor([param('long int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int const v) [constructor] cls.add_constructor([param('long long int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int const v) [constructor] cls.add_constructor([param('unsigned int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int const v) [constructor] cls.add_constructor([param('long unsigned int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int const v) [constructor] cls.add_constructor([param('long long unsigned int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t const hi, uint64_t const lo) [constructor] cls.add_constructor([param('int64_t const', 'hi'), param('uint64_t const', 'lo')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-128.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-128.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-128.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-128.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t const v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t const', 'v')], is_static=True) ## int64x64-128.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-128.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) [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'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')], 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_Ns3DeviceNameTag_methods(root_module, cls): ## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag(ns3::DeviceNameTag const & arg0) [constructor] cls.add_constructor([param('ns3::DeviceNameTag const &', 'arg0')]) ## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag() [constructor] cls.add_constructor([]) ## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## packet-socket.h (module 'network'): std::string ns3::DeviceNameTag::GetDeviceName() const [member function] cls.add_method('GetDeviceName', 'std::string', [], is_const=True) ## packet-socket.h (module 'network'): ns3::TypeId ns3::DeviceNameTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): uint32_t ns3::DeviceNameTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): static ns3::TypeId ns3::DeviceNameTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): void ns3::DeviceNameTag::SetDeviceName(std::string n) [member function] cls.add_method('SetDeviceName', 'void', [param('std::string', 'n')]) return def register_Ns3FlowIdTag_methods(root_module, cls): ## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(ns3::FlowIdTag const & arg0) [constructor] cls.add_constructor([param('ns3::FlowIdTag const &', 'arg0')]) ## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag() [constructor] cls.add_constructor([]) ## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(uint32_t flowId) [constructor] cls.add_constructor([param('uint32_t', 'flowId')]) ## flow-id-tag.h (module 'network'): static uint32_t ns3::FlowIdTag::AllocateFlowId() [member function] cls.add_method('AllocateFlowId', 'uint32_t', [], is_static=True) ## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Deserialize(ns3::TagBuffer buf) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buf')], is_virtual=True) ## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetFlowId() const [member function] cls.add_method('GetFlowId', 'uint32_t', [], is_const=True) ## flow-id-tag.h (module 'network'): ns3::TypeId ns3::FlowIdTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## flow-id-tag.h (module 'network'): static ns3::TypeId ns3::FlowIdTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Serialize(ns3::TagBuffer buf) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buf')], is_const=True, is_virtual=True) ## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::SetFlowId(uint32_t flowId) [member function] cls.add_method('SetFlowId', 'void', [param('uint32_t', 'flowId')]) 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) [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_Ns3LlcSnapHeader_methods(root_module, cls): ## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader(ns3::LlcSnapHeader const & arg0) [constructor] cls.add_constructor([param('ns3::LlcSnapHeader const &', 'arg0')]) ## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader() [constructor] cls.add_constructor([]) ## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## llc-snap-header.h (module 'network'): ns3::TypeId ns3::LlcSnapHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## llc-snap-header.h (module 'network'): uint16_t ns3::LlcSnapHeader::GetType() [member function] cls.add_method('GetType', 'uint16_t', []) ## llc-snap-header.h (module 'network'): static ns3::TypeId ns3::LlcSnapHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::SetType(uint16_t type) [member function] cls.add_method('SetType', 'void', [param('uint16_t', 'type')]) 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) [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) [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<const ns3::Object> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3PacketBurst_methods(root_module, cls): ## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst(ns3::PacketBurst const & arg0) [constructor] cls.add_constructor([param('ns3::PacketBurst const &', 'arg0')]) ## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst() [constructor] cls.add_constructor([]) ## packet-burst.h (module 'network'): void ns3::PacketBurst::AddPacket(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('AddPacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')]) ## packet-burst.h (module 'network'): std::list<ns3::Ptr<ns3::Packet>, std::allocator<ns3::Ptr<ns3::Packet> > >::const_iterator ns3::PacketBurst::Begin() const [member function] cls.add_method('Begin', 'std::list< ns3::Ptr< ns3::Packet > > const_iterator', [], is_const=True) ## packet-burst.h (module 'network'): ns3::Ptr<ns3::PacketBurst> ns3::PacketBurst::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::PacketBurst >', [], is_const=True) ## packet-burst.h (module 'network'): std::list<ns3::Ptr<ns3::Packet>, std::allocator<ns3::Ptr<ns3::Packet> > >::const_iterator ns3::PacketBurst::End() const [member function] cls.add_method('End', 'std::list< ns3::Ptr< ns3::Packet > > const_iterator', [], is_const=True) ## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## packet-burst.h (module 'network'): std::list<ns3::Ptr<ns3::Packet>, std::allocator<ns3::Ptr<ns3::Packet> > > ns3::PacketBurst::GetPackets() const [member function] cls.add_method('GetPackets', 'std::list< ns3::Ptr< ns3::Packet > >', [], is_const=True) ## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet-burst.h (module 'network'): static ns3::TypeId ns3::PacketBurst::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-burst.h (module 'network'): void ns3::PacketBurst::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3PacketSocketTag_methods(root_module, cls): ## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag(ns3::PacketSocketTag const & arg0) [constructor] cls.add_constructor([param('ns3::PacketSocketTag const &', 'arg0')]) ## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag() [constructor] cls.add_constructor([]) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## packet-socket.h (module 'network'): ns3::Address ns3::PacketSocketTag::GetDestAddress() const [member function] cls.add_method('GetDestAddress', 'ns3::Address', [], is_const=True) ## packet-socket.h (module 'network'): ns3::TypeId ns3::PacketSocketTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): ns3::NetDevice::PacketType ns3::PacketSocketTag::GetPacketType() const [member function] cls.add_method('GetPacketType', 'ns3::NetDevice::PacketType', [], is_const=True) ## packet-socket.h (module 'network'): uint32_t ns3::PacketSocketTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocketTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetDestAddress(ns3::Address a) [member function] cls.add_method('SetDestAddress', 'void', [param('ns3::Address', 'a')]) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetPacketType(ns3::NetDevice::PacketType t) [member function] cls.add_method('SetPacketType', 'void', [param('ns3::NetDevice::PacketType', 't')]) return def register_Ns3PcapFileWrapper_methods(root_module, cls): ## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor] cls.add_constructor([]) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::ios_base::openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::ios_base::openmode', 'mode')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Header const & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Header const &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')]) ## pcap-file-wrapper.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PcapFileWrapper::Read(ns3::Time & t) [member function] cls.add_method('Read', 'ns3::Ptr< ns3::Packet >', [param('ns3::Time &', 't')]) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) return def register_Ns3QueueBase_methods(root_module, cls): ## queue.h (module 'network'): ns3::QueueBase::QueueBase(ns3::QueueBase const & arg0) [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'): ns3::QueueSize ns3::QueueBase::GetCurrentSize() const [member function] cls.add_method('GetCurrentSize', 'ns3::QueueSize', [], is_const=True) ## queue.h (module 'network'): ns3::QueueSize ns3::QueueBase::GetMaxSize() const [member function] cls.add_method('GetMaxSize', 'ns3::QueueSize', [], 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::SetMaxSize(ns3::QueueSize size) [member function] cls.add_method('SetMaxSize', 'void', [param('ns3::QueueSize', 'size')]) return def register_Ns3QueueLimits_methods(root_module, cls): ## queue-limits.h (module 'network'): ns3::QueueLimits::QueueLimits() [constructor] cls.add_constructor([]) ## queue-limits.h (module 'network'): ns3::QueueLimits::QueueLimits(ns3::QueueLimits const & arg0) [constructor] cls.add_constructor([param('ns3::QueueLimits const &', 'arg0')]) ## queue-limits.h (module 'network'): int32_t ns3::QueueLimits::Available() const [member function] cls.add_method('Available', 'int32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## queue-limits.h (module 'network'): void ns3::QueueLimits::Completed(uint32_t count) [member function] cls.add_method('Completed', 'void', [param('uint32_t', 'count')], is_pure_virtual=True, is_virtual=True) ## queue-limits.h (module 'network'): static ns3::TypeId ns3::QueueLimits::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue-limits.h (module 'network'): void ns3::QueueLimits::Queued(uint32_t count) [member function] cls.add_method('Queued', 'void', [param('uint32_t', 'count')], is_pure_virtual=True, is_virtual=True) ## queue-limits.h (module 'network'): void ns3::QueueLimits::Reset() [member function] cls.add_method('Reset', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3RadiotapHeader_methods(root_module, cls): ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader(ns3::RadiotapHeader const & arg0) [constructor] cls.add_constructor([param('ns3::RadiotapHeader const &', 'arg0')]) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader() [constructor] cls.add_constructor([]) ## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## radiotap-header.h (module 'network'): ns3::TypeId ns3::RadiotapHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## radiotap-header.h (module 'network'): static ns3::TypeId ns3::RadiotapHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAmpduStatus(uint32_t referenceNumber, uint16_t flags, uint8_t crc) [member function] cls.add_method('SetAmpduStatus', 'void', [param('uint32_t', 'referenceNumber'), param('uint16_t', 'flags'), param('uint8_t', 'crc')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaNoisePower(double noise) [member function] cls.add_method('SetAntennaNoisePower', 'void', [param('double', 'noise')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaSignalPower(double signal) [member function] cls.add_method('SetAntennaSignalPower', 'void', [param('double', 'signal')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetChannelFrequencyAndFlags(uint16_t frequency, uint16_t flags) [member function] cls.add_method('SetChannelFrequencyAndFlags', 'void', [param('uint16_t', 'frequency'), param('uint16_t', 'flags')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetFrameFlags(uint8_t flags) [member function] cls.add_method('SetFrameFlags', 'void', [param('uint8_t', 'flags')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetHeFields(uint16_t data1, uint16_t data2, uint16_t data3, uint16_t data5) [member function] cls.add_method('SetHeFields', 'void', [param('uint16_t', 'data1'), param('uint16_t', 'data2'), param('uint16_t', 'data3'), param('uint16_t', 'data5')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetMcsFields(uint8_t known, uint8_t flags, uint8_t mcs) [member function] cls.add_method('SetMcsFields', 'void', [param('uint8_t', 'known'), param('uint8_t', 'flags'), param('uint8_t', 'mcs')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetRate(uint8_t rate) [member function] cls.add_method('SetRate', 'void', [param('uint8_t', 'rate')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetTsft(uint64_t tsft) [member function] cls.add_method('SetTsft', 'void', [param('uint64_t', 'tsft')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetVhtFields(uint16_t known, uint8_t flags, uint8_t bandwidth, uint8_t * mcs_nss, uint8_t coding, uint8_t group_id, uint16_t partial_aid) [member function] cls.add_method('SetVhtFields', 'void', [param('uint16_t', 'known'), param('uint8_t', 'flags'), param('uint8_t', 'bandwidth'), param('uint8_t *', 'mcs_nss'), param('uint8_t', 'coding'), param('uint8_t', 'group_id'), param('uint16_t', 'partial_aid')]) return def register_Ns3RandomVariableStream_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function] cls.add_method('SetStream', 'void', [param('int64_t', 'stream')]) ## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function] cls.add_method('GetStream', 'int64_t', [], is_const=True) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function] cls.add_method('SetAntithetic', 'void', [param('bool', 'isAntithetic')]) ## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function] cls.add_method('IsAntithetic', 'bool', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function] cls.add_method('Peek', 'ns3::RngStream *', [], is_const=True, visibility='protected') return def register_Ns3SequentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function] cls.add_method('GetIncrement', 'ns3::Ptr< ns3::RandomVariableStream >', [], is_const=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function] cls.add_method('GetConsecutive', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter< ns3::PbbAddressBlock > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter< ns3::PbbMessage > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter< ns3::PbbPacket > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter< ns3::PbbTlv > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) return def register_Ns3SllHeader_methods(root_module, cls): ## sll-header.h (module 'network'): ns3::SllHeader::SllHeader(ns3::SllHeader const & arg0) [constructor] cls.add_constructor([param('ns3::SllHeader const &', 'arg0')]) ## sll-header.h (module 'network'): ns3::SllHeader::SllHeader() [constructor] cls.add_constructor([]) ## sll-header.h (module 'network'): uint32_t ns3::SllHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## sll-header.h (module 'network'): uint16_t ns3::SllHeader::GetArpType() const [member function] cls.add_method('GetArpType', 'uint16_t', [], is_const=True) ## sll-header.h (module 'network'): ns3::TypeId ns3::SllHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## sll-header.h (module 'network'): ns3::SllHeader::PacketType ns3::SllHeader::GetPacketType() const [member function] cls.add_method('GetPacketType', 'ns3::SllHeader::PacketType', [], is_const=True) ## sll-header.h (module 'network'): uint32_t ns3::SllHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## sll-header.h (module 'network'): static ns3::TypeId ns3::SllHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## sll-header.h (module 'network'): void ns3::SllHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## sll-header.h (module 'network'): void ns3::SllHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## sll-header.h (module 'network'): void ns3::SllHeader::SetArpType(uint16_t arphdType) [member function] cls.add_method('SetArpType', 'void', [param('uint16_t', 'arphdType')]) ## sll-header.h (module 'network'): void ns3::SllHeader::SetPacketType(ns3::SllHeader::PacketType type) [member function] cls.add_method('SetPacketType', 'void', [param('ns3::SllHeader::PacketType', 'type')]) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function] cls.add_method('GetPeerName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function] cls.add_method('IpTos2Priority', 'uint8_t', [param('uint8_t', 'ipTos')], is_static=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address, std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function] cls.add_method('Ipv6LeaveGroup', 'void', [], is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketFactory_methods(root_module, cls): ## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory(ns3::SocketFactory const & arg0) [constructor] cls.add_constructor([param('ns3::SocketFactory const &', 'arg0')]) ## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory() [constructor] cls.add_constructor([]) ## socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::SocketFactory::CreateSocket() [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## socket-factory.h (module 'network'): static ns3::TypeId ns3::SocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketPriorityTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketPriorityTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): 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('>') 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_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], 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_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::int64x64_t const &', u'right')) 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() ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [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) [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) [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::Deserialize(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')], 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_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3Application_methods(root_module, cls): ## application.h (module 'network'): ns3::Application::Application(ns3::Application const & arg0) [constructor] cls.add_constructor([param('ns3::Application const &', 'arg0')]) ## application.h (module 'network'): ns3::Application::Application() [constructor] cls.add_constructor([]) ## application.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Application::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## application.h (module 'network'): static ns3::TypeId ns3::Application::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## application.h (module 'network'): void ns3::Application::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## application.h (module 'network'): void ns3::Application::SetStartTime(ns3::Time start) [member function] cls.add_method('SetStartTime', 'void', [param('ns3::Time', 'start')]) ## application.h (module 'network'): void ns3::Application::SetStopTime(ns3::Time stop) [member function] cls.add_method('SetStopTime', 'void', [param('ns3::Time', 'stop')]) ## application.h (module 'network'): void ns3::Application::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## application.h (module 'network'): void ns3::Application::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## application.h (module 'network'): void ns3::Application::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## application.h (module 'network'): void ns3::Application::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [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) [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) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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) [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<const ns3::CallbackImplBase> 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') ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::ObjectBase*']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'void']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'unsigned int']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::NetDevice> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Packet const> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'unsigned short']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Address const&']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::NetDevice::PacketType']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::QueueDiscItem const> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Socket> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'bool']) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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(std::size_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('std::size_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'): std::size_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'std::size_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_Ns3DataCalculator_methods(root_module, cls): ## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator(ns3::DataCalculator const & arg0) [constructor] cls.add_constructor([param('ns3::DataCalculator const &', 'arg0')]) ## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator() [constructor] cls.add_constructor([]) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Disable() [member function] cls.add_method('Disable', 'void', []) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Enable() [member function] cls.add_method('Enable', 'void', []) ## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetContext() const [member function] cls.add_method('GetContext', 'std::string', [], is_const=True) ## data-calculator.h (module 'stats'): bool ns3::DataCalculator::GetEnabled() const [member function] cls.add_method('GetEnabled', 'bool', [], is_const=True) ## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetKey() const [member function] cls.add_method('GetKey', 'std::string', [], is_const=True) ## data-calculator.h (module 'stats'): static ns3::TypeId ns3::DataCalculator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Output(ns3::DataOutputCallback & callback) const [member function] cls.add_method('Output', 'void', [param('ns3::DataOutputCallback &', 'callback')], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetContext(std::string const context) [member function] cls.add_method('SetContext', 'void', [param('std::string const', 'context')]) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetKey(std::string const key) [member function] cls.add_method('SetKey', 'void', [param('std::string const', 'key')]) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Start(ns3::Time const & startTime) [member function] cls.add_method('Start', 'void', [param('ns3::Time const &', 'startTime')], is_virtual=True) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Stop(ns3::Time const & stopTime) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'stopTime')], is_virtual=True) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3DataCollectionObject_methods(root_module, cls): ## data-collection-object.h (module 'stats'): ns3::DataCollectionObject::DataCollectionObject(ns3::DataCollectionObject const & arg0) [constructor] cls.add_constructor([param('ns3::DataCollectionObject const &', 'arg0')]) ## data-collection-object.h (module 'stats'): ns3::DataCollectionObject::DataCollectionObject() [constructor] cls.add_constructor([]) ## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::Disable() [member function] cls.add_method('Disable', 'void', []) ## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::Enable() [member function] cls.add_method('Enable', 'void', []) ## data-collection-object.h (module 'stats'): std::string ns3::DataCollectionObject::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## data-collection-object.h (module 'stats'): static ns3::TypeId ns3::DataCollectionObject::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## data-collection-object.h (module 'stats'): bool ns3::DataCollectionObject::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True, is_virtual=True) ## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::SetName(std::string name) [member function] cls.add_method('SetName', 'void', [param('std::string', 'name')]) return def register_Ns3DataOutputInterface_methods(root_module, cls): ## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface(ns3::DataOutputInterface const & arg0) [constructor] cls.add_constructor([param('ns3::DataOutputInterface const &', 'arg0')]) ## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface() [constructor] cls.add_constructor([]) ## data-output-interface.h (module 'stats'): std::string ns3::DataOutputInterface::GetFilePrefix() const [member function] cls.add_method('GetFilePrefix', 'std::string', [], is_const=True) ## data-output-interface.h (module 'stats'): static ns3::TypeId ns3::DataOutputInterface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::Output(ns3::DataCollector & dc) [member function] cls.add_method('Output', 'void', [param('ns3::DataCollector &', 'dc')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::SetFilePrefix(std::string const prefix) [member function] cls.add_method('SetFilePrefix', 'void', [param('std::string const', 'prefix')]) ## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3DataRateChecker_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [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::DataRate const & value) [constructor] cls.add_constructor([param('ns3::DataRate const &', 'value')]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [constructor] cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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, std::size_t length) [member function] cls.add_method('SetValueArray', 'void', [param('double *', 'values'), param('std::size_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(double const & value) [constructor] cls.add_constructor([param('double const &', 'value')]) ## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [constructor] cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3DynamicQueueLimits_methods(root_module, cls): ## dynamic-queue-limits.h (module 'network'): ns3::DynamicQueueLimits::DynamicQueueLimits(ns3::DynamicQueueLimits const & arg0) [constructor] cls.add_constructor([param('ns3::DynamicQueueLimits const &', 'arg0')]) ## dynamic-queue-limits.h (module 'network'): ns3::DynamicQueueLimits::DynamicQueueLimits() [constructor] cls.add_constructor([]) ## dynamic-queue-limits.h (module 'network'): int32_t ns3::DynamicQueueLimits::Available() const [member function] cls.add_method('Available', 'int32_t', [], is_const=True, is_virtual=True) ## dynamic-queue-limits.h (module 'network'): void ns3::DynamicQueueLimits::Completed(uint32_t count) [member function] cls.add_method('Completed', 'void', [param('uint32_t', 'count')], is_virtual=True) ## dynamic-queue-limits.h (module 'network'): static ns3::TypeId ns3::DynamicQueueLimits::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## dynamic-queue-limits.h (module 'network'): void ns3::DynamicQueueLimits::Queued(uint32_t count) [member function] cls.add_method('Queued', 'void', [param('uint32_t', 'count')], is_virtual=True) ## dynamic-queue-limits.h (module 'network'): void ns3::DynamicQueueLimits::Reset() [member function] cls.add_method('Reset', 'void', [], is_virtual=True) 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) [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) [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) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3ErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::ErrorModel::ErrorModel(ns3::ErrorModel const & arg0) [constructor] cls.add_constructor([param('ns3::ErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::ErrorModel::ErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): void ns3::ErrorModel::Disable() [member function] cls.add_method('Disable', 'void', []) ## error-model.h (module 'network'): void ns3::ErrorModel::Enable() [member function] cls.add_method('Enable', 'void', []) ## error-model.h (module 'network'): static ns3::TypeId ns3::ErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): bool ns3::ErrorModel::IsCorrupt(ns3::Ptr<ns3::Packet> pkt) [member function] cls.add_method('IsCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'pkt')]) ## error-model.h (module 'network'): bool ns3::ErrorModel::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## error-model.h (module 'network'): void ns3::ErrorModel::Reset() [member function] cls.add_method('Reset', 'void', []) ## error-model.h (module 'network'): bool ns3::ErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], is_pure_virtual=True, visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::ErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3EthernetHeader_methods(root_module, cls): ## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(ns3::EthernetHeader const & arg0) [constructor] cls.add_constructor([param('ns3::EthernetHeader const &', 'arg0')]) ## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(bool hasPreamble) [constructor] cls.add_constructor([param('bool', 'hasPreamble')]) ## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader() [constructor] cls.add_constructor([]) ## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Mac48Address', [], is_const=True) ## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetHeaderSize() const [member function] cls.add_method('GetHeaderSize', 'uint32_t', [], is_const=True) ## ethernet-header.h (module 'network'): ns3::TypeId ns3::EthernetHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ethernet-header.h (module 'network'): uint16_t ns3::EthernetHeader::GetLengthType() const [member function] cls.add_method('GetLengthType', 'uint16_t', [], is_const=True) ## ethernet-header.h (module 'network'): ns3::ethernet_header_t ns3::EthernetHeader::GetPacketType() const [member function] cls.add_method('GetPacketType', 'ns3::ethernet_header_t', [], is_const=True) ## ethernet-header.h (module 'network'): uint64_t ns3::EthernetHeader::GetPreambleSfd() const [member function] cls.add_method('GetPreambleSfd', 'uint64_t', [], is_const=True) ## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Mac48Address', [], is_const=True) ## ethernet-header.h (module 'network'): static ns3::TypeId ns3::EthernetHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetDestination(ns3::Mac48Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Mac48Address', 'destination')]) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetLengthType(uint16_t size) [member function] cls.add_method('SetLengthType', 'void', [param('uint16_t', 'size')]) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetPreambleSfd(uint64_t preambleSfd) [member function] cls.add_method('SetPreambleSfd', 'void', [param('uint64_t', 'preambleSfd')]) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetSource(ns3::Mac48Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Mac48Address', 'source')]) return def register_Ns3EthernetTrailer_methods(root_module, cls): ## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer(ns3::EthernetTrailer const & arg0) [constructor] cls.add_constructor([param('ns3::EthernetTrailer const &', 'arg0')]) ## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer() [constructor] cls.add_constructor([]) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::CalcFcs(ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('CalcFcs', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')]) ## ethernet-trailer.h (module 'network'): bool ns3::EthernetTrailer::CheckFcs(ns3::Ptr<const ns3::Packet> p) const [member function] cls.add_method('CheckFcs', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p')], is_const=True) ## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_virtual=True) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::EnableFcs(bool enable) [member function] cls.add_method('EnableFcs', 'void', [param('bool', 'enable')]) ## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetFcs() const [member function] cls.add_method('GetFcs', 'uint32_t', [], is_const=True) ## ethernet-trailer.h (module 'network'): ns3::TypeId ns3::EthernetTrailer::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetTrailerSize() const [member function] cls.add_method('GetTrailerSize', 'uint32_t', [], is_const=True) ## ethernet-trailer.h (module 'network'): static ns3::TypeId ns3::EthernetTrailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Serialize(ns3::Buffer::Iterator end) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'end')], is_const=True, is_virtual=True) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::SetFcs(uint32_t fcs) [member function] cls.add_method('SetFcs', 'void', [param('uint32_t', 'fcs')]) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3ExponentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3GammaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function] cls.add_method('GetBeta', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha'), param('double', 'beta')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha'), param('uint32_t', 'beta')]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3IntegerValue_methods(root_module, cls): ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor] cls.add_constructor([]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor] cls.add_constructor([param('int64_t const &', 'value')]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [constructor] cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3ListErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::ListErrorModel::ListErrorModel(ns3::ListErrorModel const & arg0) [constructor] cls.add_constructor([param('ns3::ListErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::ListErrorModel::ListErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ListErrorModel::GetList() const [member function] cls.add_method('GetList', 'std::list< unsigned int >', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::ListErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): void ns3::ListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function] cls.add_method('SetList', 'void', [param('std::list< unsigned int > const &', 'packetlist')]) ## error-model.h (module 'network'): bool ns3::ListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::ListErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], 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) [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::Mac16Address const & value) [constructor] cls.add_constructor([param('ns3::Mac16Address const &', 'value')]) ## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Mac16AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Mac64Address const & value) [constructor] cls.add_constructor([param('ns3::Mac64Address const &', 'value')]) ## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Mac64AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3MinMaxAvgTotalCalculator__Unsigned_int_methods(root_module, cls): ## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int>::MinMaxAvgTotalCalculator(ns3::MinMaxAvgTotalCalculator<unsigned int> const & arg0) [constructor] cls.add_constructor([param('ns3::MinMaxAvgTotalCalculator< unsigned int > const &', 'arg0')]) ## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int>::MinMaxAvgTotalCalculator() [constructor] cls.add_constructor([]) ## basic-data-calculators.h (module 'stats'): static ns3::TypeId ns3::MinMaxAvgTotalCalculator<unsigned int>::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Output(ns3::DataOutputCallback & callback) const [member function] cls.add_method('Output', 'void', [param('ns3::DataOutputCallback &', 'callback')], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Reset() [member function] cls.add_method('Reset', 'void', []) ## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Update(unsigned int const i) [member function] cls.add_method('Update', 'void', [param('unsigned int const', 'i')]) ## basic-data-calculators.h (module 'stats'): long int ns3::MinMaxAvgTotalCalculator<unsigned int>::getCount() const [member function] cls.add_method('getCount', 'long int', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMax() const [member function] cls.add_method('getMax', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMean() const [member function] cls.add_method('getMean', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMin() const [member function] cls.add_method('getMin', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getSqrSum() const [member function] cls.add_method('getSqrSum', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getStddev() const [member function] cls.add_method('getStddev', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getSum() const [member function] cls.add_method('getSum', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getVariance() const [member function] cls.add_method('getVariance', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', 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) [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::NetDevice::PromiscReceiveCallback 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::NetDevice::ReceiveCallback cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NetDeviceQueue_methods(root_module, cls): ## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor] cls.add_constructor([]) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function] cls.add_method('Wake', 'void', [], is_virtual=True) ## net-device-queue-interface.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function] cls.add_method('IsStopped', 'bool', [], is_const=True) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::NotifyAggregatedObject(ns3::Ptr<ns3::NetDeviceQueueInterface> ndqi) [member function] cls.add_method('NotifyAggregatedObject', 'void', [param('ns3::Ptr< ns3::NetDeviceQueueInterface >', 'ndqi')]) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::NetDeviceQueue::WakeCallback cb) [member function] cls.add_method('SetWakeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::NotifyQueuedBytes(uint32_t bytes) [member function] cls.add_method('NotifyQueuedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::NotifyTransmittedBytes(uint32_t bytes) [member function] cls.add_method('NotifyTransmittedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::ResetQueueLimits() [member function] cls.add_method('ResetQueueLimits', 'void', []) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::SetQueueLimits(ns3::Ptr<ns3::QueueLimits> ql) [member function] cls.add_method('SetQueueLimits', 'void', [param('ns3::Ptr< ns3::QueueLimits >', 'ql')]) ## net-device-queue-interface.h (module 'network'): ns3::Ptr<ns3::QueueLimits> ns3::NetDeviceQueue::GetQueueLimits() [member function] cls.add_method('GetQueueLimits', 'ns3::Ptr< ns3::QueueLimits >', []) ## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [constructor] cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')]) return def register_Ns3NetDeviceQueueInterface_methods(root_module, cls): ## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [constructor] cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')]) ## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor] cls.add_constructor([]) ## net-device-queue-interface.h (module 'network'): std::size_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function] cls.add_method('GetNTxQueues', 'std::size_t', [], is_const=True) ## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface::SelectQueueCallback ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function] cls.add_method('GetSelectQueueCallback', 'ns3::NetDeviceQueueInterface::SelectQueueCallback', [], is_const=True) ## net-device-queue-interface.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(std::size_t i) const [member function] cls.add_method('GetTxQueue', 'ns3::Ptr< ns3::NetDeviceQueue >', [param('std::size_t', 'i')], is_const=True) ## net-device-queue-interface.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::SetNTxQueues(std::size_t numTxQueues) [member function] cls.add_method('SetNTxQueues', 'void', [param('std::size_t', 'numTxQueues')]) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::NetDeviceQueueInterface::SelectQueueCallback cb) [member function] cls.add_method('SetSelectQueueCallback', 'void', [param('std::function< unsigned long long ( ns3::Ptr< ns3::QueueItem > ) >', 'cb')]) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [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) [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::Node::DeviceAdditionListener 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::Node::ProtocolHandler 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::Node::DeviceAdditionListener 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::Node::ProtocolHandler handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable] cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function] cls.add_method('GetVariance', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [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::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::ios_base::openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::ios_base::openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [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'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header, uint32_t size) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header'), param('uint32_t', 'size')], 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'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header'), param('uint32_t', 'size')]) ## 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_Ns3PacketSizeMinMaxAvgTotalCalculator_methods(root_module, cls): ## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator::PacketSizeMinMaxAvgTotalCalculator(ns3::PacketSizeMinMaxAvgTotalCalculator const & arg0) [constructor] cls.add_constructor([param('ns3::PacketSizeMinMaxAvgTotalCalculator const &', 'arg0')]) ## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator::PacketSizeMinMaxAvgTotalCalculator() [constructor] cls.add_constructor([]) ## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::FrameUpdate(std::string path, ns3::Ptr<const ns3::Packet> packet, ns3::Mac48Address realto) [member function] cls.add_method('FrameUpdate', 'void', [param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'realto')]) ## packet-data-calculators.h (module 'network'): static ns3::TypeId ns3::PacketSizeMinMaxAvgTotalCalculator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::PacketUpdate(std::string path, ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('PacketUpdate', 'void', [param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3PacketSocket_methods(root_module, cls): ## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket(ns3::PacketSocket const & arg0) [constructor] cls.add_constructor([param('ns3::PacketSocket const &', 'arg0')]) ## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket() [constructor] cls.add_constructor([]) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind() [member function] cls.add_method('Bind', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Close() [member function] cls.add_method('Close', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_virtual=True) ## packet-socket.h (module 'network'): bool ns3::PacketSocket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): ns3::Socket::SocketErrno ns3::PacketSocket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::PacketSocket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::GetPeerName(ns3::Address & address) const [member function] cls.add_method('GetPeerName', 'int', [param('ns3::Address &', 'address')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): ns3::Socket::SocketType ns3::PacketSocket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Listen() [member function] cls.add_method('Listen', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_virtual=True) ## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_virtual=True) ## packet-socket.h (module 'network'): bool ns3::PacketSocket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_virtual=True) ## packet-socket.h (module 'network'): void ns3::PacketSocket::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): void ns3::PacketSocket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3PacketSocketClient_methods(root_module, cls): ## packet-socket-client.h (module 'network'): ns3::PacketSocketClient::PacketSocketClient(ns3::PacketSocketClient const & arg0) [constructor] cls.add_constructor([param('ns3::PacketSocketClient const &', 'arg0')]) ## packet-socket-client.h (module 'network'): ns3::PacketSocketClient::PacketSocketClient() [constructor] cls.add_constructor([]) ## packet-socket-client.h (module 'network'): uint8_t ns3::PacketSocketClient::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## packet-socket-client.h (module 'network'): static ns3::TypeId ns3::PacketSocketClient::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::SetRemote(ns3::PacketSocketAddress addr) [member function] cls.add_method('SetRemote', 'void', [param('ns3::PacketSocketAddress', 'addr')]) ## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3PacketSocketFactory_methods(root_module, cls): ## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory(ns3::PacketSocketFactory const & arg0) [constructor] cls.add_constructor([param('ns3::PacketSocketFactory const &', 'arg0')]) ## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory() [constructor] cls.add_constructor([]) ## packet-socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::PacketSocketFactory::CreateSocket() [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## packet-socket-factory.h (module 'network'): static ns3::TypeId ns3::PacketSocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3PacketSocketServer_methods(root_module, cls): ## packet-socket-server.h (module 'network'): ns3::PacketSocketServer::PacketSocketServer(ns3::PacketSocketServer const & arg0) [constructor] cls.add_constructor([param('ns3::PacketSocketServer const &', 'arg0')]) ## packet-socket-server.h (module 'network'): ns3::PacketSocketServer::PacketSocketServer() [constructor] cls.add_constructor([]) ## packet-socket-server.h (module 'network'): static ns3::TypeId ns3::PacketSocketServer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::SetLocal(ns3::PacketSocketAddress addr) [member function] cls.add_method('SetLocal', 'void', [param('ns3::PacketSocketAddress', 'addr')]) ## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=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_Ns3PbbAddressBlock_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock(ns3::PbbAddressBlock const & arg0) [constructor] cls.add_constructor([param('ns3::PbbAddressBlock const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressBack() const [member function] cls.add_method('AddressBack', 'ns3::Address', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::AddressIterator ns3::PbbAddressBlock::AddressBegin() [member function] cls.add_method('AddressBegin', 'ns3::PbbAddressBlock::AddressIterator', []) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::ConstAddressIterator ns3::PbbAddressBlock::AddressBegin() const [member function] cls.add_method('AddressBegin', 'ns3::PbbAddressBlock::ConstAddressIterator', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressClear() [member function] cls.add_method('AddressClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::AddressEmpty() const [member function] cls.add_method('AddressEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::AddressIterator ns3::PbbAddressBlock::AddressEnd() [member function] cls.add_method('AddressEnd', 'ns3::PbbAddressBlock::AddressIterator', []) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::ConstAddressIterator ns3::PbbAddressBlock::AddressEnd() const [member function] cls.add_method('AddressEnd', 'ns3::PbbAddressBlock::ConstAddressIterator', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::AddressIterator ns3::PbbAddressBlock::AddressErase(ns3::PbbAddressBlock::AddressIterator position) [member function] cls.add_method('AddressErase', 'ns3::PbbAddressBlock::AddressIterator', [param('std::list< ns3::Address > iterator', 'position')]) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::AddressIterator ns3::PbbAddressBlock::AddressErase(ns3::PbbAddressBlock::AddressIterator first, ns3::PbbAddressBlock::AddressIterator last) [member function] cls.add_method('AddressErase', 'ns3::PbbAddressBlock::AddressIterator', [param('std::list< ns3::Address > iterator', 'first'), param('std::list< ns3::Address > iterator', 'last')]) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressFront() const [member function] cls.add_method('AddressFront', 'ns3::Address', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::AddressIterator ns3::PbbAddressBlock::AddressInsert(ns3::PbbAddressBlock::AddressIterator position, ns3::Address const value) [member function] cls.add_method('AddressInsert', 'ns3::PbbAddressBlock::AddressIterator', [param('std::list< ns3::Address > iterator', 'position'), param('ns3::Address const', 'value')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopBack() [member function] cls.add_method('AddressPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopFront() [member function] cls.add_method('AddressPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushBack(ns3::Address address) [member function] cls.add_method('AddressPushBack', 'void', [param('ns3::Address', 'address')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushFront(ns3::Address address) [member function] cls.add_method('AddressPushFront', 'void', [param('ns3::Address', 'address')]) ## packetbb.h (module 'network'): int ns3::PbbAddressBlock::AddressSize() const [member function] cls.add_method('AddressSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): uint32_t ns3::PbbAddressBlock::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixBack() const [member function] cls.add_method('PrefixBack', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::PrefixIterator ns3::PbbAddressBlock::PrefixBegin() [member function] cls.add_method('PrefixBegin', 'ns3::PbbAddressBlock::PrefixIterator', []) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::ConstPrefixIterator ns3::PbbAddressBlock::PrefixBegin() const [member function] cls.add_method('PrefixBegin', 'ns3::PbbAddressBlock::ConstPrefixIterator', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixClear() [member function] cls.add_method('PrefixClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::PrefixEmpty() const [member function] cls.add_method('PrefixEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::PrefixIterator ns3::PbbAddressBlock::PrefixEnd() [member function] cls.add_method('PrefixEnd', 'ns3::PbbAddressBlock::PrefixIterator', []) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::ConstPrefixIterator ns3::PbbAddressBlock::PrefixEnd() const [member function] cls.add_method('PrefixEnd', 'ns3::PbbAddressBlock::ConstPrefixIterator', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::PrefixIterator ns3::PbbAddressBlock::PrefixErase(ns3::PbbAddressBlock::PrefixIterator position) [member function] cls.add_method('PrefixErase', 'ns3::PbbAddressBlock::PrefixIterator', [param('std::list< unsigned char > iterator', 'position')]) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::PrefixIterator ns3::PbbAddressBlock::PrefixErase(ns3::PbbAddressBlock::PrefixIterator first, ns3::PbbAddressBlock::PrefixIterator last) [member function] cls.add_method('PrefixErase', 'ns3::PbbAddressBlock::PrefixIterator', [param('std::list< unsigned char > iterator', 'first'), param('std::list< unsigned char > iterator', 'last')]) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixFront() const [member function] cls.add_method('PrefixFront', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::PrefixIterator ns3::PbbAddressBlock::PrefixInsert(ns3::PbbAddressBlock::PrefixIterator position, uint8_t const value) [member function] cls.add_method('PrefixInsert', 'ns3::PbbAddressBlock::PrefixIterator', [param('std::list< unsigned char > iterator', 'position'), param('uint8_t const', 'value')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopBack() [member function] cls.add_method('PrefixPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopFront() [member function] cls.add_method('PrefixPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushBack(uint8_t prefix) [member function] cls.add_method('PrefixPushBack', 'void', [param('uint8_t', 'prefix')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushFront(uint8_t prefix) [member function] cls.add_method('PrefixPushFront', 'void', [param('uint8_t', 'prefix')]) ## packetbb.h (module 'network'): int ns3::PbbAddressBlock::PrefixSize() const [member function] cls.add_method('PrefixSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvBack() [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbAddressTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvBack() const [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbAddressTlv > const', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::TlvIterator ns3::PbbAddressBlock::TlvBegin() [member function] cls.add_method('TlvBegin', 'ns3::PbbAddressBlock::TlvIterator', []) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::ConstTlvIterator ns3::PbbAddressBlock::TlvBegin() const [member function] cls.add_method('TlvBegin', 'ns3::PbbAddressBlock::ConstTlvIterator', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvClear() [member function] cls.add_method('TlvClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::TlvEmpty() const [member function] cls.add_method('TlvEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::TlvIterator ns3::PbbAddressBlock::TlvEnd() [member function] cls.add_method('TlvEnd', 'ns3::PbbAddressBlock::TlvIterator', []) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::ConstTlvIterator ns3::PbbAddressBlock::TlvEnd() const [member function] cls.add_method('TlvEnd', 'ns3::PbbAddressBlock::ConstTlvIterator', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::TlvIterator ns3::PbbAddressBlock::TlvErase(ns3::PbbAddressBlock::TlvIterator position) [member function] cls.add_method('TlvErase', 'ns3::PbbAddressBlock::TlvIterator', [param('ns3::PbbAddressTlvBlock::Iterator', 'position')]) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::TlvIterator ns3::PbbAddressBlock::TlvErase(ns3::PbbAddressBlock::TlvIterator first, ns3::PbbAddressBlock::TlvIterator last) [member function] cls.add_method('TlvErase', 'ns3::PbbAddressBlock::TlvIterator', [param('ns3::PbbAddressTlvBlock::Iterator', 'first'), param('ns3::PbbAddressTlvBlock::Iterator', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvFront() [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbAddressTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvFront() const [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbAddressTlv > const', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::TlvIterator ns3::PbbAddressBlock::TlvInsert(ns3::PbbAddressBlock::TlvIterator position, ns3::Ptr<ns3::PbbTlv> const value) [member function] cls.add_method('TlvInsert', 'ns3::PbbAddressBlock::TlvIterator', [param('ns3::PbbAddressTlvBlock::Iterator', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'value')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopBack() [member function] cls.add_method('TlvPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopFront() [member function] cls.add_method('TlvPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushBack(ns3::Ptr<ns3::PbbAddressTlv> address) [member function] cls.add_method('TlvPushBack', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushFront(ns3::Ptr<ns3::PbbAddressTlv> address) [member function] cls.add_method('TlvPushFront', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')]) ## packetbb.h (module 'network'): int ns3::PbbAddressBlock::TlvSize() const [member function] cls.add_method('TlvSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::DeserializeAddress(uint8_t * buffer) const [member function] cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'uint8_t', [], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrintAddress(std::ostream & os, ns3::PbbAddressBlock::ConstAddressIterator iter) const [member function] cls.add_method('PrintAddress', 'void', [param('std::ostream &', 'os'), param('std::list< ns3::Address > const_iterator', 'iter')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::SerializeAddress(uint8_t * buffer, ns3::PbbAddressBlock::ConstAddressIterator iter) const [member function] cls.add_method('SerializeAddress', 'void', [param('uint8_t *', 'buffer'), param('std::list< ns3::Address > const_iterator', 'iter')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbAddressBlockIpv4_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4(ns3::PbbAddressBlockIpv4 const & arg0) [constructor] cls.add_constructor([param('ns3::PbbAddressBlockIpv4 const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv4::DeserializeAddress(uint8_t * buffer) const [member function] cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv4::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'uint8_t', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::PrintAddress(std::ostream & os, ns3::PbbAddressBlock::ConstAddressIterator iter) const [member function] cls.add_method('PrintAddress', 'void', [param('std::ostream &', 'os'), param('std::list< ns3::Address > const_iterator', 'iter')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::SerializeAddress(uint8_t * buffer, ns3::PbbAddressBlock::ConstAddressIterator iter) const [member function] cls.add_method('SerializeAddress', 'void', [param('uint8_t *', 'buffer'), param('std::list< ns3::Address > const_iterator', 'iter')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbAddressBlockIpv6_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6(ns3::PbbAddressBlockIpv6 const & arg0) [constructor] cls.add_constructor([param('ns3::PbbAddressBlockIpv6 const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv6::DeserializeAddress(uint8_t * buffer) const [member function] cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv6::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'uint8_t', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::PrintAddress(std::ostream & os, ns3::PbbAddressBlock::ConstAddressIterator iter) const [member function] cls.add_method('PrintAddress', 'void', [param('std::ostream &', 'os'), param('std::list< ns3::Address > const_iterator', 'iter')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::SerializeAddress(uint8_t * buffer, ns3::PbbAddressBlock::ConstAddressIterator iter) const [member function] cls.add_method('SerializeAddress', 'void', [param('uint8_t *', 'buffer'), param('std::list< ns3::Address > const_iterator', 'iter')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbMessage_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage(ns3::PbbMessage const & arg0) [constructor] cls.add_constructor([param('ns3::PbbMessage const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockBack() [member function] cls.add_method('AddressBlockBack', 'ns3::Ptr< ns3::PbbAddressBlock >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockBack() const [member function] cls.add_method('AddressBlockBack', 'ns3::Ptr< ns3::PbbAddressBlock > const', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbMessage::AddressBlockIterator ns3::PbbMessage::AddressBlockBegin() [member function] cls.add_method('AddressBlockBegin', 'ns3::PbbMessage::AddressBlockIterator', []) ## packetbb.h (module 'network'): ns3::PbbMessage::ConstAddressBlockIterator ns3::PbbMessage::AddressBlockBegin() const [member function] cls.add_method('AddressBlockBegin', 'ns3::PbbMessage::ConstAddressBlockIterator', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockClear() [member function] cls.add_method('AddressBlockClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbMessage::AddressBlockEmpty() const [member function] cls.add_method('AddressBlockEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbMessage::AddressBlockIterator ns3::PbbMessage::AddressBlockEnd() [member function] cls.add_method('AddressBlockEnd', 'ns3::PbbMessage::AddressBlockIterator', []) ## packetbb.h (module 'network'): ns3::PbbMessage::ConstAddressBlockIterator ns3::PbbMessage::AddressBlockEnd() const [member function] cls.add_method('AddressBlockEnd', 'ns3::PbbMessage::ConstAddressBlockIterator', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbMessage::AddressBlockIterator ns3::PbbMessage::AddressBlockErase(ns3::PbbMessage::AddressBlockIterator position) [member function] cls.add_method('AddressBlockErase', 'ns3::PbbMessage::AddressBlockIterator', [param('std::list< ns3::Ptr< ns3::PbbAddressBlock > > iterator', 'position')]) ## packetbb.h (module 'network'): ns3::PbbMessage::AddressBlockIterator ns3::PbbMessage::AddressBlockErase(ns3::PbbMessage::AddressBlockIterator first, ns3::PbbMessage::AddressBlockIterator last) [member function] cls.add_method('AddressBlockErase', 'ns3::PbbMessage::AddressBlockIterator', [param('std::list< ns3::Ptr< ns3::PbbAddressBlock > > iterator', 'first'), param('std::list< ns3::Ptr< ns3::PbbAddressBlock > > iterator', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockFront() [member function] cls.add_method('AddressBlockFront', 'ns3::Ptr< ns3::PbbAddressBlock >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockFront() const [member function] cls.add_method('AddressBlockFront', 'ns3::Ptr< ns3::PbbAddressBlock > const', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopBack() [member function] cls.add_method('AddressBlockPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopFront() [member function] cls.add_method('AddressBlockPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushBack(ns3::Ptr<ns3::PbbAddressBlock> block) [member function] cls.add_method('AddressBlockPushBack', 'void', [param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushFront(ns3::Ptr<ns3::PbbAddressBlock> block) [member function] cls.add_method('AddressBlockPushFront', 'void', [param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')]) ## packetbb.h (module 'network'): int ns3::PbbMessage::AddressBlockSize() const [member function] cls.add_method('AddressBlockSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): static ns3::Ptr<ns3::PbbMessage> ns3::PbbMessage::DeserializeMessage(ns3::Buffer::Iterator & start) [member function] cls.add_method('DeserializeMessage', 'ns3::Ptr< ns3::PbbMessage >', [param('ns3::Buffer::Iterator &', 'start')], is_static=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopCount() const [member function] cls.add_method('GetHopCount', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::GetOriginatorAddress() const [member function] cls.add_method('GetOriginatorAddress', 'ns3::Address', [], is_const=True) ## packetbb.h (module 'network'): uint16_t ns3::PbbMessage::GetSequenceNumber() const [member function] cls.add_method('GetSequenceNumber', 'uint16_t', [], is_const=True) ## packetbb.h (module 'network'): uint32_t ns3::PbbMessage::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopCount() const [member function] cls.add_method('HasHopCount', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopLimit() const [member function] cls.add_method('HasHopLimit', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbMessage::HasOriginatorAddress() const [member function] cls.add_method('HasOriginatorAddress', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbMessage::HasSequenceNumber() const [member function] cls.add_method('HasSequenceNumber', 'bool', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopCount(uint8_t hopcount) [member function] cls.add_method('SetHopCount', 'void', [param('uint8_t', 'hopcount')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopLimit(uint8_t hoplimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hoplimit')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetOriginatorAddress(ns3::Address address) [member function] cls.add_method('SetOriginatorAddress', 'void', [param('ns3::Address', 'address')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetSequenceNumber(uint16_t seqnum) [member function] cls.add_method('SetSequenceNumber', 'void', [param('uint16_t', 'seqnum')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvBack() [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvBack() const [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbMessage::TlvIterator ns3::PbbMessage::TlvBegin() [member function] cls.add_method('TlvBegin', 'ns3::PbbMessage::TlvIterator', []) ## packetbb.h (module 'network'): ns3::PbbMessage::ConstTlvIterator ns3::PbbMessage::TlvBegin() const [member function] cls.add_method('TlvBegin', 'ns3::PbbMessage::ConstTlvIterator', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvClear() [member function] cls.add_method('TlvClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbMessage::TlvEmpty() const [member function] cls.add_method('TlvEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbMessage::TlvIterator ns3::PbbMessage::TlvEnd() [member function] cls.add_method('TlvEnd', 'ns3::PbbMessage::TlvIterator', []) ## packetbb.h (module 'network'): ns3::PbbMessage::ConstTlvIterator ns3::PbbMessage::TlvEnd() const [member function] cls.add_method('TlvEnd', 'ns3::PbbMessage::ConstTlvIterator', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbMessage::TlvIterator ns3::PbbMessage::TlvErase(ns3::PbbMessage::TlvIterator position) [member function] cls.add_method('TlvErase', 'ns3::PbbMessage::TlvIterator', [param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'position')]) ## packetbb.h (module 'network'): ns3::PbbMessage::TlvIterator ns3::PbbMessage::TlvErase(ns3::PbbMessage::TlvIterator first, ns3::PbbMessage::TlvIterator last) [member function] cls.add_method('TlvErase', 'ns3::PbbMessage::TlvIterator', [param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'first'), param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvFront() [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvFront() const [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopBack() [member function] cls.add_method('TlvPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopFront() [member function] cls.add_method('TlvPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushBack', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushFront', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): int ns3::PbbMessage::TlvSize() const [member function] cls.add_method('TlvSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('AddressBlockDeserialize', 'ns3::Ptr< ns3::PbbAddressBlock >', [param('ns3::Buffer::Iterator &', 'start')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('DeserializeOriginatorAddress', 'ns3::Address', [param('ns3::Buffer::Iterator &', 'start')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessage::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'ns3::PbbAddressLength', [], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::PrintOriginatorAddress(std::ostream & os) const [member function] cls.add_method('PrintOriginatorAddress', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('SerializeOriginatorAddress', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbMessageIpv4_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4(ns3::PbbMessageIpv4 const & arg0) [constructor] cls.add_constructor([param('ns3::PbbMessageIpv4 const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv4::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('AddressBlockDeserialize', 'ns3::Ptr< ns3::PbbAddressBlock >', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv4::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('DeserializeOriginatorAddress', 'ns3::Address', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv4::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'ns3::PbbAddressLength', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::PrintOriginatorAddress(std::ostream & os) const [member function] cls.add_method('PrintOriginatorAddress', 'void', [param('std::ostream &', 'os')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('SerializeOriginatorAddress', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbMessageIpv6_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6(ns3::PbbMessageIpv6 const & arg0) [constructor] cls.add_constructor([param('ns3::PbbMessageIpv6 const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv6::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('AddressBlockDeserialize', 'ns3::Ptr< ns3::PbbAddressBlock >', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv6::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('DeserializeOriginatorAddress', 'ns3::Address', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv6::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'ns3::PbbAddressLength', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::PrintOriginatorAddress(std::ostream & os) const [member function] cls.add_method('PrintOriginatorAddress', 'void', [param('std::ostream &', 'os')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('SerializeOriginatorAddress', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbPacket_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket(ns3::PbbPacket const & arg0) [constructor] cls.add_constructor([param('ns3::PbbPacket const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## packetbb.h (module 'network'): ns3::PbbPacket::TlvIterator ns3::PbbPacket::Erase(ns3::PbbPacket::TlvIterator position) [member function] cls.add_method('Erase', 'ns3::PbbPacket::TlvIterator', [param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'position')]) ## packetbb.h (module 'network'): ns3::PbbPacket::TlvIterator ns3::PbbPacket::Erase(ns3::PbbPacket::TlvIterator first, ns3::PbbPacket::TlvIterator last) [member function] cls.add_method('Erase', 'ns3::PbbPacket::TlvIterator', [param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'first'), param('std::list< ns3::Ptr< ns3::PbbTlv > > iterator', 'last')]) ## packetbb.h (module 'network'): ns3::PbbPacket::MessageIterator ns3::PbbPacket::Erase(ns3::PbbPacket::MessageIterator position) [member function] cls.add_method('Erase', 'ns3::PbbPacket::MessageIterator', [param('std::list< ns3::Ptr< ns3::PbbMessage > > iterator', 'position')]) ## packetbb.h (module 'network'): ns3::PbbPacket::MessageIterator ns3::PbbPacket::Erase(ns3::PbbPacket::MessageIterator first, ns3::PbbPacket::MessageIterator last) [member function] cls.add_method('Erase', 'ns3::PbbPacket::MessageIterator', [param('std::list< ns3::Ptr< ns3::PbbMessage > > iterator', 'first'), param('std::list< ns3::Ptr< ns3::PbbMessage > > iterator', 'last')]) ## packetbb.h (module 'network'): ns3::TypeId ns3::PbbPacket::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## packetbb.h (module 'network'): uint16_t ns3::PbbPacket::GetSequenceNumber() const [member function] cls.add_method('GetSequenceNumber', 'uint16_t', [], is_const=True) ## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## packetbb.h (module 'network'): static ns3::TypeId ns3::PbbPacket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbPacket::GetVersion() const [member function] cls.add_method('GetVersion', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbPacket::HasSequenceNumber() const [member function] cls.add_method('HasSequenceNumber', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageBack() [member function] cls.add_method('MessageBack', 'ns3::Ptr< ns3::PbbMessage >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageBack() const [member function] cls.add_method('MessageBack', 'ns3::Ptr< ns3::PbbMessage > const', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbPacket::MessageIterator ns3::PbbPacket::MessageBegin() [member function] cls.add_method('MessageBegin', 'ns3::PbbPacket::MessageIterator', []) ## packetbb.h (module 'network'): ns3::PbbPacket::ConstMessageIterator ns3::PbbPacket::MessageBegin() const [member function] cls.add_method('MessageBegin', 'ns3::PbbPacket::ConstMessageIterator', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessageClear() [member function] cls.add_method('MessageClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbPacket::MessageEmpty() const [member function] cls.add_method('MessageEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbPacket::MessageIterator ns3::PbbPacket::MessageEnd() [member function] cls.add_method('MessageEnd', 'ns3::PbbPacket::MessageIterator', []) ## packetbb.h (module 'network'): ns3::PbbPacket::ConstMessageIterator ns3::PbbPacket::MessageEnd() const [member function] cls.add_method('MessageEnd', 'ns3::PbbPacket::ConstMessageIterator', [], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageFront() [member function] cls.add_method('MessageFront', 'ns3::Ptr< ns3::PbbMessage >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageFront() const [member function] cls.add_method('MessageFront', 'ns3::Ptr< ns3::PbbMessage > const', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopBack() [member function] cls.add_method('MessagePopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopFront() [member function] cls.add_method('MessagePopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushBack(ns3::Ptr<ns3::PbbMessage> message) [member function] cls.add_method('MessagePushBack', 'void', [param('ns3::Ptr< ns3::PbbMessage >', 'message')]) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushFront(ns3::Ptr<ns3::PbbMessage> message) [member function] cls.add_method('MessagePushFront', 'void', [param('ns3::Ptr< ns3::PbbMessage >', 'message')]) ## packetbb.h (module 'network'): int ns3::PbbPacket::MessageSize() const [member function] cls.add_method('MessageSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::SetSequenceNumber(uint16_t number) [member function] cls.add_method('SetSequenceNumber', 'void', [param('uint16_t', 'number')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvBack() [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvBack() const [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbPacket::TlvIterator ns3::PbbPacket::TlvBegin() [member function] cls.add_method('TlvBegin', 'ns3::PbbPacket::TlvIterator', []) ## packetbb.h (module 'network'): ns3::PbbPacket::ConstTlvIterator ns3::PbbPacket::TlvBegin() const [member function] cls.add_method('TlvBegin', 'ns3::PbbPacket::ConstTlvIterator', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvClear() [member function] cls.add_method('TlvClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbPacket::TlvEmpty() const [member function] cls.add_method('TlvEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::PbbPacket::TlvIterator ns3::PbbPacket::TlvEnd() [member function] cls.add_method('TlvEnd', 'ns3::PbbPacket::TlvIterator', []) ## packetbb.h (module 'network'): ns3::PbbPacket::ConstTlvIterator ns3::PbbPacket::TlvEnd() const [member function] cls.add_method('TlvEnd', 'ns3::PbbPacket::ConstTlvIterator', [], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvFront() [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvFront() const [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopBack() [member function] cls.add_method('TlvPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopFront() [member function] cls.add_method('TlvPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushBack', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushFront', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): int ns3::PbbPacket::TlvSize() const [member function] cls.add_method('TlvSize', 'int', [], is_const=True) return def register_Ns3PbbTlv_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv(ns3::PbbTlv const & arg0) [constructor] cls.add_constructor([param('ns3::PbbTlv const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): void ns3::PbbTlv::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): uint32_t ns3::PbbTlv::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetTypeExt() const [member function] cls.add_method('GetTypeExt', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): ns3::Buffer ns3::PbbTlv::GetValue() const [member function] cls.add_method('GetValue', 'ns3::Buffer', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbTlv::HasTypeExt() const [member function] cls.add_method('HasTypeExt', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbTlv::HasValue() const [member function] cls.add_method('HasValue', 'bool', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlv::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlv::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## packetbb.h (module 'network'): void ns3::PbbTlv::SetTypeExt(uint8_t type) [member function] cls.add_method('SetTypeExt', 'void', [param('uint8_t', 'type')]) ## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(ns3::Buffer start) [member function] cls.add_method('SetValue', 'void', [param('ns3::Buffer', 'start')]) ## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('SetValue', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStart() const [member function] cls.add_method('GetIndexStart', 'uint8_t', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStop() const [member function] cls.add_method('GetIndexStop', 'uint8_t', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStart() const [member function] cls.add_method('HasIndexStart', 'bool', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStop() const [member function] cls.add_method('HasIndexStop', 'bool', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): bool ns3::PbbTlv::IsMultivalue() const [member function] cls.add_method('IsMultivalue', 'bool', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStart(uint8_t index) [member function] cls.add_method('SetIndexStart', 'void', [param('uint8_t', 'index')], visibility='protected') ## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStop(uint8_t index) [member function] cls.add_method('SetIndexStop', 'void', [param('uint8_t', 'index')], visibility='protected') ## packetbb.h (module 'network'): void ns3::PbbTlv::SetMultivalue(bool isMultivalue) [member function] cls.add_method('SetMultivalue', 'void', [param('bool', 'isMultivalue')], visibility='protected') return def register_Ns3Probe_methods(root_module, cls): ## probe.h (module 'stats'): ns3::Probe::Probe(ns3::Probe const & arg0) [constructor] cls.add_constructor([param('ns3::Probe const &', 'arg0')]) ## probe.h (module 'stats'): ns3::Probe::Probe() [constructor] cls.add_constructor([]) ## probe.h (module 'stats'): bool ns3::Probe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function] cls.add_method('ConnectByObject', 'bool', [param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')], is_pure_virtual=True, is_virtual=True) ## probe.h (module 'stats'): void ns3::Probe::ConnectByPath(std::string path) [member function] cls.add_method('ConnectByPath', 'void', [param('std::string', 'path')], is_pure_virtual=True, is_virtual=True) ## probe.h (module 'stats'): static ns3::TypeId ns3::Probe::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## probe.h (module 'stats'): bool ns3::Probe::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3Queue__Ns3Packet_methods(root_module, cls): ## queue.h (module 'network'): static ns3::TypeId ns3::Queue<ns3::Packet>::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue.h (module 'network'): ns3::Queue<ns3::Packet>::Queue() [constructor] cls.add_constructor([]) ## queue.h (module 'network'): bool ns3::Queue<ns3::Packet>::Enqueue(ns3::Ptr<ns3::Packet> item) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'item')], is_pure_virtual=True, is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', [], is_pure_virtual=True, is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::Remove() [member function] cls.add_method('Remove', 'ns3::Ptr< ns3::Packet >', [], is_pure_virtual=True, is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::Queue<ns3::Packet>::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet const >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## queue.h (module 'network'): void ns3::Queue<ns3::Packet>::Flush() [member function] cls.add_method('Flush', 'void', []) ## queue.h (module 'network'): ns3::Queue<ns3::Packet>::Queue(ns3::Queue<ns3::Packet> const & arg0) [constructor] cls.add_constructor([param('ns3::Queue< ns3::Packet > const &', 'arg0')]) ## queue.h (module 'network'): ns3::Queue<ns3::Packet>::ConstIterator ns3::Queue<ns3::Packet>::Head() const [member function] cls.add_method('Head', 'ns3::Queue< ns3::Packet > ConstIterator', [], is_const=True, visibility='protected') ## queue.h (module 'network'): ns3::Queue<ns3::Packet>::ConstIterator ns3::Queue<ns3::Packet>::Tail() const [member function] cls.add_method('Tail', 'ns3::Queue< ns3::Packet > ConstIterator', [], is_const=True, visibility='protected') ## queue.h (module 'network'): bool ns3::Queue<ns3::Packet>::DoEnqueue(ns3::Queue<ns3::Packet>::ConstIterator pos, ns3::Ptr<ns3::Packet> item) [member function] cls.add_method('DoEnqueue', 'bool', [param('std::list< ns3::Ptr< ns3::Packet > > const_iterator', 'pos'), param('ns3::Ptr< ns3::Packet >', 'item')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::DoDequeue(ns3::Queue<ns3::Packet>::ConstIterator pos) [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::Packet >', [param('std::list< ns3::Ptr< ns3::Packet > > const_iterator', 'pos')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::DoRemove(ns3::Queue<ns3::Packet>::ConstIterator pos) [member function] cls.add_method('DoRemove', 'ns3::Ptr< ns3::Packet >', [param('std::list< ns3::Ptr< ns3::Packet > > const_iterator', 'pos')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::Queue<ns3::Packet>::DoPeek(ns3::Queue<ns3::Packet>::ConstIterator pos) const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::Packet const >', [param('std::list< ns3::Ptr< ns3::Packet > > const_iterator', 'pos')], is_const=True, visibility='protected') ## queue.h (module 'network'): void ns3::Queue<ns3::Packet>::DropBeforeEnqueue(ns3::Ptr<ns3::Packet> item) [member function] cls.add_method('DropBeforeEnqueue', 'void', [param('ns3::Ptr< ns3::Packet >', 'item')], visibility='protected') ## queue.h (module 'network'): void ns3::Queue<ns3::Packet>::DropAfterDequeue(ns3::Ptr<ns3::Packet> item) [member function] cls.add_method('DropAfterDequeue', 'void', [param('ns3::Ptr< ns3::Packet >', 'item')], visibility='protected') return def register_Ns3Queue__Ns3QueueDiscItem_methods(root_module, cls): ## queue.h (module 'network'): static ns3::TypeId ns3::Queue<ns3::QueueDiscItem>::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem>::Queue() [constructor] cls.add_constructor([]) ## queue.h (module 'network'): bool ns3::Queue<ns3::QueueDiscItem>::Enqueue(ns3::Ptr<ns3::QueueDiscItem> item) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], is_pure_virtual=True, is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::QueueDiscItem >', [], is_pure_virtual=True, is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::Remove() [member function] cls.add_method('Remove', 'ns3::Ptr< ns3::QueueDiscItem >', [], is_pure_virtual=True, is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::QueueDiscItem const >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## queue.h (module 'network'): void ns3::Queue<ns3::QueueDiscItem>::Flush() [member function] cls.add_method('Flush', 'void', []) ## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem>::Queue(ns3::Queue<ns3::QueueDiscItem> const & arg0) [constructor] cls.add_constructor([param('ns3::Queue< ns3::QueueDiscItem > const &', 'arg0')]) ## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem>::ConstIterator ns3::Queue<ns3::QueueDiscItem>::Head() const [member function] cls.add_method('Head', 'ns3::Queue< ns3::QueueDiscItem > ConstIterator', [], is_const=True, visibility='protected') ## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem>::ConstIterator ns3::Queue<ns3::QueueDiscItem>::Tail() const [member function] cls.add_method('Tail', 'ns3::Queue< ns3::QueueDiscItem > ConstIterator', [], is_const=True, visibility='protected') ## queue.h (module 'network'): bool ns3::Queue<ns3::QueueDiscItem>::DoEnqueue(ns3::Queue<ns3::QueueDiscItem>::ConstIterator pos, ns3::Ptr<ns3::QueueDiscItem> item) [member function] cls.add_method('DoEnqueue', 'bool', [param('std::list< ns3::Ptr< ns3::QueueDiscItem > > const_iterator', 'pos'), param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::DoDequeue(ns3::Queue<ns3::QueueDiscItem>::ConstIterator pos) [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::QueueDiscItem >', [param('std::list< ns3::Ptr< ns3::QueueDiscItem > > const_iterator', 'pos')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::DoRemove(ns3::Queue<ns3::QueueDiscItem>::ConstIterator pos) [member function] cls.add_method('DoRemove', 'ns3::Ptr< ns3::QueueDiscItem >', [param('std::list< ns3::Ptr< ns3::QueueDiscItem > > const_iterator', 'pos')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<const ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::DoPeek(ns3::Queue<ns3::QueueDiscItem>::ConstIterator pos) const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::QueueDiscItem const >', [param('std::list< ns3::Ptr< ns3::QueueDiscItem > > const_iterator', 'pos')], is_const=True, visibility='protected') ## queue.h (module 'network'): void ns3::Queue<ns3::QueueDiscItem>::DropBeforeEnqueue(ns3::Ptr<ns3::QueueDiscItem> item) [member function] cls.add_method('DropBeforeEnqueue', 'void', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], visibility='protected') ## queue.h (module 'network'): void ns3::Queue<ns3::QueueDiscItem>::DropAfterDequeue(ns3::Ptr<ns3::QueueDiscItem> item) [member function] cls.add_method('DropAfterDequeue', 'void', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], visibility='protected') return def register_Ns3QueueItem_methods(root_module, cls): cls.add_output_stream_operator() ## queue-item.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')]) ## queue-item.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## queue-item.h (module 'network'): uint32_t ns3::QueueItem::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True, is_virtual=True) ## queue-item.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function] cls.add_method('GetUint8Value', 'bool', [param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')], is_const=True, is_virtual=True) ## queue-item.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) return def register_Ns3QueueSizeChecker_methods(root_module, cls): ## queue-size.h (module 'network'): ns3::QueueSizeChecker::QueueSizeChecker() [constructor] cls.add_constructor([]) ## queue-size.h (module 'network'): ns3::QueueSizeChecker::QueueSizeChecker(ns3::QueueSizeChecker const & arg0) [constructor] cls.add_constructor([param('ns3::QueueSizeChecker const &', 'arg0')]) return def register_Ns3QueueSizeValue_methods(root_module, cls): ## queue-size.h (module 'network'): ns3::QueueSizeValue::QueueSizeValue() [constructor] cls.add_constructor([]) ## queue-size.h (module 'network'): ns3::QueueSizeValue::QueueSizeValue(ns3::QueueSize const & value) [constructor] cls.add_constructor([param('ns3::QueueSize const &', 'value')]) ## queue-size.h (module 'network'): ns3::QueueSizeValue::QueueSizeValue(ns3::QueueSizeValue const & arg0) [constructor] cls.add_constructor([param('ns3::QueueSizeValue const &', 'arg0')]) ## queue-size.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::QueueSizeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## queue-size.h (module 'network'): bool ns3::QueueSizeValue::DeserializeFromString(std::string value, ns3::Ptr<const ns3::AttributeChecker> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## queue-size.h (module 'network'): ns3::QueueSize ns3::QueueSizeValue::Get() const [member function] cls.add_method('Get', 'ns3::QueueSize', [], is_const=True) ## queue-size.h (module 'network'): std::string ns3::QueueSizeValue::SerializeToString(ns3::Ptr<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## queue-size.h (module 'network'): void ns3::QueueSizeValue::Set(ns3::QueueSize const & value) [member function] cls.add_method('Set', 'void', [param('ns3::QueueSize const &', 'value')]) return def register_Ns3RateErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel(ns3::RateErrorModel const & arg0) [constructor] cls.add_constructor([param('ns3::RateErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): int64_t ns3::RateErrorModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## error-model.h (module 'network'): double ns3::RateErrorModel::GetRate() const [member function] cls.add_method('GetRate', 'double', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::RateErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit ns3::RateErrorModel::GetUnit() const [member function] cls.add_method('GetUnit', 'ns3::RateErrorModel::ErrorUnit', [], is_const=True) ## error-model.h (module 'network'): void ns3::RateErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> arg0) [member function] cls.add_method('SetRandomVariable', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'arg0')]) ## error-model.h (module 'network'): void ns3::RateErrorModel::SetRate(double rate) [member function] cls.add_method('SetRate', 'void', [param('double', 'rate')]) ## error-model.h (module 'network'): void ns3::RateErrorModel::SetUnit(ns3::RateErrorModel::ErrorUnit error_unit) [member function] cls.add_method('SetUnit', 'void', [param('ns3::RateErrorModel::ErrorUnit', 'error_unit')]) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptBit(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorruptBit', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptByte(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorruptByte', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptPkt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorruptPkt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::RateErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3ReceiveListErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel(ns3::ReceiveListErrorModel const & arg0) [constructor] cls.add_constructor([param('ns3::ReceiveListErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ReceiveListErrorModel::GetList() const [member function] cls.add_method('GetList', 'std::list< unsigned int >', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::ReceiveListErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function] cls.add_method('SetList', 'void', [param('std::list< unsigned int > const &', 'packetlist')]) ## error-model.h (module 'network'): bool ns3::ReceiveListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3SimpleChannel_methods(root_module, cls): ## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel(ns3::SimpleChannel const & arg0) [constructor] cls.add_constructor([param('ns3::SimpleChannel const &', 'arg0')]) ## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel() [constructor] cls.add_constructor([]) ## simple-channel.h (module 'network'): void ns3::SimpleChannel::Add(ns3::Ptr<ns3::SimpleNetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::SimpleNetDevice >', 'device')], is_virtual=True) ## simple-channel.h (module 'network'): void ns3::SimpleChannel::BlackList(ns3::Ptr<ns3::SimpleNetDevice> from, ns3::Ptr<ns3::SimpleNetDevice> to) [member function] cls.add_method('BlackList', 'void', [param('ns3::Ptr< ns3::SimpleNetDevice >', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'to')], is_virtual=True) ## simple-channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::SimpleChannel::GetDevice(std::size_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('std::size_t', 'i')], is_const=True, is_virtual=True) ## simple-channel.h (module 'network'): std::size_t ns3::SimpleChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'std::size_t', [], is_const=True, is_virtual=True) ## simple-channel.h (module 'network'): static ns3::TypeId ns3::SimpleChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## simple-channel.h (module 'network'): void ns3::SimpleChannel::Send(ns3::Ptr<ns3::Packet> p, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from, ns3::Ptr<ns3::SimpleNetDevice> sender) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'sender')], is_virtual=True) ## simple-channel.h (module 'network'): void ns3::SimpleChannel::UnBlackList(ns3::Ptr<ns3::SimpleNetDevice> from, ns3::Ptr<ns3::SimpleNetDevice> to) [member function] cls.add_method('UnBlackList', 'void', [param('ns3::Ptr< ns3::SimpleNetDevice >', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'to')], is_virtual=True) return def register_Ns3SimpleNetDevice_methods(root_module, cls): ## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice(ns3::SimpleNetDevice const & arg0) [constructor] cls.add_constructor([param('ns3::SimpleNetDevice const &', 'arg0')]) ## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice() [constructor] cls.add_constructor([]) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::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) ## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::SimpleNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): uint32_t ns3::SimpleNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): uint16_t ns3::SimpleNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::SimpleNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Queue<ns3::Packet> > ns3::SimpleNetDevice::GetQueue() const [member function] cls.add_method('GetQueue', 'ns3::Ptr< ns3::Queue< ns3::Packet > >', [], is_const=True) ## simple-net-device.h (module 'network'): static ns3::TypeId ns3::SimpleNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::Receive(ns3::Ptr<ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')]) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::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) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::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) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetChannel(ns3::Ptr<ns3::SimpleChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SimpleChannel >', 'channel')]) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetPromiscReceiveCallback(ns3::NetDevice::PromiscReceiveCallback 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) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetQueue(ns3::Ptr<ns3::Queue<ns3::Packet> > queue) [member function] cls.add_method('SetQueue', 'void', [param('ns3::Ptr< ns3::Queue< ns3::Packet > >', 'queue')]) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetReceiveCallback(ns3::NetDevice::ReceiveCallback 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) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetReceiveErrorModel(ns3::Ptr<ns3::ErrorModel> em) [member function] cls.add_method('SetReceiveErrorModel', 'void', [param('ns3::Ptr< ns3::ErrorModel >', 'em')]) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', 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::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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(uint64_t const & value) [constructor] cls.add_constructor([param('uint64_t const &', 'value')]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [constructor] cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_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) [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::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3BinaryErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::BinaryErrorModel::BinaryErrorModel(ns3::BinaryErrorModel const & arg0) [constructor] cls.add_constructor([param('ns3::BinaryErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::BinaryErrorModel::BinaryErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): static ns3::TypeId ns3::BinaryErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): bool ns3::BinaryErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::BinaryErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3BurstErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::BurstErrorModel::BurstErrorModel(ns3::BurstErrorModel const & arg0) [constructor] cls.add_constructor([param('ns3::BurstErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::BurstErrorModel::BurstErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): int64_t ns3::BurstErrorModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## error-model.h (module 'network'): double ns3::BurstErrorModel::GetBurstRate() const [member function] cls.add_method('GetBurstRate', 'double', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::BurstErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): void ns3::BurstErrorModel::SetBurstRate(double rate) [member function] cls.add_method('SetBurstRate', 'void', [param('double', 'rate')]) ## error-model.h (module 'network'): void ns3::BurstErrorModel::SetRandomBurstSize(ns3::Ptr<ns3::RandomVariableStream> burstSz) [member function] cls.add_method('SetRandomBurstSize', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'burstSz')]) ## error-model.h (module 'network'): void ns3::BurstErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> ranVar) [member function] cls.add_method('SetRandomVariable', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'ranVar')]) ## error-model.h (module 'network'): bool ns3::BurstErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::BurstErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< 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 > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0, ns3::Ptr<const ns3::Packet> arg1, short unsigned int arg2, ns3::Address const & arg3, ns3::Address const & arg4, ns3::NetDevice::PacketType arg5) [member operator] cls.add_method('operator()', 'bool', [param('ns3::Ptr< ns3::NetDevice >', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('short unsigned int', 'arg2'), param('ns3::Address const &', 'arg3'), param('ns3::Address const &', 'arg4'), param('ns3::NetDevice::PacketType', 'arg5')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< 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 > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImpl<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0, ns3::Ptr<const ns3::Packet> arg1, short unsigned int arg2, ns3::Address const & arg3) [member operator] cls.add_method('operator()', 'bool', [param('ns3::Ptr< ns3::NetDevice >', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('short unsigned int', 'arg2'), param('ns3::Address const &', 'arg3')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, ns3::Address const & arg1) [member operator] cls.add_method('operator()', 'bool', [param('ns3::Ptr< ns3::Socket >', 'arg0'), param('ns3::Address const &', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): ns3::ObjectBase * ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()() [member operator] cls.add_method('operator()', 'ns3::ObjectBase *', [], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet const >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<const ns3::Packet> arg0, ns3::Address const & arg1) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Packet const >', 'arg0'), param('ns3::Address const &', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<const ns3::Packet> arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Packet const >', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3QueueDiscItem__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::QueueDiscItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::QueueDiscItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<const ns3::QueueDiscItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::QueueDiscItem const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::QueueDiscItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::QueueDiscItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<const ns3::QueueDiscItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<const ns3::QueueDiscItem> arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::QueueDiscItem const >', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< 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 > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0, ns3::Ptr<const ns3::Packet> arg1, short unsigned int arg2, ns3::Address const & arg3, ns3::Address const & arg4, ns3::NetDevice::PacketType arg5) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('short unsigned int', 'arg2'), param('ns3::Address const &', 'arg3'), param('ns3::Address const &', 'arg4'), param('ns3::NetDevice::PacketType', 'arg5')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, ns3::Address const & arg1) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Socket >', 'arg0'), param('ns3::Address const &', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Socket >', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, unsigned int arg1) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Socket >', 'arg0'), param('unsigned int', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()() [member operator] cls.add_method('operator()', 'void', [], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Unsigned_int_Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(unsigned int arg0, unsigned int arg1) [member operator] cls.add_method('operator()', 'void', [param('unsigned int', 'arg0'), param('unsigned int', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CounterCalculator__Unsigned_int_methods(root_module, cls): ## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int>::CounterCalculator(ns3::CounterCalculator<unsigned int> const & arg0) [constructor] cls.add_constructor([param('ns3::CounterCalculator< unsigned int > const &', 'arg0')]) ## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int>::CounterCalculator() [constructor] cls.add_constructor([]) ## basic-data-calculators.h (module 'stats'): unsigned int ns3::CounterCalculator<unsigned int>::GetCount() const [member function] cls.add_method('GetCount', 'unsigned int', [], is_const=True) ## basic-data-calculators.h (module 'stats'): static ns3::TypeId ns3::CounterCalculator<unsigned int>::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Output(ns3::DataOutputCallback & callback) const [member function] cls.add_method('Output', 'void', [param('ns3::DataOutputCallback &', 'callback')], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Update() [member function] cls.add_method('Update', 'void', []) ## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Update(unsigned int const i) [member function] cls.add_method('Update', 'void', [param('unsigned int const', 'i')]) ## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3DropTailQueue__Ns3Packet_methods(root_module, cls): ## drop-tail-queue.h (module 'network'): static ns3::TypeId ns3::DropTailQueue<ns3::Packet>::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue<ns3::Packet>::DropTailQueue() [constructor] cls.add_constructor([]) ## drop-tail-queue.h (module 'network'): bool ns3::DropTailQueue<ns3::Packet>::Enqueue(ns3::Ptr<ns3::Packet> item) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'item')], is_virtual=True) ## drop-tail-queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::DropTailQueue<ns3::Packet>::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', [], is_virtual=True) ## drop-tail-queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::DropTailQueue<ns3::Packet>::Remove() [member function] cls.add_method('Remove', 'ns3::Ptr< ns3::Packet >', [], is_virtual=True) ## drop-tail-queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::DropTailQueue<ns3::Packet>::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet const >', [], is_const=True, is_virtual=True) ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue<ns3::Packet>::DropTailQueue(ns3::DropTailQueue<ns3::Packet> const & arg0) [constructor] cls.add_constructor([param('ns3::DropTailQueue< ns3::Packet > const &', 'arg0')]) return def register_Ns3DropTailQueue__Ns3QueueDiscItem_methods(root_module, cls): ## drop-tail-queue.h (module 'network'): static ns3::TypeId ns3::DropTailQueue<ns3::QueueDiscItem>::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue<ns3::QueueDiscItem>::DropTailQueue() [constructor] cls.add_constructor([]) ## drop-tail-queue.h (module 'network'): bool ns3::DropTailQueue<ns3::QueueDiscItem>::Enqueue(ns3::Ptr<ns3::QueueDiscItem> item) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], is_virtual=True) ## drop-tail-queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::DropTailQueue<ns3::QueueDiscItem>::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::QueueDiscItem >', [], is_virtual=True) ## drop-tail-queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::DropTailQueue<ns3::QueueDiscItem>::Remove() [member function] cls.add_method('Remove', 'ns3::Ptr< ns3::QueueDiscItem >', [], is_virtual=True) ## drop-tail-queue.h (module 'network'): ns3::Ptr<const ns3::QueueDiscItem> ns3::DropTailQueue<ns3::QueueDiscItem>::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::QueueDiscItem const >', [], is_const=True, is_virtual=True) ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue<ns3::QueueDiscItem>::DropTailQueue(ns3::DropTailQueue<ns3::QueueDiscItem> const & arg0) [constructor] cls.add_constructor([param('ns3::DropTailQueue< ns3::QueueDiscItem > const &', 'arg0')]) return def register_Ns3ErrorChannel_methods(root_module, cls): ## error-channel.h (module 'network'): ns3::ErrorChannel::ErrorChannel(ns3::ErrorChannel const & arg0) [constructor] cls.add_constructor([param('ns3::ErrorChannel const &', 'arg0')]) ## error-channel.h (module 'network'): ns3::ErrorChannel::ErrorChannel() [constructor] cls.add_constructor([]) ## error-channel.h (module 'network'): void ns3::ErrorChannel::Add(ns3::Ptr<ns3::SimpleNetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::SimpleNetDevice >', 'device')], is_virtual=True) ## error-channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::ErrorChannel::GetDevice(std::size_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('std::size_t', 'i')], is_const=True, is_virtual=True) ## error-channel.h (module 'network'): std::size_t ns3::ErrorChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'std::size_t', [], is_const=True, is_virtual=True) ## error-channel.h (module 'network'): static ns3::TypeId ns3::ErrorChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-channel.h (module 'network'): void ns3::ErrorChannel::Send(ns3::Ptr<ns3::Packet> p, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from, ns3::Ptr<ns3::SimpleNetDevice> sender) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'sender')], is_virtual=True) ## error-channel.h (module 'network'): void ns3::ErrorChannel::SetDuplicateMode(bool mode) [member function] cls.add_method('SetDuplicateMode', 'void', [param('bool', 'mode')]) ## error-channel.h (module 'network'): void ns3::ErrorChannel::SetDuplicateTime(ns3::Time delay) [member function] cls.add_method('SetDuplicateTime', 'void', [param('ns3::Time', 'delay')]) ## error-channel.h (module 'network'): void ns3::ErrorChannel::SetJumpingMode(bool mode) [member function] cls.add_method('SetJumpingMode', 'void', [param('bool', 'mode')]) ## error-channel.h (module 'network'): void ns3::ErrorChannel::SetJumpingTime(ns3::Time delay) [member function] cls.add_method('SetJumpingTime', 'void', [param('ns3::Time', 'delay')]) return def register_Ns3PacketCounterCalculator_methods(root_module, cls): ## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator::PacketCounterCalculator(ns3::PacketCounterCalculator const & arg0) [constructor] cls.add_constructor([param('ns3::PacketCounterCalculator const &', 'arg0')]) ## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator::PacketCounterCalculator() [constructor] cls.add_constructor([]) ## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::FrameUpdate(std::string path, ns3::Ptr<const ns3::Packet> packet, ns3::Mac48Address realto) [member function] cls.add_method('FrameUpdate', 'void', [param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'realto')]) ## packet-data-calculators.h (module 'network'): static ns3::TypeId ns3::PacketCounterCalculator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::PacketUpdate(std::string path, ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('PacketUpdate', 'void', [param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3PacketProbe_methods(root_module, cls): ## packet-probe.h (module 'network'): ns3::PacketProbe::PacketProbe(ns3::PacketProbe const & arg0) [constructor] cls.add_constructor([param('ns3::PacketProbe const &', 'arg0')]) ## packet-probe.h (module 'network'): ns3::PacketProbe::PacketProbe() [constructor] cls.add_constructor([]) ## packet-probe.h (module 'network'): bool ns3::PacketProbe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function] cls.add_method('ConnectByObject', 'bool', [param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')], is_virtual=True) ## packet-probe.h (module 'network'): void ns3::PacketProbe::ConnectByPath(std::string path) [member function] cls.add_method('ConnectByPath', 'void', [param('std::string', 'path')], is_virtual=True) ## packet-probe.h (module 'network'): static ns3::TypeId ns3::PacketProbe::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-probe.h (module 'network'): void ns3::PacketProbe::SetValue(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('SetValue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet-probe.h (module 'network'): static void ns3::PacketProbe::SetValueByPath(std::string path, ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('SetValueByPath', 'void', [param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')], is_static=True) return def register_Ns3PbbAddressTlv_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv(ns3::PbbAddressTlv const & arg0) [constructor] cls.add_constructor([param('ns3::PbbAddressTlv const &', 'arg0')]) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStart() const [member function] cls.add_method('GetIndexStart', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStop() const [member function] cls.add_method('GetIndexStop', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStart() const [member function] cls.add_method('HasIndexStart', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStop() const [member function] cls.add_method('HasIndexStop', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::IsMultivalue() const [member function] cls.add_method('IsMultivalue', 'bool', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStart(uint8_t index) [member function] cls.add_method('SetIndexStart', 'void', [param('uint8_t', 'index')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStop(uint8_t index) [member function] cls.add_method('SetIndexStop', 'void', [param('uint8_t', 'index')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetMultivalue(bool isMultivalue) [member function] cls.add_method('SetMultivalue', 'void', [param('bool', 'isMultivalue')]) return def register_Ns3QueueDiscItem_methods(root_module, cls): ## queue-item.h (module 'network'): ns3::QueueDiscItem::QueueDiscItem(ns3::Ptr<ns3::Packet> p, ns3::Address const & addr, uint16_t protocol) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Address const &', 'addr'), param('uint16_t', 'protocol')]) ## queue-item.h (module 'network'): ns3::Address ns3::QueueDiscItem::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True) ## queue-item.h (module 'network'): uint16_t ns3::QueueDiscItem::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint16_t', [], is_const=True) ## queue-item.h (module 'network'): uint8_t ns3::QueueDiscItem::GetTxQueueIndex() const [member function] cls.add_method('GetTxQueueIndex', 'uint8_t', [], is_const=True) ## queue-item.h (module 'network'): void ns3::QueueDiscItem::SetTxQueueIndex(uint8_t txq) [member function] cls.add_method('SetTxQueueIndex', 'void', [param('uint8_t', 'txq')]) ## queue-item.h (module 'network'): ns3::Time ns3::QueueDiscItem::GetTimeStamp() const [member function] cls.add_method('GetTimeStamp', 'ns3::Time', [], is_const=True) ## queue-item.h (module 'network'): void ns3::QueueDiscItem::SetTimeStamp(ns3::Time t) [member function] cls.add_method('SetTimeStamp', 'void', [param('ns3::Time', 't')]) ## queue-item.h (module 'network'): void ns3::QueueDiscItem::AddHeader() [member function] cls.add_method('AddHeader', 'void', [], is_pure_virtual=True, is_virtual=True) ## queue-item.h (module 'network'): void ns3::QueueDiscItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## queue-item.h (module 'network'): bool ns3::QueueDiscItem::Mark() [member function] cls.add_method('Mark', 'bool', [], is_pure_virtual=True, is_virtual=True) ## queue-item.h (module 'network'): uint32_t ns3::QueueDiscItem::Hash(uint32_t perturbation=0) const [member function] cls.add_method('Hash', 'uint32_t', [param('uint32_t', 'perturbation', default_value='0')], is_const=True, 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) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::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, std::size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('std::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) [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) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::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) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, std::size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('std::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) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, std::size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('std::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 ## crc32.h (module 'network'): uint32_t ns3::CRC32Calculate(uint8_t const * data, int length) [free function] module.add_function('CRC32Calculate', 'uint32_t', [param('uint8_t const *', 'data'), param('int', 'length')]) ## address.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeAddressChecker() [free function] module.add_function('MakeAddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## data-rate.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeDataRateChecker() [free function] module.add_function('MakeDataRateChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## ipv4-address.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeIpv4AddressChecker() [free function] module.add_function('MakeIpv4AddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## ipv4-address.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeIpv4MaskChecker() [free function] module.add_function('MakeIpv4MaskChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## ipv6-address.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeIpv6AddressChecker() [free function] module.add_function('MakeIpv6AddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## ipv6-address.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeIpv6PrefixChecker() [free function] module.add_function('MakeIpv6PrefixChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## mac16-address.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeMac16AddressChecker() [free function] module.add_function('MakeMac16AddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## mac48-address.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeMac48AddressChecker() [free function] module.add_function('MakeMac48AddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## mac64-address.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeMac64AddressChecker() [free function] module.add_function('MakeMac64AddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## queue-size.h (module 'network'): ns3::Ptr<const ns3::AttributeChecker> ns3::MakeQueueSizeChecker() [free function] module.add_function('MakeQueueSizeChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## address-utils.h (module 'network'): void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Address & ad, uint32_t len) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Address &', 'ad'), param('uint32_t', 'len')]) ## address-utils.h (module 'network'): void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Ipv4Address & ad) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv4Address &', 'ad')]) ## address-utils.h (module 'network'): void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Ipv6Address & ad) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv6Address &', 'ad')]) ## address-utils.h (module 'network'): void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Mac16Address & ad) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac16Address &', 'ad')]) ## address-utils.h (module 'network'): void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Mac48Address & ad) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac48Address &', 'ad')]) ## address-utils.h (module 'network'): void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Mac64Address & ad) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac64Address &', 'ad')]) ## address-utils.h (module 'network'): void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Address const & ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Address const &', 'ad')]) ## address-utils.h (module 'network'): void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Ipv4Address ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv4Address', 'ad')]) ## address-utils.h (module 'network'): void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Ipv6Address ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv6Address', 'ad')]) ## address-utils.h (module 'network'): void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Mac16Address ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac16Address', 'ad')]) ## address-utils.h (module 'network'): void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Mac48Address ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac48Address', 'ad')]) ## address-utils.h (module 'network'): void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Mac64Address ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac64Address', 'ad')]) register_functions_ns3_FatalImpl(module.add_cpp_namespace('FatalImpl'), root_module) register_functions_ns3_Hash(module.add_cpp_namespace('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.add_cpp_namespace('TracedValueCallback'), root_module) register_functions_ns3_addressUtils(module.add_cpp_namespace('addressUtils'), root_module) register_functions_ns3_internal(module.add_cpp_namespace('internal'), root_module) register_functions_ns3_tests(module.add_cpp_namespace('tests'), 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.add_cpp_namespace('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): ## address-utils.h (module 'network'): bool ns3::addressUtils::IsMulticast(ns3::Address const & ad) [free function] module.add_function('IsMulticast', 'bool', [param('ns3::Address const &', 'ad')]) return def register_functions_ns3_internal(module, root_module): return def register_functions_ns3_tests(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
7,644,027,052,523,548,000
64.658655
594
0.610563
false
3.810793
false
false
false
wxgeo/geophar
wxgeometrie/sympy/printing/rcode.py
3
14687
""" R code printer The RCodePrinter converts single sympy expressions into single R expressions, using the functions defined in math.h where possible. """ from __future__ import print_function, division from sympy.core import S from sympy.core.compatibility import string_types, range from sympy.codegen.ast import Assignment from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE from sympy.sets.fancysets import Range # dictionary mapping sympy function to (argument_conditions, C_function). # Used in RCodePrinter._print_Function(self) known_functions = { #"Abs": [(lambda x: not x.is_integer, "fabs")], "Abs": "abs", "sin": "sin", "cos": "cos", "tan": "tan", "asin": "asin", "acos": "acos", "atan": "atan", "atan2": "atan2", "exp": "exp", "log": "log", "erf": "erf", "sinh": "sinh", "cosh": "cosh", "tanh": "tanh", "asinh": "asinh", "acosh": "acosh", "atanh": "atanh", "floor": "floor", "ceiling": "ceiling", "sign": "sign", "Max": "max", "Min": "min", "factorial": "factorial", "gamma": "gamma", "digamma": "digamma", "trigamma": "trigamma", "beta": "beta", } # These are the core reserved words in the R language. Taken from: # https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Reserved-words reserved_words = ['if', 'else', 'repeat', 'while', 'function', 'for', 'in', 'next', 'break', 'TRUE', 'FALSE', 'NULL', 'Inf', 'NaN', 'NA', 'NA_integer_', 'NA_real_', 'NA_complex_', 'NA_character_', 'volatile'] class RCodePrinter(CodePrinter): """A printer to convert python expressions to strings of R code""" printmethod = "_rcode" language = "R" _default_settings = { 'order': None, 'full_prec': 'auto', 'precision': 15, 'user_functions': {}, 'human': True, 'contract': True, 'dereference': set(), 'error_on_reserved': False, 'reserved_word_suffix': '_', } _operators = { 'and': '&', 'or': '|', 'not': '!', } _relationals = { } def __init__(self, settings={}): CodePrinter.__init__(self, settings) self.known_functions = dict(known_functions) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) self._dereference = set(settings.get('dereference', [])) self.reserved_words = set(reserved_words) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "// {0}".format(text) def _declare_number_const(self, name, value): return "{0} = {1};".format(name, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): rows, cols = mat.shape return ((i, j) for i in range(rows) for j in range(cols)) def _get_loop_opening_ending(self, indices): """Returns a tuple (open_lines, close_lines) containing lists of codelines """ open_lines = [] close_lines = [] loopstart = "for (%(var)s in %(start)s:%(end)s){" for i in indices: # R arrays start at 1 and end at dimension open_lines.append(loopstart % { 'var': self._print(i.label), 'start': self._print(i.lower+1), 'end': self._print(i.upper + 1)}) close_lines.append("}") return open_lines, close_lines def _print_Pow(self, expr): if "Pow" in self.known_functions: return self._print_Function(expr) PREC = precedence(expr) if expr.exp == -1: return '1.0/%s' % (self.parenthesize(expr.base, PREC)) elif expr.exp == 0.5: return 'sqrt(%s)' % self._print(expr.base) else: return '%s^%s' % (self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC)) def _print_Rational(self, expr): p, q = int(expr.p), int(expr.q) return '%d.0/%d.0' % (p, q) def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s[%s]" % (self._print(expr.base.label), ", ".join(inds)) def _print_Idx(self, expr): return self._print(expr.label) def _print_Exp1(self, expr): return "exp(1)" def _print_Pi(self, expr): return 'pi' def _print_Infinity(self, expr): return 'Inf' def _print_NegativeInfinity(self, expr): return '-Inf' def _print_Assignment(self, expr): from sympy.functions.elementary.piecewise import Piecewise from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.tensor.indexed import IndexedBase lhs = expr.lhs rhs = expr.rhs # We special case assignments that take multiple lines #if isinstance(expr.rhs, Piecewise): # # Here we modify Piecewise so each expression is now # # an Assignment, and then continue on the print. # expressions = [] # conditions = [] # for (e, c) in rhs.args: # expressions.append(Assignment(lhs, e)) # conditions.append(c) # temp = Piecewise(*zip(expressions, conditions)) # return self._print(temp) #elif isinstance(lhs, MatrixSymbol): if isinstance(lhs, MatrixSymbol): # Here we form an Assignment for each element in the array, # printing each one. lines = [] for (i, j) in self._traverse_matrix_indices(lhs): temp = Assignment(lhs[i, j], rhs[i, j]) code0 = self._print(temp) lines.append(code0) return "\n".join(lines) elif self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_Piecewise(self, expr): # This method is called only for inline if constructs # Top level piecewise is handled in doprint() if expr.args[-1].cond == True: last_line = "%s" % self._print(expr.args[-1].expr) else: last_line = "ifelse(%s,%s,NA)" % (self._print(expr.args[-1].cond), self._print(expr.args[-1].expr)) code=last_line for e, c in reversed(expr.args[:-1]): code= "ifelse(%s,%s," % (self._print(c), self._print(e))+code+")" return(code) def _print_ITE(self, expr): from sympy.functions import Piecewise _piecewise = Piecewise((expr.args[1], expr.args[0]), (expr.args[2], True)) return self._print(_piecewise) def _print_MatrixElement(self, expr): return "{0}[{1}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True), expr.j + expr.i*expr.parent.shape[1]) def _print_Symbol(self, expr): name = super(RCodePrinter, self)._print_Symbol(expr) if expr in self._dereference: return '(*{0})'.format(name) else: return name def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return ("{0} {1} {2}").format(lhs_code, op, rhs_code) def _print_sinc(self, expr): from sympy.functions.elementary.trigonometric import sin from sympy.core.relational import Ne from sympy.functions import Piecewise _piecewise = Piecewise( (sin(expr.args[0]) / expr.args[0], Ne(expr.args[0], 0)), (1, True)) return self._print(_piecewise) def _print_AugmentedAssignment(self, expr): lhs_code = self._print(expr.lhs) op = expr.rel_op rhs_code = self._print(expr.rhs) return "{0} {1} {2};".format(lhs_code, op, rhs_code) def _print_For(self, expr): target = self._print(expr.target) if isinstance(expr.iterable, Range): start, stop, step = expr.iterable.args else: raise NotImplementedError("Only iterable currently supported is Range") body = self._print(expr.body) return ('for ({target} = {start}; {target} < {stop}; {target} += ' '{step}) {{\n{body}\n}}').format(target=target, start=start, stop=stop, step=step, body=body) def indent_code(self, code): """Accepts a string of code or a list of code lines""" if isinstance(code, string_types): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_token = ('{', '(', '{\n', '(\n') dec_token = ('}', ')') code = [ line.lstrip(' \t') for line in code ] increase = [ int(any(map(line.endswith, inc_token))) for line in code ] decrease = [ int(any(map(line.startswith, dec_token))) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line == '' or line == '\n': pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def rcode(expr, assign_to=None, **settings): """Converts an expr to a string of r code Parameters ========== expr : Expr A sympy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=15]. user_functions : dict, optional A dictionary where the keys are string representations of either ``FunctionClass`` or ``UndefinedFunction`` instances and the values are their desired R string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, rfunction_string)] or [(argument_test, rfunction_formater)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. Examples ======== >>> from sympy import rcode, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> rcode((2*tau)**Rational(7, 2)) '8*sqrt(2)*tau^(7.0/2.0)' >>> rcode(sin(x), assign_to="s") 's = sin(x);' Simple custom printing can be defined for certain types by passing a dictionary of {"type" : "function"} to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. >>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs"), ... (lambda x: x.is_integer, "ABS")], ... "func": "f" ... } >>> func = Function('func') >>> rcode(func(Abs(x) + ceiling(x)), user_functions=custom_functions) 'f(fabs(x) + CEIL(x))' or if the R-function takes a subset of the original arguments: >>> rcode(2**x + 3**x, user_functions={'Pow': [ ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e), ... (lambda b, e: b != 2, 'pow')]}) 'exp2(x) + pow(3, x)' ``Piecewise`` expressions are converted into conditionals. If an ``assign_to`` variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(rcode(expr, assign_to=tau)) tau = ifelse(x > 0,x + 1,x); Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> rcode(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions must be provided to ``assign_to``. Note that any expression that can be generated normally can also exist inside a Matrix: >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(rcode(mat, A)) A[0] = x^2; A[1] = ifelse(x > 0,x + 1,x); A[2] = sin(x); """ return RCodePrinter(settings).doprint(expr, assign_to) def print_rcode(expr, **settings): """Prints R representation of the given expression.""" print(rcode(expr, **settings))
gpl-2.0
3,434,515,022,985,625,000
34.052506
111
0.564717
false
3.696703
false
false
false
jpburstrom/sampleman
mainwindowui.py
1
18965
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'sampleman.ui' # # Created: Sun Mar 7 13:00:58 2010 # by: PyQt4 UI code generator 4.7 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(579, 671) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QtGui.QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.lineEdit = QtGui.QLineEdit(self.centralwidget) self.lineEdit.setObjectName("lineEdit") self.gridLayout.addWidget(self.lineEdit, 0, 0, 1, 1) self.fileView = QtGui.QListView(self.centralwidget) self.fileView.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.fileView.setDragEnabled(False) self.fileView.setDragDropMode(QtGui.QAbstractItemView.DragOnly) self.fileView.setDefaultDropAction(QtCore.Qt.CopyAction) self.fileView.setAlternatingRowColors(True) self.fileView.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.fileView.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems) self.fileView.setLayoutMode(QtGui.QListView.Batched) self.fileView.setBatchSize(30) self.fileView.setObjectName("fileView") self.gridLayout.addWidget(self.fileView, 1, 0, 1, 1) self.sliderFrame = QtGui.QFrame(self.centralwidget) self.sliderFrame.setFrameShape(QtGui.QFrame.NoFrame) self.sliderFrame.setFrameShadow(QtGui.QFrame.Plain) self.sliderFrame.setObjectName("sliderFrame") self.verticalLayout_2 = QtGui.QVBoxLayout(self.sliderFrame) self.verticalLayout_2.setMargin(0) self.verticalLayout_2.setObjectName("verticalLayout_2") self.fileInfoLabel = QtGui.QLabel(self.sliderFrame) self.fileInfoLabel.setWordWrap(True) self.fileInfoLabel.setObjectName("fileInfoLabel") self.verticalLayout_2.addWidget(self.fileInfoLabel) self.seekSlider_2 = phonon.Phonon.SeekSlider(self.sliderFrame) self.seekSlider_2.setObjectName("seekSlider_2") self.verticalLayout_2.addWidget(self.seekSlider_2) self.volumeSlider_2 = phonon.Phonon.VolumeSlider(self.sliderFrame) self.volumeSlider_2.setObjectName("volumeSlider_2") self.verticalLayout_2.addWidget(self.volumeSlider_2) self.gridLayout.addWidget(self.sliderFrame, 3, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 579, 22)) self.menubar.setObjectName("menubar") self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuOpen_with = QtGui.QMenu(self.menuFile) self.menuOpen_with.setObjectName("menuOpen_with") self.menuOpen_copy_with = QtGui.QMenu(self.menuFile) self.menuOpen_copy_with.setObjectName("menuOpen_copy_with") self.menuExport_as = QtGui.QMenu(self.menuFile) self.menuExport_as.setObjectName("menuExport_as") self.menuLibrary = QtGui.QMenu(self.menubar) self.menuLibrary.setObjectName("menuLibrary") self.menuRescan_folders = QtGui.QMenu(self.menuLibrary) self.menuRescan_folders.setObjectName("menuRescan_folders") self.menuView = QtGui.QMenu(self.menubar) self.menuView.setObjectName("menuView") self.menuEdit = QtGui.QMenu(self.menubar) self.menuEdit.setObjectName("menuEdit") MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.dockWidget_2 = QtGui.QDockWidget(MainWindow) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.dockWidget_2.sizePolicy().hasHeightForWidth()) self.dockWidget_2.setSizePolicy(sizePolicy) self.dockWidget_2.setMinimumSize(QtCore.QSize(150, 242)) self.dockWidget_2.setMaximumSize(QtCore.QSize(150, 385)) self.dockWidget_2.setFeatures(QtGui.QDockWidget.DockWidgetClosable|QtGui.QDockWidget.DockWidgetMovable) self.dockWidget_2.setObjectName("dockWidget_2") self.dockWidgetContents_2 = QtGui.QWidget() self.dockWidgetContents_2.setObjectName("dockWidgetContents_2") self.verticalLayout = QtGui.QVBoxLayout(self.dockWidgetContents_2) self.verticalLayout.setObjectName("verticalLayout") self.tagView = QtGui.QListView(self.dockWidgetContents_2) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(60) sizePolicy.setVerticalStretch(100) sizePolicy.setHeightForWidth(self.tagView.sizePolicy().hasHeightForWidth()) self.tagView.setSizePolicy(sizePolicy) self.tagView.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.tagView.setDragDropMode(QtGui.QAbstractItemView.DragDrop) self.tagView.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.tagView.setObjectName("tagView") self.verticalLayout.addWidget(self.tagView) self.dockWidget_2.setWidget(self.dockWidgetContents_2) MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dockWidget_2) self.dockWidget = QtGui.QDockWidget(MainWindow) self.dockWidget.setFeatures(QtGui.QDockWidget.DockWidgetClosable|QtGui.QDockWidget.DockWidgetMovable) self.dockWidget.setObjectName("dockWidget") self.dockWidgetContents = QtGui.QWidget() self.dockWidgetContents.setObjectName("dockWidgetContents") self.gridLayout_2 = QtGui.QGridLayout(self.dockWidgetContents) self.gridLayout_2.setObjectName("gridLayout_2") self.stack = QtGui.QListView(self.dockWidgetContents) self.stack.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.stack.setDragEnabled(False) self.stack.setDragDropMode(QtGui.QAbstractItemView.DragOnly) self.stack.setDefaultDropAction(QtCore.Qt.CopyAction) self.stack.setAlternatingRowColors(True) self.stack.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.stack.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems) self.stack.setLayoutMode(QtGui.QListView.Batched) self.stack.setBatchSize(30) self.stack.setObjectName("stack") self.gridLayout_2.addWidget(self.stack, 0, 0, 1, 3) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 1, 0, 1, 1) self.pushButton = QtGui.QPushButton(self.dockWidgetContents) self.pushButton.setObjectName("pushButton") self.gridLayout_2.addWidget(self.pushButton, 1, 2, 1, 1) self.pushButton_2 = QtGui.QPushButton(self.dockWidgetContents) self.pushButton_2.setObjectName("pushButton_2") self.gridLayout_2.addWidget(self.pushButton_2, 1, 1, 1, 1) self.dockWidget.setWidget(self.dockWidgetContents) MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(8), self.dockWidget) self.dockWidget_3 = QtGui.QDockWidget(MainWindow) self.dockWidget_3.setFeatures(QtGui.QDockWidget.DockWidgetClosable|QtGui.QDockWidget.DockWidgetMovable) self.dockWidget_3.setObjectName("dockWidget_3") self.dockWidgetContents_3 = QtGui.QWidget() self.dockWidgetContents_3.setObjectName("dockWidgetContents_3") self.verticalLayout_3 = QtGui.QVBoxLayout(self.dockWidgetContents_3) self.verticalLayout_3.setObjectName("verticalLayout_3") self.comboBox = QtGui.QComboBox(self.dockWidgetContents_3) self.comboBox.setObjectName("comboBox") self.verticalLayout_3.addWidget(self.comboBox) self.dockWidget_3.setWidget(self.dockWidgetContents_3) MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dockWidget_3) self.actionQuit = QtGui.QAction(MainWindow) self.actionQuit.setObjectName("actionQuit") self.actionTest = QtGui.QAction(MainWindow) self.actionTest.setObjectName("actionTest") self.actionAll_folders = QtGui.QAction(MainWindow) self.actionAll_folders.setObjectName("actionAll_folders") self.actionEdit_all = QtGui.QAction(MainWindow) self.actionEdit_all.setObjectName("actionEdit_all") self.actionEdit_one_by_one = QtGui.QAction(MainWindow) self.actionEdit_one_by_one.setObjectName("actionEdit_one_by_one") self.actionPlay = QtGui.QAction(MainWindow) self.actionPlay.setCheckable(True) self.actionPlay.setObjectName("actionPlay") self.actionShow_file_info = QtGui.QAction(MainWindow) self.actionShow_file_info.setCheckable(True) self.actionShow_file_info.setChecked(True) self.actionShow_file_info.setObjectName("actionShow_file_info") self.actionLocation = QtGui.QAction(MainWindow) self.actionLocation.setCheckable(True) self.actionLocation.setChecked(True) self.actionLocation.setObjectName("actionLocation") self.actionShow_volume = QtGui.QAction(MainWindow) self.actionShow_volume.setCheckable(True) self.actionShow_volume.setChecked(True) self.actionShow_volume.setObjectName("actionShow_volume") self.actionShow_tags = QtGui.QAction(MainWindow) self.actionShow_tags.setCheckable(True) self.actionShow_tags.setChecked(True) self.actionShow_tags.setObjectName("actionShow_tags") self.actionShow_stack = QtGui.QAction(MainWindow) self.actionShow_stack.setCheckable(True) self.actionShow_stack.setChecked(True) self.actionShow_stack.setObjectName("actionShow_stack") self.actionStack = QtGui.QAction(MainWindow) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/ft/icons/_blank.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionStack.setIcon(icon) self.actionStack.setObjectName("actionStack") self.actionProject = QtGui.QAction(MainWindow) self.actionProject.setCheckable(True) self.actionProject.setChecked(True) self.actionProject.setObjectName("actionProject") self.actionPreferences = QtGui.QAction(MainWindow) self.actionPreferences.setObjectName("actionPreferences") self.actionQuit_2 = QtGui.QAction(MainWindow) self.actionQuit_2.setObjectName("actionQuit_2") self.menuFile.addAction(self.actionStack) self.menuFile.addAction(self.menuOpen_with.menuAction()) self.menuFile.addAction(self.menuOpen_copy_with.menuAction()) self.menuFile.addAction(self.menuExport_as.menuAction()) self.menuFile.addAction(self.actionPlay) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit_2) self.menuRescan_folders.addAction(self.actionAll_folders) self.menuRescan_folders.addSeparator() self.menuLibrary.addAction(self.menuRescan_folders.menuAction()) self.menuView.addAction(self.actionShow_file_info) self.menuView.addAction(self.actionLocation) self.menuView.addAction(self.actionShow_volume) self.menuView.addAction(self.actionShow_tags) self.menuView.addAction(self.actionShow_stack) self.menuView.addAction(self.actionProject) self.menuEdit.addAction(self.actionEdit_all) self.menuEdit.addAction(self.actionEdit_one_by_one) self.menuEdit.addSeparator() self.menuEdit.addAction(self.actionPreferences) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuEdit.menuAction()) self.menubar.addAction(self.menuLibrary.menuAction()) self.menubar.addAction(self.menuView.menuAction()) self.retranslateUi(MainWindow) QtCore.QObject.connect(self.actionShow_file_info, QtCore.SIGNAL("toggled(bool)"), self.fileInfoLabel.setVisible) QtCore.QObject.connect(self.actionLocation, QtCore.SIGNAL("toggled(bool)"), self.seekSlider_2.setVisible) QtCore.QObject.connect(self.actionShow_tags, QtCore.SIGNAL("toggled(bool)"), self.dockWidget_2.setVisible) QtCore.QObject.connect(self.actionShow_volume, QtCore.SIGNAL("toggled(bool)"), self.volumeSlider_2.setVisible) QtCore.QObject.connect(self.actionShow_stack, QtCore.SIGNAL("toggled(bool)"), self.dockWidget.setVisible) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "Sampleman", None, QtGui.QApplication.UnicodeUTF8)) self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "File", None, QtGui.QApplication.UnicodeUTF8)) self.menuOpen_with.setTitle(QtGui.QApplication.translate("MainWindow", "Open with", None, QtGui.QApplication.UnicodeUTF8)) self.menuOpen_copy_with.setTitle(QtGui.QApplication.translate("MainWindow", "Open copy with", None, QtGui.QApplication.UnicodeUTF8)) self.menuExport_as.setTitle(QtGui.QApplication.translate("MainWindow", "Export as", None, QtGui.QApplication.UnicodeUTF8)) self.menuLibrary.setTitle(QtGui.QApplication.translate("MainWindow", "Repos", None, QtGui.QApplication.UnicodeUTF8)) self.menuRescan_folders.setTitle(QtGui.QApplication.translate("MainWindow", "Rescan repos", None, QtGui.QApplication.UnicodeUTF8)) self.menuView.setTitle(QtGui.QApplication.translate("MainWindow", "View", None, QtGui.QApplication.UnicodeUTF8)) self.menuEdit.setTitle(QtGui.QApplication.translate("MainWindow", "Edit", None, QtGui.QApplication.UnicodeUTF8)) self.dockWidget_2.setWindowTitle(QtGui.QApplication.translate("MainWindow", "Tags", None, QtGui.QApplication.UnicodeUTF8)) self.dockWidget.setWindowTitle(QtGui.QApplication.translate("MainWindow", "Stack", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "Clear", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton_2.setText(QtGui.QApplication.translate("MainWindow", "Delete", None, QtGui.QApplication.UnicodeUTF8)) self.dockWidget_3.setWindowTitle(QtGui.QApplication.translate("MainWindow", "Project", None, QtGui.QApplication.UnicodeUTF8)) self.actionQuit.setText(QtGui.QApplication.translate("MainWindow", "Close", None, QtGui.QApplication.UnicodeUTF8)) self.actionTest.setText(QtGui.QApplication.translate("MainWindow", "Test", None, QtGui.QApplication.UnicodeUTF8)) self.actionAll_folders.setText(QtGui.QApplication.translate("MainWindow", "All folders", None, QtGui.QApplication.UnicodeUTF8)) self.actionAll_folders.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+Alt+R", None, QtGui.QApplication.UnicodeUTF8)) self.actionEdit_all.setText(QtGui.QApplication.translate("MainWindow", "Edit all", None, QtGui.QApplication.UnicodeUTF8)) self.actionEdit_all.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+E", None, QtGui.QApplication.UnicodeUTF8)) self.actionEdit_one_by_one.setText(QtGui.QApplication.translate("MainWindow", "Edit one by one", None, QtGui.QApplication.UnicodeUTF8)) self.actionEdit_one_by_one.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+Shift+E", None, QtGui.QApplication.UnicodeUTF8)) self.actionPlay.setText(QtGui.QApplication.translate("MainWindow", "Play", None, QtGui.QApplication.UnicodeUTF8)) self.actionPlay.setShortcut(QtGui.QApplication.translate("MainWindow", "Space", None, QtGui.QApplication.UnicodeUTF8)) self.actionShow_file_info.setText(QtGui.QApplication.translate("MainWindow", "File Info", None, QtGui.QApplication.UnicodeUTF8)) self.actionShow_file_info.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+I", None, QtGui.QApplication.UnicodeUTF8)) self.actionLocation.setText(QtGui.QApplication.translate("MainWindow", "Location", None, QtGui.QApplication.UnicodeUTF8)) self.actionLocation.setToolTip(QtGui.QApplication.translate("MainWindow", "Location", None, QtGui.QApplication.UnicodeUTF8)) self.actionLocation.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+L", None, QtGui.QApplication.UnicodeUTF8)) self.actionShow_volume.setText(QtGui.QApplication.translate("MainWindow", "Volume", None, QtGui.QApplication.UnicodeUTF8)) self.actionShow_volume.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+V", None, QtGui.QApplication.UnicodeUTF8)) self.actionShow_tags.setText(QtGui.QApplication.translate("MainWindow", "Tags", None, QtGui.QApplication.UnicodeUTF8)) self.actionShow_tags.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+T", None, QtGui.QApplication.UnicodeUTF8)) self.actionShow_stack.setText(QtGui.QApplication.translate("MainWindow", "Stack", None, QtGui.QApplication.UnicodeUTF8)) self.actionShow_stack.setToolTip(QtGui.QApplication.translate("MainWindow", "Show Stack", None, QtGui.QApplication.UnicodeUTF8)) self.actionShow_stack.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+B", None, QtGui.QApplication.UnicodeUTF8)) self.actionStack.setText(QtGui.QApplication.translate("MainWindow", "Stack", None, QtGui.QApplication.UnicodeUTF8)) self.actionStack.setToolTip(QtGui.QApplication.translate("MainWindow", "Stack selected files", None, QtGui.QApplication.UnicodeUTF8)) self.actionStack.setShortcut(QtGui.QApplication.translate("MainWindow", "S", None, QtGui.QApplication.UnicodeUTF8)) self.actionProject.setText(QtGui.QApplication.translate("MainWindow", "Project", None, QtGui.QApplication.UnicodeUTF8)) self.actionProject.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+P", None, QtGui.QApplication.UnicodeUTF8)) self.actionPreferences.setText(QtGui.QApplication.translate("MainWindow", "Preferences", None, QtGui.QApplication.UnicodeUTF8)) self.actionQuit_2.setText(QtGui.QApplication.translate("MainWindow", "Quit", None, QtGui.QApplication.UnicodeUTF8)) from PyQt4 import phonon import sampleman_rc
gpl-3.0
3,103,841,371,846,845,400
67.963636
144
0.739784
false
3.955162
false
false
false
Weihonghao/ECM
Vpy34/lib/python3.5/site-packages/theano/tensor/nlinalg.py
1
23539
from __future__ import absolute_import, print_function, division import logging import numpy from six.moves import xrange import theano from theano.tensor import as_tensor_variable from theano.gof import Op, Apply from theano.gradient import DisconnectedType from theano.tensor import basic as tensor logger = logging.getLogger(__name__) class MatrixPinv(Op): """Computes the pseudo-inverse of a matrix :math:`A`. The pseudo-inverse of a matrix :math:`A`, denoted :math:`A^+`, is defined as: "the matrix that 'solves' [the least-squares problem] :math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then :math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`. Note that :math:`Ax=AA^+b`, so :math:`AA^+` is close to the identity matrix. This method is not faster than `matrix_inverse`. Its strength comes from that it works for non-square matrices. If you have a square matrix though, `matrix_inverse` can be both more exact and faster to compute. Also this op does not get optimized into a solve op. """ __props__ = () def __init__(self): pass def make_node(self, x): x = as_tensor_variable(x) assert x.ndim == 2 return Apply(self, [x], [x.type()]) def perform(self, node, inputs, outputs): (x,) = inputs (z,) = outputs z[0] = numpy.linalg.pinv(x).astype(x.dtype) pinv = MatrixPinv() class MatrixInverse(Op): """Computes the inverse of a matrix :math:`A`. Given a square matrix :math:`A`, ``matrix_inverse`` returns a square matrix :math:`A_{inv}` such that the dot product :math:`A \cdot A_{inv}` and :math:`A_{inv} \cdot A` equals the identity matrix :math:`I`. Notes ----- When possible, the call to this op will be optimized to the call of ``solve``. """ __props__ = () def __init__(self): pass def make_node(self, x): x = as_tensor_variable(x) assert x.ndim == 2 return Apply(self, [x], [x.type()]) def perform(self, node, inputs, outputs): (x,) = inputs (z,) = outputs z[0] = numpy.linalg.inv(x).astype(x.dtype) def grad(self, inputs, g_outputs): r"""The gradient function should return .. math:: V\frac{\partial X^{-1}}{\partial X}, where :math:`V` corresponds to ``g_outputs`` and :math:`X` to ``inputs``. Using the `matrix cookbook <http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=3274>`_, one can deduce that the relation corresponds to .. math:: (X^{-1} \cdot V^{T} \cdot X^{-1})^T. """ x, = inputs xi = self(x) gz, = g_outputs # TT.dot(gz.T,xi) return [-matrix_dot(xi, gz.T, xi).T] def R_op(self, inputs, eval_points): r"""The gradient function should return .. math:: \frac{\partial X^{-1}}{\partial X}V, where :math:`V` corresponds to ``g_outputs`` and :math:`X` to ``inputs``. Using the `matrix cookbook <http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=3274>`_, one can deduce that the relation corresponds to .. math:: X^{-1} \cdot V \cdot X^{-1}. """ x, = inputs xi = self(x) ev, = eval_points if ev is None: return [None] return [-matrix_dot(xi, ev, xi)] def infer_shape(self, node, shapes): return shapes matrix_inverse = MatrixInverse() def matrix_dot(*args): """ Shorthand for product between several dots. Given :math:`N` matrices :math:`A_0, A_1, .., A_N`, ``matrix_dot`` will generate the matrix product between all in the given order, namely :math:`A_0 \cdot A_1 \cdot A_2 \cdot .. \cdot A_N`. """ rval = args[0] for a in args[1:]: rval = theano.tensor.dot(rval, a) return rval class AllocDiag(Op): """ Allocates a square matrix with the given vector as its diagonal. """ __props__ = () def make_node(self, _x): x = as_tensor_variable(_x) if x.type.ndim != 1: raise TypeError('AllocDiag only works on vectors', _x) return Apply(self, [x], [theano.tensor.matrix(dtype=x.type.dtype)]) def grad(self, inputs, g_outputs): return [extract_diag(g_outputs[0])] def perform(self, node, inputs, outputs): (x,) = inputs (z,) = outputs if x.ndim != 1: raise TypeError(x) z[0] = numpy.diag(x) def infer_shape(self, node, shapes): x_s, = shapes return [(x_s[0], x_s[0])] alloc_diag = AllocDiag() class ExtractDiag(Op): """Return the diagonal of a matrix. Notes ----- Works on the GPU. """ __props__ = ("view",) def __init__(self, view=False): self.view = view if self.view: self.view_map = {0: [0]} def make_node(self, _x): if not isinstance(_x, theano.Variable): x = as_tensor_variable(_x) else: x = _x if x.type.ndim != 2: raise TypeError('ExtractDiag only works on matrices', _x) y = x.type.clone(broadcastable=(False,))() return Apply(self, [x], [y]) def perform(self, node, ins, outs): """ For some reason numpy.diag(x) is really slow, so we implemented our own. """ x, = ins z, = outs # zero-dimensional matrices ... if x.shape[0] == 0 or x.shape[1] == 0: z[0] = node.outputs[0].type.value_zeros((0,)) return if x.shape[0] < x.shape[1]: rval = x[:, 0] else: rval = x[0] rval.strides = (x.strides[0] + x.strides[1],) if self.view: z[0] = rval else: z[0] = rval.copy() def __str__(self): return 'ExtractDiag{view=%s}' % self.view def grad(self, inputs, g_outputs): x = theano.tensor.zeros_like(inputs[0]) xdiag = alloc_diag(g_outputs[0]) return [theano.tensor.set_subtensor( x[:xdiag.shape[0], :xdiag.shape[1]], xdiag)] def infer_shape(self, node, shapes): x_s, = shapes shp = theano.tensor.min(node.inputs[0].shape) return [(shp,)] extract_diag = ExtractDiag() # TODO: optimization to insert ExtractDiag with view=True def diag(x): """ Numpy-compatibility method If `x` is a matrix, return its diagonal. If `x` is a vector return a matrix with it as its diagonal. * This method does not support the `k` argument that numpy supports. """ xx = as_tensor_variable(x) if xx.type.ndim == 1: return alloc_diag(xx) elif xx.type.ndim == 2: return extract_diag(xx) else: raise TypeError('diag requires vector or matrix argument', x) def trace(X): """ Returns the sum of diagonal elements of matrix X. Notes ----- Works on GPU since 0.6rc4. """ return extract_diag(X).sum() class Det(Op): """ Matrix determinant. Input should be a square matrix. """ __props__ = () def make_node(self, x): x = as_tensor_variable(x) assert x.ndim == 2 o = theano.tensor.scalar(dtype=x.dtype) return Apply(self, [x], [o]) def perform(self, node, inputs, outputs): (x,) = inputs (z,) = outputs try: z[0] = numpy.asarray(numpy.linalg.det(x), dtype=x.dtype) except Exception: print('Failed to compute determinant', x) raise def grad(self, inputs, g_outputs): gz, = g_outputs x, = inputs return [gz * self(x) * matrix_inverse(x).T] def infer_shape(self, node, shapes): return [()] def __str__(self): return "Det" det = Det() class Eig(Op): """ Compute the eigenvalues and right eigenvectors of a square array. """ _numop = staticmethod(numpy.linalg.eig) __props__ = () def make_node(self, x): x = as_tensor_variable(x) assert x.ndim == 2 w = theano.tensor.vector(dtype=x.dtype) v = theano.tensor.matrix(dtype=x.dtype) return Apply(self, [x], [w, v]) def perform(self, node, inputs, outputs): (x,) = inputs (w, v) = outputs w[0], v[0] = [z.astype(x.dtype) for z in self._numop(x)] def infer_shape(self, node, shapes): n = shapes[0][0] return [(n,), (n, n)] eig = Eig() class Eigh(Eig): """ Return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix. """ _numop = staticmethod(numpy.linalg.eigh) __props__ = ('UPLO',) def __init__(self, UPLO='L'): assert UPLO in ['L', 'U'] self.UPLO = UPLO def make_node(self, x): x = as_tensor_variable(x) assert x.ndim == 2 # Numpy's linalg.eigh may return either double or single # presision eigenvalues depending on installed version of # LAPACK. Rather than trying to reproduce the (rather # involved) logic, we just probe linalg.eigh with a trivial # input. w_dtype = self._numop([[numpy.dtype(x.dtype).type()]])[0].dtype.name w = theano.tensor.vector(dtype=w_dtype) v = theano.tensor.matrix(dtype=x.dtype) return Apply(self, [x], [w, v]) def perform(self, node, inputs, outputs): (x,) = inputs (w, v) = outputs w[0], v[0] = self._numop(x, self.UPLO) def grad(self, inputs, g_outputs): r"""The gradient function should return .. math:: \sum_n\left(W_n\frac{\partial\,w_n} {\partial a_{ij}} + \sum_k V_{nk}\frac{\partial\,v_{nk}} {\partial a_{ij}}\right), where [:math:`W`, :math:`V`] corresponds to ``g_outputs``, :math:`a` to ``inputs``, and :math:`(w, v)=\mbox{eig}(a)`. Analytic formulae for eigensystem gradients are well-known in perturbation theory: .. math:: \frac{\partial\,w_n} {\partial a_{ij}} = v_{in}\,v_{jn} .. math:: \frac{\partial\,v_{kn}} {\partial a_{ij}} = \sum_{m\ne n}\frac{v_{km}v_{jn}}{w_n-w_m} """ x, = inputs w, v = self(x) # Replace gradients wrt disconnected variables with # zeros. This is a work-around for issue #1063. gw, gv = _zero_disconnected([w, v], g_outputs) return [EighGrad(self.UPLO)(x, w, v, gw, gv)] def _zero_disconnected(outputs, grads): l = [] for o, g in zip(outputs, grads): if isinstance(g.type, DisconnectedType): l.append(o.zeros_like()) else: l.append(g) return l class EighGrad(Op): """ Gradient of an eigensystem of a Hermitian matrix. """ __props__ = ('UPLO',) def __init__(self, UPLO='L'): assert UPLO in ['L', 'U'] self.UPLO = UPLO if UPLO == 'L': self.tri0 = numpy.tril self.tri1 = lambda a: numpy.triu(a, 1) else: self.tri0 = numpy.triu self.tri1 = lambda a: numpy.tril(a, -1) def make_node(self, x, w, v, gw, gv): x, w, v, gw, gv = map(as_tensor_variable, (x, w, v, gw, gv)) assert x.ndim == 2 assert w.ndim == 1 assert v.ndim == 2 assert gw.ndim == 1 assert gv.ndim == 2 out_dtype = theano.scalar.upcast(x.dtype, w.dtype, v.dtype, gw.dtype, gv.dtype) out = theano.tensor.matrix(dtype=out_dtype) return Apply(self, [x, w, v, gw, gv], [out]) def perform(self, node, inputs, outputs): """ Implements the "reverse-mode" gradient for the eigensystem of a square matrix. """ x, w, v, W, V = inputs N = x.shape[0] outer = numpy.outer def G(n): return sum(v[:, m] * V.T[n].dot(v[:, m]) / (w[n] - w[m]) for m in xrange(N) if m != n) g = sum(outer(v[:, n], v[:, n] * W[n] + G(n)) for n in xrange(N)) # Numpy's eigh(a, 'L') (eigh(a, 'U')) is a function of tril(a) # (triu(a)) only. This means that partial derivative of # eigh(a, 'L') (eigh(a, 'U')) with respect to a[i,j] is zero # for i < j (i > j). At the same time, non-zero components of # the gradient must account for the fact that variation of the # opposite triangle contributes to variation of two elements # of Hermitian (symmetric) matrix. The following line # implements the necessary logic. out = self.tri0(g) + self.tri1(g).T # Make sure we return the right dtype even if NumPy performed # upcasting in self.tri0. outputs[0][0] = numpy.asarray(out, dtype=node.outputs[0].dtype) def infer_shape(self, node, shapes): return [shapes[0]] def eigh(a, UPLO='L'): return Eigh(UPLO)(a) class QRFull(Op): """ Full QR Decomposition. Computes the QR decomposition of a matrix. Factor the matrix a as qr, where q is orthonormal and r is upper-triangular. """ _numop = staticmethod(numpy.linalg.qr) __props__ = ('mode',) def __init__(self, mode): self.mode = mode def make_node(self, x): x = as_tensor_variable(x) assert x.ndim == 2, "The input of qr function should be a matrix." q = theano.tensor.matrix(dtype=x.dtype) if self.mode != 'raw': r = theano.tensor.matrix(dtype=x.dtype) else: r = theano.tensor.vector(dtype=x.dtype) return Apply(self, [x], [q, r]) def perform(self, node, inputs, outputs): (x,) = inputs (q, r) = outputs assert x.ndim == 2, "The input of qr function should be a matrix." q[0], r[0] = self._numop(x, self.mode) class QRIncomplete(Op): """ Incomplete QR Decomposition. Computes the QR decomposition of a matrix. Factor the matrix a as qr and return a single matrix. """ _numop = staticmethod(numpy.linalg.qr) __props__ = ('mode',) def __init__(self, mode): self.mode = mode def make_node(self, x): x = as_tensor_variable(x) assert x.ndim == 2, "The input of qr function should be a matrix." q = theano.tensor.matrix(dtype=x.dtype) return Apply(self, [x], [q]) def perform(self, node, inputs, outputs): (x,) = inputs (q,) = outputs assert x.ndim == 2, "The input of qr function should be a matrix." q[0] = self._numop(x, self.mode) def qr(a, mode="reduced"): """ Computes the QR decomposition of a matrix. Factor the matrix a as qr, where q is orthonormal and r is upper-triangular. Parameters ---------- a : array_like, shape (M, N) Matrix to be factored. mode : {'reduced', 'complete', 'r', 'raw'}, optional If K = min(M, N), then 'reduced' returns q, r with dimensions (M, K), (K, N) 'complete' returns q, r with dimensions (M, M), (M, N) 'r' returns r only with dimensions (K, N) 'raw' returns h, tau with dimensions (N, M), (K,) Note that array h returned in 'raw' mode is transposed for calling Fortran. Default mode is 'reduced' Returns ------- q : matrix of float or complex, optional A matrix with orthonormal columns. When mode = 'complete' the result is an orthogonal/unitary matrix depending on whether or not a is real/complex. The determinant may be either +/- 1 in that case. r : matrix of float or complex, optional The upper-triangular matrix. """ x = [[2, 1], [3, 4]] if isinstance(numpy.linalg.qr(x, mode), tuple): return QRFull(mode)(a) else: return QRIncomplete(mode)(a) class SVD(Op): """ Parameters ---------- full_matrices : bool, optional If True (default), u and v have the shapes (M, M) and (N, N), respectively. Otherwise, the shapes are (M, K) and (K, N), respectively, where K = min(M, N). compute_uv : bool, optional Whether or not to compute u and v in addition to s. True by default. """ # See doc in the docstring of the function just after this class. _numop = staticmethod(numpy.linalg.svd) __props__ = ('full_matrices', 'compute_uv') def __init__(self, full_matrices=True, compute_uv=True): self.full_matrices = full_matrices self.compute_uv = compute_uv def make_node(self, x): x = as_tensor_variable(x) assert x.ndim == 2, "The input of svd function should be a matrix." w = theano.tensor.matrix(dtype=x.dtype) u = theano.tensor.vector(dtype=x.dtype) v = theano.tensor.matrix(dtype=x.dtype) return Apply(self, [x], [w, u, v]) def perform(self, node, inputs, outputs): (x,) = inputs (w, u, v) = outputs assert x.ndim == 2, "The input of svd function should be a matrix." w[0], u[0], v[0] = self._numop(x, self.full_matrices, self.compute_uv) def svd(a, full_matrices=1, compute_uv=1): """ This function performs the SVD on CPU. Parameters ---------- full_matrices : bool, optional If True (default), u and v have the shapes (M, M) and (N, N), respectively. Otherwise, the shapes are (M, K) and (K, N), respectively, where K = min(M, N). compute_uv : bool, optional Whether or not to compute u and v in addition to s. True by default. Returns ------- U, V, D : matrices """ return SVD(full_matrices, compute_uv)(a) class lstsq(Op): __props__ = () def make_node(self, x, y, rcond): x = theano.tensor.as_tensor_variable(x) y = theano.tensor.as_tensor_variable(y) rcond = theano.tensor.as_tensor_variable(rcond) return theano.Apply(self, [x, y, rcond], [theano.tensor.matrix(), theano.tensor.dvector(), theano.tensor.lscalar(), theano.tensor.dvector()]) def perform(self, node, inputs, outputs): zz = numpy.linalg.lstsq(inputs[0], inputs[1], inputs[2]) outputs[0][0] = zz[0] outputs[1][0] = zz[1] outputs[2][0] = numpy.array(zz[2]) outputs[3][0] = zz[3] def matrix_power(M, n): """ Raise a square matrix to the (integer) power n. Parameters ---------- M : Tensor variable n : Python int """ result = 1 for i in xrange(n): result = theano.dot(result, M) return result def norm(x, ord): x = as_tensor_variable(x) ndim = x.ndim if ndim == 0: raise ValueError("'axis' entry is out of bounds.") elif ndim == 1: if ord is None: return tensor.sum(x**2)**0.5 elif ord == 'inf': return tensor.max(abs(x)) elif ord == '-inf': return tensor.min(abs(x)) elif ord == 0: return x[x.nonzero()].shape[0] else: try: z = tensor.sum(abs(x**ord))**(1. / ord) except TypeError: raise ValueError("Invalid norm order for vectors.") return z elif ndim == 2: if ord is None or ord == 'fro': return tensor.sum(abs(x**2))**(0.5) elif ord == 'inf': return tensor.max(tensor.sum(abs(x), 1)) elif ord == '-inf': return tensor.min(tensor.sum(abs(x), 1)) elif ord == 1: return tensor.max(tensor.sum(abs(x), 0)) elif ord == -1: return tensor.min(tensor.sum(abs(x), 0)) else: raise ValueError(0) elif ndim > 2: raise NotImplementedError("We don't support norm witn ndim > 2") class TensorInv(Op): """ Class wrapper for tensorinv() function; Theano utilization of numpy.linalg.tensorinv; """ _numop = staticmethod(numpy.linalg.tensorinv) __props__ = ('ind',) def __init__(self, ind=2): self.ind = ind def make_node(self, a): a = as_tensor_variable(a) out = a.type() return Apply(self, [a], [out]) def perform(self, node, inputs, outputs): (a,) = inputs (x,) = outputs x[0] = self._numop(a, self.ind) def infer_shape(self, node, shapes): sp = shapes[0][self.ind:] + shapes[0][:self.ind] return [sp] def tensorinv(a, ind=2): """ Does not run on GPU; Theano utilization of numpy.linalg.tensorinv; Compute the 'inverse' of an N-dimensional array. The result is an inverse for `a` relative to the tensordot operation ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy, ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the tensordot operation. Parameters ---------- a : array_like Tensor to 'invert'. Its shape must be 'square', i. e., ``prod(a.shape[:ind]) == prod(a.shape[ind:])``. ind : int, optional Number of first indices that are involved in the inverse sum. Must be a positive integer, default is 2. Returns ------- b : ndarray `a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``. Raises ------ LinAlgError If `a` is singular or not 'square' (in the above sense). """ return TensorInv(ind)(a) class TensorSolve(Op): """ Theano utilization of numpy.linalg.tensorsolve Class wrapper for tensorsolve function. """ _numop = staticmethod(numpy.linalg.tensorsolve) __props__ = ('axes', ) def __init__(self, axes=None): self.axes = axes def make_node(self, a, b): a = as_tensor_variable(a) b = as_tensor_variable(b) out_dtype = theano.scalar.upcast(a.dtype, b.dtype) x = theano.tensor.matrix(dtype=out_dtype) return Apply(self, [a, b], [x]) def perform(self, node, inputs, outputs): (a, b,) = inputs (x,) = outputs x[0] = self._numop(a, b, self.axes) def tensorsolve(a, b, axes=None): """ Theano utilization of numpy.linalg.tensorsolve. Does not run on GPU! Solve the tensor equation ``a x = b`` for x. It is assumed that all indices of `x` are summed over in the product, together with the rightmost indices of `a`, as is done in, for example, ``tensordot(a, x, axes=len(b.shape))``. Parameters ---------- a : array_like Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals the shape of that sub-tensor of `a` consisting of the appropriate number of its rightmost indices, and must be such that ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be 'square'). b : array_like Right-hand tensor, which can be of any shape. axes : tuple of ints, optional Axes in `a` to reorder to the right, before inversion. If None (default), no reordering is done. Returns ------- x : ndarray, shape Q Raises ------ LinAlgError If `a` is singular or not 'square' (in the above sense). """ return TensorSolve(axes)(a, b)
agpl-3.0
5,579,638,122,380,263,000
27.190419
80
0.550363
false
3.508571
false
false
false
cylc/cylc
cylc/flow/cycling/loader.py
1
4880
# THIS FILE IS PART OF THE CYLC SUITE ENGINE. # Copyright (C) NIWA & British Crown (Met Office) & Contributors. # # 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/>. """ Tasks spawn a sequence of POINTS (P) separated by INTERVALS (I). Each task may have multiple sequences, e.g. 12-hourly and 6-hourly. """ from . import integer from . import iso8601 from metomi.isodatetime.data import Calendar ISO8601_CYCLING_TYPE = 'iso8601' INTEGER_CYCLING_TYPE = 'integer' IS_OFFSET_ABSOLUTE_IMPLS = { INTEGER_CYCLING_TYPE: integer.is_offset_absolute, ISO8601_CYCLING_TYPE: iso8601.is_offset_absolute, } POINTS = {INTEGER_CYCLING_TYPE: integer.IntegerPoint, ISO8601_CYCLING_TYPE: iso8601.ISO8601Point} DUMP_FORMAT_GETTERS = {INTEGER_CYCLING_TYPE: integer.get_dump_format, ISO8601_CYCLING_TYPE: iso8601.get_dump_format} POINT_RELATIVE_GETTERS = { INTEGER_CYCLING_TYPE: integer.get_point_relative, ISO8601_CYCLING_TYPE: iso8601.get_point_relative } INTERVALS = {INTEGER_CYCLING_TYPE: integer.IntegerInterval, ISO8601_CYCLING_TYPE: iso8601.ISO8601Interval} SEQUENCES = {INTEGER_CYCLING_TYPE: integer.IntegerSequence, ISO8601_CYCLING_TYPE: iso8601.ISO8601Sequence} INIT_FUNCTIONS = {INTEGER_CYCLING_TYPE: integer.init_from_cfg, ISO8601_CYCLING_TYPE: iso8601.init_from_cfg} class DefaultCycler: """Store the default TYPE for Cyclers.""" TYPE = None def get_point(*args, **kwargs): """Return a cylc.flow.cycling.PointBase-derived object from a string.""" if args[0] is None: return None cycling_type = kwargs.pop("cycling_type", DefaultCycler.TYPE) return get_point_cls(cycling_type=cycling_type)(*args, **kwargs) def get_point_cls(cycling_type=None): """Return the cylc.flow.cycling.PointBase-derived class we're using.""" if cycling_type is None: cycling_type = DefaultCycler.TYPE return POINTS[cycling_type] def get_dump_format(cycling_type=None): """Return cycle point dump format, or None.""" return DUMP_FORMAT_GETTERS[cycling_type]() def get_point_relative(*args, **kwargs): """Return a point from an offset expression and a base point.""" cycling_type = kwargs.pop("cycling_type", DefaultCycler.TYPE) return POINT_RELATIVE_GETTERS[cycling_type](*args, **kwargs) def get_interval(*args, **kwargs): """Return a cylc.flow.cycling.IntervalBase-derived object from a string.""" if args[0] is None: return None cycling_type = kwargs.pop("cycling_type", DefaultCycler.TYPE) return get_interval_cls(cycling_type=cycling_type)(*args, **kwargs) def get_interval_cls(cycling_type=None): """Return the cylc.flow.cycling.IntervalBase-derived class we're using.""" if cycling_type is None: cycling_type = DefaultCycler.TYPE return INTERVALS[cycling_type] def get_sequence(*args, **kwargs): """Return a cylc.flow.cycling.SequenceBase-derived object from a string.""" if args[0] is None: return None cycling_type = kwargs.pop("cycling_type", DefaultCycler.TYPE) return get_sequence_cls(cycling_type=cycling_type)(*args, **kwargs) def get_sequence_cls(cycling_type=None): """Return the cylc.flow.cycling.SequenceBase-derived class we're using.""" if cycling_type is None: cycling_type = DefaultCycler.TYPE return SEQUENCES[cycling_type] def init_cyclers(cfg): """Initialise cycling specifics using the suite configuration (cfg).""" DefaultCycler.TYPE = cfg['scheduling']['cycling mode'] if DefaultCycler.TYPE in Calendar.MODES: DefaultCycler.TYPE = ISO8601_CYCLING_TYPE INIT_FUNCTIONS[DefaultCycler.TYPE](cfg) def is_offset_absolute(offset_string, **kwargs): """Return True if offset_string is a point rather than an interval.""" cycling_type = kwargs.pop("cycling_type", DefaultCycler.TYPE) return IS_OFFSET_ABSOLUTE_IMPLS[cycling_type](offset_string) def standardise_point_string(point_string, cycling_type=None): """Return a standardised version of point_string.""" if point_string is None: return None point = get_point(point_string, cycling_type=cycling_type) if point is not None: point.standardise() point_string = str(point) return point_string
gpl-3.0
2,625,730,440,720,114,000
33.366197
79
0.71168
false
3.277367
false
false
false
tjmonsi/cmsc129-2016-repo
submissions/exercise3/pitargue/lexical_analyzer.py
1
8280
import string class DFA: keywords = [ 'var', 'input', 'output', 'break', 'continue', 'if', 'elsif', 'else', 'switch', 'case', 'default', 'while', 'do', 'for', 'foreach', 'in', 'function', 'return', 'true', 'false' ] def __init__(self, transition_functions, start_state, accept_states): self.transition_functions = transition_functions self.accept_states = accept_states self.start_state = start_state self.state_count = 0 + len(accept_states) self.token = '' def create_keyword(self, keyword, name): current_state = self.start_state for i in range(len(keyword)): if (current_state, keyword[i]) in self.transition_functions.keys(): current_state = self.transition_functions[(current_state, keyword[i])] else: self.state_count += 1 self.transition_functions[(current_state, keyword[i])] = current_state = self.state_count self.accept_states[self.state_count] = name.upper() + '_KEYWORD' # create a list of lexemes (a tuple containing the lexeme name and the token) based from the given input def tokenize(self, input): result = [] current_state = self.start_state for i in range(len(input)): if (current_state, input[i]) in self.transition_functions.keys(): temp = self.transition_functions[(current_state, input[i])] self.token = self.token + input[i] current_state = temp if i+1 < len(input): if current_state in self.accept_states.keys() and (current_state, input[i+1]) not in self.transition_functions.keys(): #result.append((self.accept_states[current_state], self.token)) res = self.accept_states[current_state] if res == 'IDENTIFIER': if self.token in self.keywords: result.append((self.token.upper() + '_KEYWORD', self.token)) else: result.append((res, self.token)) else: result.append((self.accept_states[current_state], self.token)) self.token = '' current_state = self.start_state elif current_state in self.accept_states.keys(): #result.append((self.accept_states[current_state], self.token)) res = self.accept_states[current_state] if res == 'IDENTIFIER': if self.token in self.keywords: result.append((self.token.upper() + '_KEYWORD', self.token)) else: result.append((res, self.token)) else: result.append((self.accept_states[current_state], self.token)) self.token = '' current_state = self.start_state else: result.append(('UNKNOWN_TOKEN', self.token)) self.token = '' return result def create_DFA(): dfa = DFA({}, 0, {}) # add dfa for keywords #dfa.create_keyword('def', 'identifier') #dfa.create_keyword('input', 'input') #dfa.create_keyword('output', 'output') #dfa.create_keyword('break', 'break') #dfa.create_keyword('continue', 'continue') #dfa.create_keyword('if', 'if') #dfa.create_keyword('elsif', 'else_if') #dfa.create_keyword('else', 'else') #dfa.create_keyword('switch', 'switch') #dfa.create_keyword('case', 'case') #dfa.create_keyword('default', 'default') #dfa.create_keyword('while', 'while') #dfa.create_keyword('do', 'do') #dfa.create_keyword('for', 'for') #dfa.create_keyword('foreach', 'foreach') #dfa.create_keyword('in', 'in') #dfa.create_keyword('function', 'function') #dfa.create_keyword('return', 'return') #dfa.create_keyword('true', 'true') #dfa.create_keyword('false', 'false') # add dfa for symbols dfa.create_keyword('(', 'open_parenthesis') dfa.create_keyword(')', 'close_parenthesis') dfa.create_keyword('[', 'open_bracket') dfa.create_keyword(']', 'close_bracket') dfa.create_keyword('{', 'open_curly_brace') dfa.create_keyword('}', 'close_curly_brace') dfa.create_keyword(';', 'semicolon') dfa.create_keyword(',', 'comma') dfa.create_keyword('?', 'question_mark') dfa.create_keyword(':', 'colon') dfa.create_keyword('+', 'plus') dfa.create_keyword('-', 'minus') dfa.create_keyword('*', 'multiply') dfa.create_keyword('/', 'divide') dfa.create_keyword('%', 'modulo') dfa.create_keyword('=', 'equal_sign') dfa.create_keyword('&&', 'and') dfa.create_keyword('||', 'or') dfa.create_keyword('!', 'not') dfa.create_keyword('==', 'equals') dfa.create_keyword('!=', 'not_equals') dfa.create_keyword('>', 'greater_than') dfa.create_keyword('<', 'less_than') dfa.create_keyword('>=', 'greater_than_or_equals') dfa.create_keyword('<=', 'less_than_or_equals') dfa.create_keyword('++', 'increment') dfa.create_keyword('--', 'decrement') # add dfa for number literals current_state = dfa.start_state dfa.state_count += 1 for c in string.digits: dfa.transition_functions[(current_state, c)] = dfa.state_count dfa.transition_functions[(dfa.start_state, c)] = dfa.state_count dfa.transition_functions[(dfa.state_count, c)] = dfa.state_count dfa.accept_states[dfa.state_count] = 'INTEGER_LITERAL' current_state = dfa.state_count dfa.state_count += 1 dfa.transition_functions[(current_state, '.')] = dfa.state_count dfa.transition_functions[(dfa.start_state, '.')] = dfa.state_count current_state = dfa.state_count dfa.state_count += 1 for c in string.digits: dfa.transition_functions[(current_state, c)] = dfa.state_count dfa.transition_functions[(dfa.state_count, c)] = dfa.state_count dfa.accept_states[dfa.state_count] = 'FLOAT_LITERAL' # add dfa for string literals current_state = dfa.start_state dfa.state_count += 1 dfa.transition_functions[(current_state, '"')] = dfa.state_count current_state = dfa.state_count dfa.state_count += 1 for c in string.printable: dfa.transition_functions[(current_state, c)] = dfa.state_count dfa.transition_functions[(dfa.state_count, c)] = dfa.state_count current_state = dfa.state_count dfa.state_count += 1 dfa.transition_functions[(current_state, '"')] = dfa.state_count dfa.accept_states[dfa.state_count] = 'STRING_LITERAL'; # add dfa for single line comment current_state = dfa.start_state dfa.state_count += 1 dfa.transition_functions[(current_state, '@')] = dfa.state_count current_state = dfa.state_count dfa.state_count += 1 for c in string.printable: dfa.transition_functions[(current_state, c)] = dfa.state_count dfa.transition_functions[(dfa.state_count, c)] = dfa.state_count current_state = dfa.state_count dfa.state_count += 1 dfa.transition_functions[(current_state, '\n')] = dfa.state_count dfa.accept_states[dfa.state_count] = 'SINGLE-LINE COMMENT' # add dfa for identifiers current_state = dfa.start_state dfa.state_count += 1 for c in string.ascii_letters: dfa.transition_functions[(current_state, c)] = dfa.state_count #current_state = dfa.state_count #dfa.state_count += 1 for c in string.ascii_letters: #dfa.transition_functions[(current_state, c)] = dfa.state_count dfa.transition_functions[(dfa.state_count, c)] = dfa.state_count for c in string.digits: #dfa.transition_functions[(current_state, c)] = dfa.state_count dfa.transition_functions[(dfa.state_count, c)] = dfa.state_count #dfa.transition_functions[(current_state, '_')] = dfa.state_count dfa.transition_functions[(dfa.state_count, '_')] = dfa.state_count dfa.accept_states[dfa.state_count] = 'IDENTIFIER' return dfa
mit
3,629,047,361,692,439,600
39.990099
134
0.586957
false
3.604702
false
false
false
aipescience/django-daiquiri
daiquiri/core/adapter/download/base.py
1
4910
import logging import csv import subprocess import re from django.conf import settings from daiquiri.core.generators import generate_csv, generate_votable, generate_fits from daiquiri.core.utils import get_doi_url logger = logging.getLogger(__name__) class BaseDownloadAdapter(object): def __init__(self, database_key, database_config): self.database_key = database_key self.database_config = database_config def generate(self, format_key, columns, sources=[], schema_name=None, table_name=None, nrows=None, query_status=None, query=None, query_language=None): # create the final list of arguments subprocess.Popen if format_key == 'sql': # create the final list of arguments subprocess.Popen self.set_args(schema_name, table_name) return self.generate_dump() else: # create the final list of arguments subprocess.Popen self.set_args(schema_name, table_name, data_only=True) # prepend strings with settings.FILES_BASE_PATH if they refer to files prepend = self.get_prepend(columns) if format_key == 'csv': return generate_csv(self.generate_rows(prepend=prepend), columns) elif format_key == 'votable': return generate_votable(self.generate_rows(prepend=prepend), columns, table=self.get_table_name(schema_name, table_name), infos=self.get_infos(query_status, query, query_language, sources), links=self.get_links(sources), empty=(nrows==0)) elif format_key == 'fits': return generate_fits(self.generate_rows(prepend=prepend), columns, nrows, table_name=self.get_table_name(schema_name, table_name)) else: raise Exception('Not supported.') def generate_dump(self): # log the arguments logger.debug('execute "%s"' % ' '.join(self.args)) # excecute the subprocess try: process = subprocess.Popen(self.args, stdout=subprocess.PIPE) for line in process.stdout: if not line.startswith((b'\n', b'\r\n', b'--', b'SET', b'/*!')): yield line.decode() except subprocess.CalledProcessError as e: logger.error('Command PIPE returned non-zero exit status: %s' % e) def generate_rows(self, prepend=None): # log the arguments logger.debug('execute "%s"' % ' '.join(self.args)) # excecute the subprocess try: process = subprocess.Popen(self.args, stdout=subprocess.PIPE) for line in process.stdout: insert_pattern = re.compile('^INSERT INTO .*? VALUES \((.*?)\);') insert_result = insert_pattern.match(line.decode()) if insert_result: line = insert_result.group(1) reader = csv.reader([line], quotechar="'", skipinitialspace=True) row = next(reader) if prepend: yield [(prepend[i] + cell if (i in prepend and cell != 'NULL') else cell) for i, cell in enumerate(row)] else: yield row except subprocess.CalledProcessError as e: logger.error('Command PIPE returned non-zero exit status: %s' % e) def get_prepend(self, columns): if not settings.FILES_BASE_URL: return {} # prepend strings with settings.FILES_BASE_PATH if they refer to files prepend = {} for i, column in enumerate(columns): column_ucd = column.get('ucd') if column_ucd and 'meta.ref' in column_ucd and \ ('meta.file' in column_ucd or 'meta.note' in column_ucd or 'meta.image' in column_ucd): prepend[i] = settings.FILES_BASE_URL return prepend def get_table_name(self, schema_name, table_name): return '%(schema_name)s.%(table_name)s' % { 'schema_name': schema_name, 'table_name': table_name } def get_infos(self, query_status, query, query_language, sources): infos = [ ('QUERY_STATUS', query_status), ('QUERY', query), ('QUERY_LANGUAGE', query_language) ] for source in sources: infos.append(('SOURCE', '%(schema_name)s.%(table_name)s' % source)) return infos def get_links(self, sources): return [( '%(schema_name)s.%(table_name)s' % source, 'doc', get_doi_url(source['doi']) if source['doi'] else source['url'] ) for source in sources]
apache-2.0
6,772,274,127,375,952,000
36.480916
128
0.555804
false
4.322183
false
false
false
hiro2016/ergodox_gui_configurator
GUIComponents/KeyPresstInterceptorComponent.py
1
9286
import platform from threading import Timer from PyQt5 import QtCore from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QTextEdit, QLabel, QSizePolicy, QLineEdit, QApplication, QWidget import sys from NoneGUIComponents import keypress_observer from NoneGUIComponents.dict_keys import * from NoneGUIComponents.key_conf_dict_parser import KeyConfDictParser class KeyPressInterceptorComponent(QVBoxLayout, QObject): """"" A GUI component: label, QTextEdit(Captures the last user key stroke when selected). label, label(shows the guesstimate of the hid usage id) label, QTextEdit(shows the keyname;editiable) The last item is editable because it's it's part of display string for QPushButtons in CentralWidget. Upon a key press this script finds: the key's common name if available Upon a key press this script guess: the keycode hid usage id the key sends To manage two information sources, pyxhook and QTextEdit, each running in its own thread and updating gui independently, using flag: boolean literalUpdated and Timer to check if QTextEdit field needs to be cleared. Ugly but truly solving the issue is not worth the effort as of now. Note: method call chains: QTextEdit event -> eventFilter -> connect_keypress_observer -> pyxhook connection established. QTextEdit event -> eventFilter -> disconnect_keypress_observer -> disconnect pyxhook connection. pyxhook keypress event -> inner function onKeyPress -> signalKeyPressed-> on_key_pressed pyxhook keypress event -> inner function onKeyPress -> fieldUpdateTimer -> inner function checkIfModifierKeyPressed """"" # Here to call QTextEdit method from non-qt thread. # connected to on_key_pressed signalKeyPressed = pyqtSignal(str, str) # sets literal_input_te to "" from any thread. signalClearTextEdit = pyqtSignal() # referenced and set by by fieldUpdateTimer param function # checkIfModifierKeyPressed. # set by __init_gui::filter # Used to check if QLineEdit needs to be updated/cleared literalUpdated = False # Used Like PostDelayed or Future. # Decide whether to clear the literal_input_et after # both Qt and keypress_observer callback are completed. fieldUpdateTimer = None def __init__(self, prv_config:dict={}): super().__init__() self.__init_gui(prv_config) self.is_keypress_observer_connected = False # Enable user input scanning only when the top mont QTextEdit is # selected. self.literal_input_te.installEventFilter(self) # clears text edit where user select to capture scancode # this is necessary to make sure the te contains nothing # after the user presses a modifier key. te = self.literal_input_te self.signalClearTextEdit.connect(lambda f=te: f.clear()) self.setFocus() # initializing attributes self.keypress_observer = None def setFocus(self, reason=QtCore.Qt.NoFocusReason): self.literal_input_te.setFocus(reason) # Only connected when QTextEdit is selected. def connect_keypress_observer(self): if self.is_keypress_observer_connected == True: return self.signalKeyPressed.connect(self.on_key_pressed) # qwidget cannot be accessed by an external thread, so doing it via signal. def onKeyPress(hid_usage_id:str, keyname:str, trigger = self.signalKeyPressed ): trigger.emit(hid_usage_id,keyname) # Check if the key pressed is a modifier. If so, clear literal_input_te. def checkIfModifierKeyPressed(): if not self.literalUpdated: self.signalClearTextEdit.emit() self.literalUpdated = False self.fieldUpdateTimer = None self.fieldUpdateTimer = Timer(0.05, checkIfModifierKeyPressed) self.fieldUpdateTimer.start() self.keypress_observer = keypress_observer.KeyPressObserver(onKeyPress) self.is_keypress_observer_connected = True def disconnect_keypress_observer(self): # this maybe called after closeEvent # OR before connect called try: self.signalKeyPressed.disconnect() except TypeError as e: print(e) msg = "disconnect() failed between 'signalKeyPressed' and all its connections" if msg not in str(e): raise e if self.keypress_observer is not None: if self.is_keypress_observer_connected: self.keypress_observer.destroy() self.keypress_observer = None self.is_keypress_observer_connected = False def __init_gui(self,d): p = KeyConfDictParser(d) # self.font = QFont() # self.font.setPointSize(13) bl = self # bl = self.vertical_box_layout = QVBoxLayout() hl1 = QHBoxLayout() hl1.setContentsMargins(0,5,5, 5) hl1.setSpacing(5) # literal row l_literal = QLabel("input literal") self.literal_input_te = input_literal = QLineEdit() # input_literal.setMaximumHeight(font_height) # input_literal.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) def filter(): length = len(input_literal.text()) self.literalUpdated = True if length == 2: c = input_literal.cursor() # c = input_literal.textCursor() # c.movePosition(QTextCursor.Left,QTextCursor.MoveAnchor) # c.deletePreviousChar() # c.movePosition(QTextCursor.Right,QTextCursor.MoveAnchor) ct = input_literal.text() input_literal.clear() input_literal.setText(ct[1]) input_literal.textChanged.connect(filter # stackoverflow # lambda: te.setText(te.toPlainText()[-1]) ) hl1.addWidget(l_literal) hl1.addWidget(input_literal) # hid usage id row hl2 = QHBoxLayout() hl2.setContentsMargins(0,5,5, 5) hl2.setSpacing(5) l_hid_usage_id = QLabel("HID usage id:") hl2.addWidget(l_hid_usage_id) self.hid_usage_id_display = QLabel()# contents will be set upon user input self.hid_usage_id_display.setText(p.hid_usage_id) hl2.addWidget(self.hid_usage_id_display) # key name row hl3 = QHBoxLayout() hl3.setContentsMargins(0,5,5, 5) hl3.setSpacing(5) l_key_name = QLabel("Key's name") hl3.addWidget(l_key_name) self.key_name = QLineEdit()# contents will be set upon user input self.key_name.setText(p.keyname) # self.key_name.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) # self.key_name.setMaximumHeight(font_height) hl3.addWidget(self.key_name) bl.addLayout(hl1) bl.addLayout(hl2) bl.addLayout(hl3) # self.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding) # self.setLayout(bl) bl.setAlignment(QtCore.Qt.AlignTop) # self.setGeometry(3,3,300,300) # print(self.geometry().height()) # self.setStyleSheet("background-color:red;") def on_key_pressed(self, hid_usage_id:str, common_keyname:str): self.hid_usage_id_display.setText(hid_usage_id) self.key_name.setText(str(common_keyname)) def closeEvent(self, QCloseEvent): self.disconnect_keypress_observer() super().closeEvent(QCloseEvent) def eventFilter(self, source, event): if(source is not self.literal_input_te): return super().eventFilter(source, event) # sometimes FocusIn is called twice. if event.type() == QtCore.QEvent.FocusOut: if self.is_keypress_observer_connected: self.disconnect_keypress_observer() elif event.type() == QtCore.QEvent.FocusIn: if not self.is_keypress_observer_connected: self.connect_keypress_observer() return super().eventFilter(source, event) def getData(self) -> dict: data = { key_hid_usage_id :self.hid_usage_id_display.text(), key_key_name:self.key_name.text() } return data def setEnabled(self,state): self.key_name.setEnabled(state) self.literal_input_te.setEnabled(state) if state: self.setFocus() self.connect_keypress_observer() else: self.disconnect_keypress_observer() if __name__ == "__main__": app = QApplication(sys.argv) # t = ScancodeViewer() # t = KeyCodeViewer() w = QWidget() t = KeyPressInterceptorComponent() w.setLayout(t) w.show () r = app.exec_() sys.exit(r) print(t.getData())
gpl-2.0
-1,803,215,776,816,161,300
35.703557
118
0.620719
false
4.042664
false
false
false
vprusso/youtube_tutorials
web_scraping_and_automation/selenium/craigstlist_scraper.py
1
2952
# YouTube Video (Part 1): https://www.youtube.com/watch?v=4o2Eas2WqAQ&t=0s&list=PL5tcWHG-UPH1aSWALagYP2r3RMmuslcrr # YouTube Video (Part 2): https://www.youtube.com/watch?v=x5o0XFozYnE&t=716s&list=PL5tcWHG-UPH1aSWALagYP2r3RMmuslcrr # YouTube Video (Part 3): https://www.youtube.com/watch?v=_y43iqSJgnc&t=1s&list=PL5tcWHG-UPH1aSWALagYP2r3RMmuslcrr from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException from bs4 import BeautifulSoup import urllib.request class CraiglistScraper(object): def __init__(self, location, postal, max_price, radius): self.location = location self.postal = postal self.max_price = max_price self.radius = radius self.url = f"https://{location}.craigslist.org/search/sss?search_distance={radius}&postal={postal}&max_price={max_price}" self.driver = webdriver.Firefox() self.delay = 3 def load_craigslist_url(self): self.driver.get(self.url) try: wait = WebDriverWait(self.driver, self.delay) wait.until(EC.presence_of_element_located((By.ID, "searchform"))) print("Page is ready") except TimeoutException: print("Loading took too much time") def extract_post_information(self): all_posts = self.driver.find_elements_by_class_name("result-row") dates = [] titles = [] prices = [] for post in all_posts: title = post.text.split("$") if title[0] == '': title = title[1] else: title = title[0] title = title.split("\n") price = title[0] title = title[-1] title = title.split(" ") month = title[0] day = title[1] title = ' '.join(title[2:]) date = month + " " + day #print("PRICE: " + price) #print("TITLE: " + title) #print("DATE: " + date) titles.append(title) prices.append(price) dates.append(date) return titles, prices, dates def extract_post_urls(self): url_list = [] html_page = urllib.request.urlopen(self.url) soup = BeautifulSoup(html_page, "lxml") for link in soup.findAll("a", {"class": "result-title hdrlnk"}): print(link["href"]) url_list.append(link["href"]) return url_list def quit(self): self.driver.close() location = "sfbay" postal = "94201" max_price = "500" radius = "5" scraper = CraiglistScraper(location, postal, max_price, radius) scraper.load_craigslist_url() titles, prices, dates = scraper.extract_post_information() print(titles) #scraper.extract_post_urls() #scraper.quit()
gpl-3.0
6,487,594,359,226,624,000
30.073684
129
0.609417
false
3.389208
false
false
false
cisco-oss-eng/Cloud99
cloud99/loaders/__init__.py
1
2556
# Copyright 2016 Cisco Systems, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import pykka from cloud99.logging_setup import LOGGER class TaskStatus(object): INIT = "init" STOPPED = "stopped" ABORTED = "aborted" FINISHED = "finished" class BaseLoader(pykka.ThreadingActor): def __init__(self, observer, openrc, inventory, **params): # args kept to match signature super(BaseLoader, self).__init__() self.observer = observer self.task_status = TaskStatus.INIT self.runner_thread = None self.checker_thread = None self.times = 0 def on_receive(self, message): msg = message.get('msg') params = message.get("params") if msg == 'validate_config': self.validate_config() if msg == 'start': self.execute(params) if msg == "stop_task": self.abort() if msg == 'stop': self.stop() def abort(self): self.task_status = TaskStatus.ABORTED self.wait_for_threads() self.observer.tell({'msg': 'loader_finished', "times": self.times}) def stop(self): self.task_status = TaskStatus.STOPPED self.wait_for_threads() super(BaseLoader, self).stop() def wait_for_threads(self): if self.runner_thread: self.runner_thread.join() if self.checker_thread: self.checker_thread.join() self.reset() def reset(self): self.runner_thread = None self.checker_thread = None self.task_status = TaskStatus.INIT def on_failure(self, exception_type, exception_value, traceback): LOGGER.error(exception_type, exception_value, traceback) @abc.abstractmethod def validate_config(self): """""" @abc.abstractmethod def execute(self, params=None): """ """ @abc.abstractmethod def load(self, **params): """""" @abc.abstractmethod def check(self, **params): """ """
apache-2.0
4,718,103,721,506,559,000
28.045455
75
0.625978
false
3.99375
false
false
false
olimastro/DeepMonster
deepmonster/lasagne/nn.py
1
16191
""" neural network stuff, intended to be used with Lasagne All this code, except otherwise mentionned, was written by openai taken from improvedgan repo on github """ import numpy as np import theano as th import theano.tensor as T from theano.tensor.nnet.abstract_conv import (bilinear_upsampling, ) from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams import lasagne from lasagne.layers import dnn, ElemwiseSumLayer, NonlinearityLayer from lasagne.init import Normal, Constant from deepmonster.adlf.utils import parse_tuple # T.nnet.relu has some stability issues, this is better def relu(x): return T.maximum(x, 0) def lrelu(x, a=0.2): return T.maximum(x, a*x) # kyle's relu def divrelu(x): return (x + abs(x)) / 2. # kyle's tanh def hard_tanh(x): return T.clip(x, -1., 1.) def centered_softplus(x): return T.nnet.softplus(x) - np.cast[th.config.floatX](np.log(2.)) def log_sum_exp(x, axis=1): m = T.max(x, axis=axis, keepdims=True) return m+T.log(T.sum(T.exp(x-m), axis=axis) + 1e-9) def adam_updates(params, cost, lr=0.001, mom1=0.9, mom2=0.999): updates = [] grads = T.grad(cost, params) t = th.shared(np.cast[th.config.floatX](1.)) for p, g in zip(params, grads): v = th.shared(np.cast[th.config.floatX](p.get_value() * 0.)) mg = th.shared(np.cast[th.config.floatX](p.get_value() * 0.)) v_t = mom1*v + (1. - mom1)*g mg_t = mom2*mg + (1. - mom2)*T.square(g) v_hat = v_t / (1. - mom1 ** t) mg_hat = mg_t / (1. - mom2 ** t) g_t = v_hat / T.sqrt(mg_hat + 1e-8) p_t = p - lr * g_t updates.append((v, v_t)) updates.append((mg, mg_t)) updates.append((p, p_t)) updates.append((t, t+1)) return updates class WeightNormLayer(lasagne.layers.Layer): def __init__(self, incoming, b=lasagne.init.Constant(0.), g=lasagne.init.Constant(1.), W=lasagne.init.Normal(0.05), train_g=False, init_stdv=1., nonlinearity=relu, **kwargs): super(WeightNormLayer, self).__init__(incoming, **kwargs) self.nonlinearity = nonlinearity self.init_stdv = init_stdv k = self.input_shape[1] if b is not None: self.b = self.add_param(b, (k,), name="b", regularizable=False) if g is not None: self.g = self.add_param(g, (k,), name="g", regularizable=False, trainable=train_g) if len(self.input_shape)==4: self.axes_to_sum = (0,2,3) self.dimshuffle_args = ['x',0,'x','x'] else: self.axes_to_sum = 0 self.dimshuffle_args = ['x',0] # scale weights in layer below incoming.W_param = incoming.W #incoming.W_param.set_value(W.sample(incoming.W_param.get_value().shape)) if incoming.W_param.ndim==4: if isinstance(incoming, Deconv2DLayer): W_axes_to_sum = (0,2,3) W_dimshuffle_args = ['x',0,'x','x'] else: W_axes_to_sum = (1,2,3) W_dimshuffle_args = [0,'x','x','x'] else: W_axes_to_sum = 0 W_dimshuffle_args = ['x',0] if g is not None: incoming.W = incoming.W_param * (self.g/T.sqrt(1e-6 + T.sum(T.square(incoming.W_param),axis=W_axes_to_sum))).dimshuffle(*W_dimshuffle_args) else: incoming.W = incoming.W_param / T.sqrt(1e-6 + T.sum(T.square(incoming.W_param),axis=W_axes_to_sum,keepdims=True)) def get_output_for(self, input, init=False, **kwargs): if init: m = T.mean(input, self.axes_to_sum) input -= m.dimshuffle(*self.dimshuffle_args) inv_stdv = self.init_stdv/T.sqrt(T.mean(T.square(input), self.axes_to_sum)) input *= inv_stdv.dimshuffle(*self.dimshuffle_args) self.init_updates = [(self.b, -m*inv_stdv), (self.g, self.g*inv_stdv)] elif hasattr(self,'b'): input += self.b.dimshuffle(*self.dimshuffle_args) return self.nonlinearity(input) def weight_norm(layer, **kwargs): nonlinearity = getattr(layer, 'nonlinearity', None) if nonlinearity is not None: layer.nonlinearity = lasagne.nonlinearities.identity if hasattr(layer, 'b'): del layer.params[layer.b] layer.b = None return WeightNormLayer(layer, nonlinearity=nonlinearity, **kwargs) class Deconv2DLayer(lasagne.layers.Layer): def __init__(self, incoming, target_shape, filter_size, stride=(2, 2), pad='half', W=lasagne.init.Normal(0.05), b=lasagne.init.Constant(0.), nonlinearity=relu, **kwargs): super(Deconv2DLayer, self).__init__(incoming, **kwargs) self.target_shape = target_shape self.nonlinearity = (lasagne.nonlinearities.identity if nonlinearity is None else nonlinearity) self.filter_size = lasagne.layers.dnn.as_tuple(filter_size, 2) self.stride = lasagne.layers.dnn.as_tuple(stride, 2) self.pad = pad self.W_shape = (incoming.output_shape[1], target_shape[1], filter_size[0], filter_size[1]) self.W = self.add_param(W, self.W_shape, name="W") if b is not None: self.b = self.add_param(b, (target_shape[1],), name="b") else: self.b = None def get_output_for(self, input, **kwargs): op = T.nnet.abstract_conv.AbstractConv2d_gradInputs( imshp=self.target_shape, kshp=self.W_shape, subsample=self.stride, border_mode=self.pad) activation = op(self.W, input, self.target_shape[2:]) if self.b is not None: activation += self.b.dimshuffle('x', 0, 'x', 'x') return self.nonlinearity(activation) def get_output_shape_for(self, input_shape): return self.target_shape # minibatch discrimination layer class MinibatchLayer(lasagne.layers.Layer): def __init__(self, incoming, num_kernels, dim_per_kernel=5, theta=lasagne.init.Normal(0.05), log_weight_scale=lasagne.init.Constant(0.), b=lasagne.init.Constant(-1.), **kwargs): super(MinibatchLayer, self).__init__(incoming, **kwargs) self.num_kernels = num_kernels num_inputs = int(np.prod(self.input_shape[1:])) self.theta = self.add_param(theta, (num_inputs, num_kernels, dim_per_kernel), name="theta") self.log_weight_scale = self.add_param(log_weight_scale, (num_kernels, dim_per_kernel), name="log_weight_scale") self.W = self.theta * (T.exp(self.log_weight_scale)/T.sqrt(T.sum(T.square(self.theta),axis=0))).dimshuffle('x',0,1) self.b = self.add_param(b, (num_kernels,), name="b") def get_output_shape_for(self, input_shape): return (input_shape[0], np.prod(input_shape[1:])+self.num_kernels) def get_output_for(self, input, init=False, **kwargs): if input.ndim > 2: # if the input has more than two dimensions, flatten it into a # batch of feature vectors. input = input.flatten(2) activation = T.tensordot(input, self.W, [[1], [0]]) abs_dif = (T.sum(abs(activation.dimshuffle(0,1,2,'x') - activation.dimshuffle('x',1,2,0)),axis=2) + 1e6 * T.eye(input.shape[0]).dimshuffle(0,'x',1)) if init: mean_min_abs_dif = 0.5 * T.mean(T.min(abs_dif, axis=2),axis=0) abs_dif /= mean_min_abs_dif.dimshuffle('x',0,'x') self.init_updates = [(self.log_weight_scale, self.log_weight_scale-T.log(mean_min_abs_dif).dimshuffle(0,'x'))] f = T.sum(T.exp(-abs_dif),axis=2) if init: mf = T.mean(f,axis=0) f -= mf.dimshuffle('x',0) self.init_updates.append((self.b, -mf)) else: f += self.b.dimshuffle('x',0) return T.concatenate([input, f], axis=1) class BatchNormLayer(lasagne.layers.Layer): def __init__(self, incoming, b=lasagne.init.Constant(0.), g=lasagne.init.Constant(1.), nonlinearity=relu, **kwargs): super(BatchNormLayer, self).__init__(incoming, **kwargs) self.nonlinearity = nonlinearity k = self.input_shape[1] if b is not None: self.b = self.add_param(b, (k,), name="b", regularizable=False) if g is not None: self.g = self.add_param(g, (k,), name="g", regularizable=False) self.avg_batch_mean = self.add_param(lasagne.init.Constant(0.), (k,), name="avg_batch_mean", regularizable=False, trainable=False) self.avg_batch_var = self.add_param(lasagne.init.Constant(1.), (k,), name="avg_batch_var", regularizable=False, trainable=False) if len(self.input_shape)==4: self.axes_to_sum = (0,2,3) self.dimshuffle_args = ['x',0,'x','x'] else: self.axes_to_sum = 0 self.dimshuffle_args = ['x',0] def get_output_for(self, input, deterministic=False, set_bn_updates=True, **kwargs): if deterministic: norm_features = (input-self.avg_batch_mean.dimshuffle(*self.dimshuffle_args)) / T.sqrt(1e-6 + self.avg_batch_var).dimshuffle(*self.dimshuffle_args) else: batch_mean = T.mean(input,axis=self.axes_to_sum).flatten() centered_input = input-batch_mean.dimshuffle(*self.dimshuffle_args) batch_var = T.mean(T.square(centered_input),axis=self.axes_to_sum).flatten() batch_stdv = T.sqrt(1e-6 + batch_var) norm_features = centered_input / batch_stdv.dimshuffle(*self.dimshuffle_args) # BN updates if set_bn_updates: new_m = 0.9*self.avg_batch_mean + 0.1*batch_mean new_v = 0.9*self.avg_batch_var + T.cast((0.1*input.shape[0])/(input.shape[0]-1),th.config.floatX)*batch_var self.bn_updates = [(self.avg_batch_mean, new_m), (self.avg_batch_var, new_v)] if hasattr(self, 'g'): activation = norm_features*self.g.dimshuffle(*self.dimshuffle_args) else: activation = norm_features if hasattr(self, 'b'): activation += self.b.dimshuffle(*self.dimshuffle_args) return self.nonlinearity(activation) def batch_norm(layer, b=lasagne.init.Constant(0.), g=lasagne.init.Constant(1.), **kwargs): """ adapted from https://gist.github.com/f0k/f1a6bd3c8585c400c190 """ nonlinearity = getattr(layer, 'nonlinearity', None) if nonlinearity is not None: layer.nonlinearity = lasagne.nonlinearities.identity else: nonlinearity = lasagne.nonlinearities.identity if hasattr(layer, 'b'): del layer.params[layer.b] layer.b = None return BatchNormLayer(layer, b, g, nonlinearity=nonlinearity, **kwargs) class GaussianNoiseLayer(lasagne.layers.Layer): def __init__(self, incoming, sigma=0.1, **kwargs): super(GaussianNoiseLayer, self).__init__(incoming, **kwargs) self._srng = RandomStreams(lasagne.random.get_rng().randint(1, 2147462579)) self.sigma = sigma def get_output_for(self, input, deterministic=False, use_last_noise=False, **kwargs): if deterministic or self.sigma == 0: return input else: if not use_last_noise: self.noise = self._srng.normal(input.shape, avg=0.0, std=self.sigma) return input + self.noise # /////////// older code used for MNIST //////////// # weight normalization def l2normalize(layer, train_scale=True): W_param = layer.W s = W_param.get_value().shape if len(s)==4: axes_to_sum = (1,2,3) dimshuffle_args = [0,'x','x','x'] k = s[0] else: axes_to_sum = 0 dimshuffle_args = ['x',0] k = s[1] layer.W_scale = layer.add_param(lasagne.init.Constant(1.), (k,), name="W_scale", trainable=train_scale, regularizable=False) layer.W = W_param * (layer.W_scale/T.sqrt(1e-6 + T.sum(T.square(W_param),axis=axes_to_sum))).dimshuffle(*dimshuffle_args) return layer # fully connected layer with weight normalization class DenseLayer(lasagne.layers.Layer): def __init__(self, incoming, num_units, theta=lasagne.init.Normal(0.1), b=lasagne.init.Constant(0.), weight_scale=lasagne.init.Constant(1.), train_scale=False, nonlinearity=relu, **kwargs): super(DenseLayer, self).__init__(incoming, **kwargs) self.nonlinearity = (lasagne.nonlinearities.identity if nonlinearity is None else nonlinearity) self.num_units = num_units num_inputs = int(np.prod(self.input_shape[1:])) self.theta = self.add_param(theta, (num_inputs, num_units), name="theta") self.weight_scale = self.add_param(weight_scale, (num_units,), name="weight_scale", trainable=train_scale) self.W = self.theta * (self.weight_scale/T.sqrt(T.sum(T.square(self.theta),axis=0))).dimshuffle('x',0) self.b = self.add_param(b, (num_units,), name="b") def get_output_shape_for(self, input_shape): return (input_shape[0], self.num_units) def get_output_for(self, input, init=False, deterministic=False, **kwargs): if input.ndim > 2: # if the input has more than two dimensions, flatten it into a # batch of feature vectors. input = input.flatten(2) activation = T.dot(input, self.W) if init: ma = T.mean(activation, axis=0) activation -= ma.dimshuffle('x',0) stdv = T.sqrt(T.mean(T.square(activation),axis=0)) activation /= stdv.dimshuffle('x',0) self.init_updates = [(self.weight_scale, self.weight_scale/stdv), (self.b, -ma/stdv)] else: activation += self.b.dimshuffle('x', 0) return self.nonlinearity(activation) # comes from Ishamel code base def conv_layer(input_, filter_size, num_filters, stride, pad, nonlinearity=relu, W=Normal(0.02), **kwargs): return layers.conv.Conv2DDNNLayer(input_, num_filters=num_filters, stride=parse_tuple(stride), filter_size=parse_tuple(filter_size), pad=pad, W=W, nonlinearity=nonlinearity, **kwargs) class BilinearUpsampling(lasagne.layers.Layer): def __init__(self, input_, ratio, use_1D_kernel=True, **kwargs): super(BilinearUpsampling, self).__init__(input_, **kwargs) self.ratio = ratio self.use_1D_kernel = use_1D_kernel def get_output_shape_for(self, input_shape): dims = input_shape[2:] output_dims = tuple(c * self.ratio for c in dims) return input_shape[:2] + output_dims def get_output_for(self, input_, **kwargs): return bilinear_upsampling(input_, ratio=self.ratio, batch_size=self.input_shape[0], num_input_channels=self.input_shape[1], use_1D_kernel=self.use_1D_kernel) def resnet_block(input_, filter_size, num_filters, activation=relu, downsample=False, no_output_act=True, use_shortcut=False, use_wn=False, W_init=Normal(0.02), **kwargs): """ Resnet block layer. """ normalization = weight_norm if use_wn else batch_norm block = [] _stride = 2 if downsample else 1 # conv -> BN -> Relu block.append(normalization(conv_layer(input_, filter_size, num_filters, _stride, 'same', nonlinearity=activation, W=W_init ))) # Conv -> BN block.append(normalization(conv_layer(block[-1], filter_size, num_filters, 1, 'same', nonlinearity=None, W=W_init))) if downsample or use_shortcut: shortcut = conv_layer(input_, 1, num_filters, _stride, 'valid', nonlinearity=None) block.append(ElemwiseSumLayer([shortcut, block[-1]])) else: block.append(ElemwiseSumLayer([input_, block[-1]])) if not no_output_act: block.append(NonlinearityLayer(block[-1], nonlinearity=activation)) return block[-1]
mit
-6,252,026,180,454,746,000
41.94695
159
0.59601
false
3.259058
false
false
false
rodrigopolo/cheatsheets
upload_video.py
1
7001
#!/usr/bin/env python # Modified to always use the installation path to store and read the client_secrets.json and pyu-oauth2.json file import httplib import httplib2 import os import random import sys import time from apiclient.discovery import build from apiclient.errors import HttpError from apiclient.http import MediaFileUpload from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import argparser, run_flow # Explicitly tell the underlying HTTP transport library not to retry, since # we are handling retry logic ourselves. httplib2.RETRIES = 1 # Maximum number of times to retry before giving up. MAX_RETRIES = 10 # Always retry when these exceptions are raised. RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected, httplib.IncompleteRead, httplib.ImproperConnectionState, httplib.CannotSendRequest, httplib.CannotSendHeader, httplib.ResponseNotReady, httplib.BadStatusLine) # Always retry when an apiclient.errors.HttpError with one of these status # codes is raised. RETRIABLE_STATUS_CODES = [500, 502, 503, 504] # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. You can acquire an OAuth 2.0 client ID and client secret from # the {{ Google Cloud Console }} at # {{ https://cloud.google.com/console }}. # Please ensure that you have enabled the YouTube Data API for your project. # For more information about using OAuth2 to access the YouTube Data API, see: # https://developers.google.com/youtube/v3/guides/authentication # For more information about the client_secrets.json file format, see: # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets # CLIENT_SECRETS_FILE = "client_secrets.json" <-- removed CLIENT_SECRETS_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), "client_secrets.json") USER_KEYS = os.path.join(os.path.dirname(os.path.realpath(__file__)), "pyu-oauth2.json") # This OAuth 2.0 access scope allows an application to upload files to the # authenticated user's YouTube channel, but doesn't allow other types of access. YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" # This variable defines a message to display if the CLIENT_SECRETS_FILE is # missing. MISSING_CLIENT_SECRETS_MESSAGE = """ WARNING: Please configure OAuth 2.0 To make this sample run you will need to populate the client_secrets.json file found at: %s with information from the {{ Cloud Console }} {{ https://cloud.google.com/console }} For more information about the client_secrets.json file format, please visit: https://developers.google.com/api-client-library/python/guide/aaa_client_secrets """ % os.path.abspath(os.path.join(os.path.dirname(__file__), CLIENT_SECRETS_FILE)) VALID_PRIVACY_STATUSES = ("public", "private", "unlisted") def get_authenticated_service(args): flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_UPLOAD_SCOPE, message=MISSING_CLIENT_SECRETS_MESSAGE) storage = Storage(USER_KEYS) credentials = storage.get() if credentials is None or credentials.invalid: credentials = run_flow(flow, storage, args) return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http())) def initialize_upload(youtube, options): tags = None if options.keywords: tags = options.keywords.split(",") body=dict( snippet=dict( title=options.title, description=options.description, tags=tags, categoryId=options.category ), status=dict( privacyStatus=options.privacyStatus ) ) # Call the API's videos.insert method to create and upload the video. insert_request = youtube.videos().insert( part=",".join(body.keys()), body=body, # The chunksize parameter specifies the size of each chunk of data, in # bytes, that will be uploaded at a time. Set a higher value for # reliable connections as fewer chunks lead to faster uploads. Set a lower # value for better recovery on less reliable connections. # # Setting "chunksize" equal to -1 in the code below means that the entire # file will be uploaded in a single HTTP request. (If the upload fails, # it will still be retried where it left off.) This is usually a best # practice, but if you're using Python older than 2.6 or if you're # running on App Engine, you should set the chunksize to something like # 1024 * 1024 (1 megabyte). media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True) ) resumable_upload(insert_request) # This method implements an exponential backoff strategy to resume a # failed upload. def resumable_upload(insert_request): response = None error = None retry = 0 while response is None: try: print "Uploading file..." status, response = insert_request.next_chunk() if response is not None: if 'id' in response: print "Video id '%s' was successfully uploaded." % response['id'] else: exit("The upload failed with an unexpected response: %s" % response) except HttpError, e: if e.resp.status in RETRIABLE_STATUS_CODES: error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status, e.content) else: raise except RETRIABLE_EXCEPTIONS, e: error = "A retriable error occurred: %s" % e if error is not None: print error retry += 1 if retry > MAX_RETRIES: exit("No longer attempting to retry.") max_sleep = 2 ** retry sleep_seconds = random.random() * max_sleep print "Sleeping %f seconds and then retrying..." % sleep_seconds time.sleep(sleep_seconds) if __name__ == '__main__': argparser.add_argument("--file", required=True, help="Video file to upload") argparser.add_argument("--title", help="Video title", default="Test Title") argparser.add_argument("--description", help="Video description", default="Test Description") argparser.add_argument("--category", default="22", help="Numeric video category. " + "See https://developers.google.com/youtube/v3/docs/videoCategories/list") argparser.add_argument("--keywords", help="Video keywords, comma separated", default="") argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES, default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.") args = argparser.parse_args() if not os.path.exists(args.file): exit("Please specify a valid file using the --file= parameter.") youtube = get_authenticated_service(args) try: initialize_upload(youtube, args) except HttpError, e: print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
mit
-5,672,397,897,091,849,000
37.048913
113
0.713755
false
3.825683
false
false
false
WSULib/combine
tests/test_models/test_validation_scenario.py
1
2903
from django.test import TestCase from core.models import ValidationScenario from tests.utils import TestConfiguration SCHEMATRON_PAYLOAD = '''<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://purl.oclc.org/dsdl/schematron" xmlns:internet="http://internet.com"> <ns prefix="internet" uri="http://internet.com"/> <!-- Required top level Elements for all records record --> <pattern> <title>Required Elements for Each MODS record</title> <rule context="root"> <assert test="titleInfo">There must be a title element</assert> </rule> </pattern> </schema>''' class ValidationScenarioTestCase(TestCase): @classmethod def setUpTestData(cls): cls.schematron_attributes = { 'name': 'Test Schematron Validation', 'payload': SCHEMATRON_PAYLOAD, 'validation_type': 'sch', 'default_run': False } cls.schematron_validation_scenario = ValidationScenario(**cls.schematron_attributes) cls.schematron_validation_scenario.save() cls.config = TestConfiguration() def test_str(self): self.assertEqual('ValidationScenario: Test Schematron Validation, validation type: sch, default run: False', format(ValidationScenarioTestCase.schematron_validation_scenario)) def test_as_dict(self): as_dict = ValidationScenarioTestCase.schematron_validation_scenario.as_dict() for k, v in ValidationScenarioTestCase.schematron_attributes.items(): self.assertEqual(as_dict[k], v) def test_validate_record_schematron(self): record = ValidationScenarioTestCase.config.record validation = ValidationScenarioTestCase.schematron_validation_scenario.validate_record(record) parsed = validation['parsed'] self.assertEqual(parsed['passed'], []) self.assertEqual(parsed['fail_count'], 1) self.assertEqual(parsed['failed'], ['There must be a title element']) def test_validate_record_python(self): python_validation = '''from lxml import etree def test_has_foo(row, test_message="There must be a foo"): doc_xml = etree.fromstring(row.document.encode('utf-8')) foo_elem_query = doc_xml.xpath('foo', namespaces=row.nsmap) return len(foo_elem_query) > 0 ''' python_validation_scenario = ValidationScenario( name='Test Python Validation', payload=python_validation, validation_type='python' ) validation = python_validation_scenario.validate_record(ValidationScenarioTestCase.config.record) parsed = validation['parsed'] self.assertEqual(parsed['fail_count'], 0) self.assertEqual(parsed['passed'], ['There must be a foo']) def test_validate_record_es_query(self): # TODO: write a test :| pass def test_validate_record_xsd(self): # TODO: write a test :| pass
mit
-102,594,079,670,103,680
40.471429
116
0.672408
false
3.917679
true
false
false
foreni-packages/hachoir-parser
setup.py
1
2770
#!/usr/bin/env python from imp import load_source from os import path from sys import argv # Procedure to release a new version: # - edit hachoir_parser/version.py: __version__ = "XXX" # - edit setup.py: install_options["install_requires"] = "hachoir-core>=XXX" # - edit INSTALL: update Dependencies # - run: ./tests/run_testcase.py ~/testcase # - edit ChangeLog (set release date) # - run: hg commit # - run: hg tag hachoir-parser-XXX # - run: hg push # - run: ./README.py # - run: python2.5 ./setup.py --setuptools register sdist bdist_egg upload # - run: python2.4 ./setup.py --setuptools bdist_egg upload # - run: python2.6 ./setup.py --setuptools bdist_egg upload # - run: rm README # - check http://pypi.python.org/pypi/hachoir-parser # - update the website # * http://bitbucket.org/haypo/hachoir/wiki/Install/source # * http://bitbucket.org/haypo/hachoir/wiki/Home # - edit hachoir_parser/version.py: set version to N+1 # - edit ChangeLog: add a new "hachoir-parser N+1" section with text XXX CLASSIFIERS = [ 'Intended Audience :: Developers', 'Development Status :: 5 - Production/Stable', 'Environment :: Console :: Curses', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: OS Independent', 'Natural Language :: English', 'Programming Language :: Python'] MODULES = ( "archive", "audio", "container", "common", "file_system", "game", "image", "misc", "network", "program", "video") def main(): if "--setuptools" in argv: argv.remove("--setuptools") from setuptools import setup use_setuptools = True else: from distutils.core import setup use_setuptools = False hachoir_parser = load_source("version", path.join("hachoir_parser", "version.py")) PACKAGES = {"hachoir_parser": "hachoir_parser"} for name in MODULES: PACKAGES["hachoir_parser." + name] = "hachoir_parser/" + name readme = open('README') long_description = readme.read() readme.close() install_options = { "name": hachoir_parser.PACKAGE, "version": hachoir_parser.__version__, "url": hachoir_parser.WEBSITE, "download_url": hachoir_parser.WEBSITE, "author": "Hachoir team (see AUTHORS file)", "description": "Package of Hachoir parsers used to open binary files", "long_description": long_description, "classifiers": CLASSIFIERS, "license": hachoir_parser.LICENSE, "packages": PACKAGES.keys(), "package_dir": PACKAGES, } if use_setuptools: install_options["install_requires"] = "hachoir-core>=1.3" install_options["zip_safe"] = True setup(**install_options) if __name__ == "__main__": main()
gpl-2.0
-9,108,310,611,562,844,000
34.512821
86
0.641516
false
3.488665
false
false
false
django-leonardo/django-leonardo
leonardo/conf/default.py
1
3507
from leonardo.base import default EMAIL = { 'HOST': 'mail.domain.com', 'PORT': '25', 'USER': 'username', 'PASSWORD': 'pwd', 'SECURITY': True, } RAVEN_CONFIG = {} ALLOWED_HOSTS = ['*'] USE_TZ = True DEBUG = True ADMINS = ( ('admin', 'mail@leonardo.cz'), ) # month LEONARDO_CACHE_TIMEOUT = 60 * 60 * 24 * 31 DEFAULT_CHARSET = 'utf-8' MANAGERS = ADMINS SITE_ID = 1 SITE_NAME = 'Leonardo' TIME_ZONE = 'Europe/Prague' LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', 'EN'), ('cs', 'CS'), ) USE_I18N = True DBTEMPLATES_MEDIA_PREFIX = '/static-/' DBTEMPLATES_AUTO_POPULATE_CONTENT = True DBTEMPLATES_ADD_DEFAULT_SITE = True FILER_ENABLE_PERMISSIONS = True # noqa MIDDLEWARE_CLASSES = default.middlewares ROOT_URLCONF = 'leonardo.urls' LEONARDO_BOOTSTRAP_URL = 'http://github.com/django-leonardo/django-leonardo/raw/master/contrib/bootstrap/demo.yaml' MARKITUP_FILTER = ('markitup.renderers.render_rest', {'safe_mode': True}) INSTALLED_APPS = default.apps # For easy_thumbnails to support retina displays (recent MacBooks, iOS) THUMBNAIL_FORMAT = "PNG" FEINCMS_USE_PAGE_ADMIN = False LEONARDO_USE_PAGE_ADMIN = True FEINCMS_DEFAULT_PAGE_MODEL = 'web.Page' CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_CONFIG = {} CONSTANCE_ADDITIONAL_FIELDS = {} SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' # enable auto loading packages LEONARDO_MODULE_AUTO_INCLUDE = True # enable system module LEONARDO_SYSTEM_MODULE = True ########################## STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", 'compressor.finders.CompressorFinder', ) LOGIN_URL = '/auth/login/' LOGIN_REDIRECT_URL = '/' LOGOUT_URL = "/" LOGOUT_ON_GET = True AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': 'DEBUG', 'handlers': ['console'], }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, }, 'loggers': { 'django.request': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, 'leonardo': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, } } CRISPY_TEMPLATE_PACK = 'bootstrap3' SECRET_KEY = None APPS = [] PAGE_EXTENSIONS = [] MIGRATION_MODULES = {} # use default leonardo auth urls LEONARDO_AUTH = True FEINCMS_TIDY_HTML = False APPLICATION_CHOICES = [] ADD_JS_FILES = [] ADD_CSS_FILES = [] ADD_SCSS_FILES = [] ADD_JS_SPEC_FILES = [] ADD_ANGULAR_MODULES = [] ADD_PAGE_ACTIONS = [] ADD_WIDGET_ACTIONS = [] ADD_MIGRATION_MODULES = {} ADD_JS_COMPRESS_FILES = [] CONSTANCE_CONFIG_GROUPS = {} ABSOLUTE_URL_OVERRIDES = {} SELECT2_CACHE_PREFIX = 'SELECT2' MODULE_URLS = {} WIDGETS = {} LEONARDO_INSTALL_DEPENDENCIES = True
bsd-3-clause
-4,509,059,239,852,881,400
16.892857
115
0.60365
false
3.031115
false
false
false
sunfounder/SunFounder_SensorKit_for_RPi2
Python/08_vibration_switch.py
1
1101
#!/usr/bin/env python3 import RPi.GPIO as GPIO import time VibratePin = 11 Gpin = 13 Rpin = 12 tmp = 0 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output GPIO.setup(VibratePin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V) def Led(x): if x == 0: GPIO.output(Rpin, 1) GPIO.output(Gpin, 0) if x == 1: GPIO.output(Rpin, 0) GPIO.output(Gpin, 1) def loop(): state = 0 while True: if GPIO.input(VibratePin)==0: state = state + 1 if state > 1: state = 0 Led(state) time.sleep(1) def destroy(): GPIO.output(Gpin, GPIO.HIGH) # Green led off GPIO.output(Rpin, GPIO.HIGH) # Red led off GPIO.cleanup() # Release resource if __name__ == '__main__': # Program start from here setup() try: loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. destroy()
gpl-2.0
1,834,895,438,698,754,000
22.934783
123
0.633061
false
2.718519
false
false
false
brigittebigi/proceed
proceed/src/wxgui/cutils/viewsutils.py
1
4360
#!/usr/bin/env python2 # -*- coding: UTF-8 -*- # --------------------------------------------------------------------------- # ___ __ __ __ ___ # / | \ | \ | \ / Automatic # \__ |__/ |__/ |___| \__ Annotation # \ | | | | \ of # ___/ | | | | ___/ Speech # ============================= # # http://sldr.org/sldr000800/preview/ # # --------------------------------------------------------------------------- # developed at: # # Laboratoire Parole et Langage # # Copyright (C) 2011-2018 Brigitte Bigi # # Use of this software is governed by the GPL, v3 # This banner notice must not be removed # --------------------------------------------------------------------------- # # SPPAS 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. # # SPPAS 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 SPPAS. If not, see <http://www.gnu.org/licenses/>. # # ---------------------------------------------------------------------------- # File: viewsutils.py # ---------------------------------------------------------------------------- __docformat__ = """epytext""" __authors__ = """Brigitte Bigi""" __copyright__ = """Copyright (C) 2011-2015 Brigitte Bigi""" # ---------------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------------- import wx from wxgui.sp_consts import FRAME_TITLE from wxgui.sp_consts import HEADER_FONTSIZE from wxgui.sp_icons import APP_ICON from wxgui.cutils.imageutils import spBitmap # ---------------------------------------------------------------------------- class spFrame( wx.Frame ): """ Simple Frame. """ def __init__(self, parent, title, preferences, btype=None, size=(640,480)): """ Create a new sppasFrame. """ # Create the frame and set properties wx.Frame.__init__(self, parent, -1, FRAME_TITLE, size=size) _icon = wx.EmptyIcon() _icon.CopyFromBitmap( spBitmap(APP_ICON) ) self.SetIcon(_icon) # Create the main panel and the main sizer self.panel = wx.Panel(self) self.sizer = wx.BoxSizer(wx.VERTICAL) # Create the SPPAS specific header at the top of the panel spHeaderPanel(btype, title, parent.preferences).Draw(self.panel, self.sizer) self.panel.SetSizer(self.sizer) self.Centre() # ---------------------------------------------------------------------------- class spHeaderPanel(): """ Create a panel with a specific header containing a bitmap and a 'nice' colored title. """ def __init__(self, bmptype, label, preferences): if preferences: self.bmp = spBitmap(bmptype, 32, theme=preferences.get_theme()) else: self.bmp = spBitmap(bmptype, 32, theme=None) self.label = label self.preferences = preferences def Draw(self, panel, sizer): titlesizer = wx.BoxSizer(wx.HORIZONTAL) icon = wx.StaticBitmap(panel, bitmap=self.bmp) titlesizer.Add(icon, flag=wx.TOP|wx.RIGHT|wx.ALIGN_RIGHT, border=5) text1 = wx.StaticText(panel, label=self.label) text1.SetFont( wx.Font(HEADER_FONTSIZE, wx.SWISS, wx.NORMAL, wx.BOLD) ) if self.preferences: text1.SetForegroundColour(self.preferences.GetValue('M_FG_COLOUR')) titlesizer.Add(text1, flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=5) sizer.Add(titlesizer, 0, flag=wx.EXPAND, border=5) line1 = wx.StaticLine(panel) sizer.Add(line1, flag=wx.EXPAND|wx.BOTTOM, border=10) # ----------------------------------------------------------------------------
gpl-3.0
-7,760,454,296,008,524,000
34.638655
84
0.481422
false
4.01104
false
false
false
stormi/tsunami
src/primaires/scripting/actions/ecrire_memoire.py
1
3274
# -*-coding:Utf-8 -* # Copyright (c) 2010 LE GOFF Vincent # 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 holder 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 teleporterCT, INteleporterCT, 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. """Fichier contenant l'action ecrire_memoire.""" from primaires.scripting.action import Action class ClasseAction(Action): """Ecrit dans la mémoire du scripting. Une mémoire peut être spécifiée pour une salle, un personnage (joueur ou PNJ) ou un objet. La valeur de la mémoire peut être de n'importe quel type, sa clé doit être une chaîne. """ @classmethod def init_types(cls): cls.ajouter_types(cls.ecrire_salle, "Salle", "str", "object") cls.ajouter_types(cls.ecrire_perso, "Personnage", "str", "object") cls.ajouter_types(cls.ecrire_objet, "Objet", "str", "object") @staticmethod def ecrire_salle(salle, cle, valeur): """Ecrit une mémoire de salle.""" if salle in importeur.scripting.memoires: importeur.scripting.memoires[salle][cle] = valeur else: importeur.scripting.memoires[salle] = {cle: valeur} @staticmethod def ecrire_perso(personnage, cle, valeur): """Ecrit une mémoire de personnage (joueur ou PNJ).""" personnage = hasattr(personnage, "prototype") and \ personnage.prototype or personnage if personnage in importeur.scripting.memoires: importeur.scripting.memoires[personnage][cle] = valeur else: importeur.scripting.memoires[personnage] = {cle: valeur} @staticmethod def ecrire_objet(objet, cle, valeur): """Ecrit une mémoire d'objet.""" if objet in importeur.scripting.memoires: importeur.scripting.memoires[objet][cle] = valeur else: importeur.scripting.memoires[objet] = {cle: valeur}
bsd-3-clause
-2,439,123,936,880,081,000
43.067568
81
0.707145
false
3.514009
false
false
false
PEAT-AI/Crampy
distance_analysis.py
1
1722
#!/usr/bin/env python # -*- coding: utf-8 -*- # # distance_analysis.py # # Copyright 2015 linaro <linaro@raspberry> # # 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. # # '''imported modules''' from multiprocessing import Process from random import randint import time from random import choice '''own modules''' from dist_sensors import sensors as sens from inverse_kinematics import move_a_bit '''globals''' minn = 30 maxx = 180 medium = 100 choice_list = [minn,maxx,medium] crampys_range = range(50,150,50) #u = Process(target=sens.permap, args=()) #u.start() while True: move_a_bit.arm(choice(choice_list) + 60,choice(choice_list),choice(choice_list),choice(choice_list),choice(choice_list) -30,choice(choice_list)) time.sleep(0.8) count = minn #joints = [a, while True: if count <= maxx: for i in crampys_range: print "angle =", i move_a_bit.arm(i,i,i,i,i,i) time.sleep(0.5) count = i else: while count >= 50: move_a_bit.arm(count,count,count,count,count,count) time.sleep(0.5) count -= 10
gpl-3.0
-3,940,220,425,778,474,500
25.090909
145
0.706736
false
3.069519
false
false
false
MobileCloudNetworking/dssaas
dss-side-scripts/icn_repo_push.py
1
2702
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Mohammad Valipoor" __copyright__ = "Copyright 2014, SoftTelecom" import logging import time from subprocess import call import os def config_logger(log_level=logging.DEBUG): logging.basicConfig(format='%(levelname)s %(asctime)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', log_level=log_level) logger = logging.getLogger(__name__) logger.setLevel(log_level) hdlr = logging.FileHandler('icn_repo_push_log.txt') formatter = logging.Formatter(fmt='%(levelname)s %(asctime)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') hdlr.setFormatter(formatter) logger.addHandler(hdlr) return logger LOG = config_logger() class IcnContentManager: def generate_contentlist(self, repo_path): contentlist = [] for file in os.listdir(repo_path): if file.endswith(".webm"): contentlist.append(file) return contentlist def insert_file_to_icn(self, filename, prefix, repo_path): ret_code = -1 if filename != "" and prefix != "": LOG.debug("Running command: " + '/home/ubuntu/ccnx-0.8.2/bin/ccnputfile ' + 'ccnx:' + prefix + '/' + filename + ' ' + repo_path + '/' + filename) #ret_code = call(['/home/centos/ccnx-0.8.2/bin/ccnputfile', 'ccnx:' + prefix + '/' + filename, repo_path + '/' + filename]) ret_code = os.system('/home/ubuntu/ccnx-0.8.2/bin/ccnputfile ccnx:' + prefix + '/' + filename + ' ' + repo_path + '/' + filename) #ret_code = 0 return ret_code if __name__ == "__main__": repo_path = './files' LOG.debug("URL to poll set to: " + repo_path) icn_prefix = '/dss' LOG.debug("ICN prefix set to: " + icn_prefix) cntManager = IcnContentManager() oldCntList =[] while 1: cntList = cntManager.generate_contentlist(repo_path) print str(cntList) if cntList != oldCntList: i = 0 while i < len(cntList): if cntList[i] not in oldCntList: LOG.debug("Inserting file " + cntList[i]) ret_code = cntManager.insert_file_to_icn(cntList[i], icn_prefix, repo_path) if ret_code == 0: i += 1 else: LOG.debug("File " + cntList[i] + " has been already inserted.") i += 1 LOG.debug("Contentlist process complete. Next insertion in 30 seconds ...") oldCntList = cntList else: LOG.debug("No change in content list detected. Next insertion in 30 seconds ...") time.sleep(30)
apache-2.0
6,706,557,584,521,625,000
35.527027
157
0.559585
false
3.545932
false
false
false
chirpradio/chirpradio-volunteers
site-packages/sqlalchemy/orm/attributes.py
1
46309
# attributes.py - manages object attributes # Copyright (C) 2005, 2006, 2007, 2008 Michael Bayer mike_mp@zzzcomputing.com # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import operator, weakref from itertools import chain import UserDict from sqlalchemy import util from sqlalchemy.orm import interfaces, collections from sqlalchemy.orm.util import identity_equal from sqlalchemy import exceptions PASSIVE_NORESULT = util.symbol('PASSIVE_NORESULT') ATTR_WAS_SET = util.symbol('ATTR_WAS_SET') NO_VALUE = util.symbol('NO_VALUE') NEVER_SET = util.symbol('NEVER_SET') class InstrumentedAttribute(interfaces.PropComparator): """public-facing instrumented attribute, placed in the class dictionary. """ def __init__(self, impl, comparator=None): """Construct an InstrumentedAttribute. comparator a sql.Comparator to which class-level compare/math events will be sent """ self.impl = impl self.comparator = comparator def __set__(self, instance, value): self.impl.set(instance._state, value, None) def __delete__(self, instance): self.impl.delete(instance._state) def __get__(self, instance, owner): if instance is None: return self return self.impl.get(instance._state) def get_history(self, instance, **kwargs): return self.impl.get_history(instance._state, **kwargs) def clause_element(self): return self.comparator.clause_element() def expression_element(self): return self.comparator.expression_element() def label(self, name): return self.clause_element().label(name) def operate(self, op, *other, **kwargs): return op(self.comparator, *other, **kwargs) def reverse_operate(self, op, other, **kwargs): return op(other, self.comparator, **kwargs) def hasparent(self, instance, optimistic=False): return self.impl.hasparent(instance._state, optimistic=optimistic) def _property(self): from sqlalchemy.orm.mapper import class_mapper return class_mapper(self.impl.class_).get_property(self.impl.key) property = property(_property, doc="the MapperProperty object associated with this attribute") class ProxiedAttribute(InstrumentedAttribute): """Adds InstrumentedAttribute class-level behavior to a regular descriptor. Obsoleted by proxied_attribute_factory. """ class ProxyImpl(object): accepts_scalar_loader = False def __init__(self, key): self.key = key def __init__(self, key, user_prop, comparator=None): self.user_prop = user_prop self._comparator = comparator self.key = key self.impl = ProxiedAttribute.ProxyImpl(key) def comparator(self): if callable(self._comparator): self._comparator = self._comparator() return self._comparator comparator = property(comparator) def __get__(self, instance, owner): if instance is None: self.user_prop.__get__(instance, owner) return self return self.user_prop.__get__(instance, owner) def __set__(self, instance, value): return self.user_prop.__set__(instance, value) def __delete__(self, instance): return self.user_prop.__delete__(instance) def proxied_attribute_factory(descriptor): """Create an InstrumentedAttribute / user descriptor hybrid. Returns a new InstrumentedAttribute type that delegates descriptor behavior and getattr() to the given descriptor. """ class ProxyImpl(object): accepts_scalar_loader = False def __init__(self, key): self.key = key class Proxy(InstrumentedAttribute): """A combination of InsturmentedAttribute and a regular descriptor.""" def __init__(self, key, descriptor, comparator): self.key = key # maintain ProxiedAttribute.user_prop compatability. self.descriptor = self.user_prop = descriptor self._comparator = comparator self.impl = ProxyImpl(key) def comparator(self): if callable(self._comparator): self._comparator = self._comparator() return self._comparator comparator = property(comparator) def __get__(self, instance, owner): """Delegate __get__ to the original descriptor.""" if instance is None: descriptor.__get__(instance, owner) return self return descriptor.__get__(instance, owner) def __set__(self, instance, value): """Delegate __set__ to the original descriptor.""" return descriptor.__set__(instance, value) def __delete__(self, instance): """Delegate __delete__ to the original descriptor.""" return descriptor.__delete__(instance) def __getattr__(self, attribute): """Delegate __getattr__ to the original descriptor.""" return getattr(descriptor, attribute) Proxy.__name__ = type(descriptor).__name__ + 'Proxy' util.monkeypatch_proxied_specials(Proxy, type(descriptor), name='descriptor', from_instance=descriptor) return Proxy class AttributeImpl(object): """internal implementation for instrumented attributes.""" def __init__(self, class_, key, callable_, trackparent=False, extension=None, compare_function=None, **kwargs): """Construct an AttributeImpl. class_ the class to be instrumented. key string name of the attribute callable_ optional function which generates a callable based on a parent instance, which produces the "default" values for a scalar or collection attribute when it's first accessed, if not present already. trackparent if True, attempt to track if an instance has a parent attached to it via this attribute. extension an AttributeExtension object which will receive set/delete/append/remove/etc. events. compare_function a function that compares two values which are normally assignable to this attribute. """ self.class_ = class_ self.key = key self.callable_ = callable_ self.trackparent = trackparent if compare_function is None: self.is_equal = operator.eq else: self.is_equal = compare_function self.extensions = util.to_list(extension or []) def hasparent(self, state, optimistic=False): """Return the boolean value of a `hasparent` flag attached to the given item. The `optimistic` flag determines what the default return value should be if no `hasparent` flag can be located. As this function is used to determine if an instance is an *orphan*, instances that were loaded from storage should be assumed to not be orphans, until a True/False value for this flag is set. An instance attribute that is loaded by a callable function will also not have a `hasparent` flag. """ return state.parents.get(id(self), optimistic) def sethasparent(self, state, value): """Set a boolean flag on the given item corresponding to whether or not it is attached to a parent object via the attribute represented by this ``InstrumentedAttribute``. """ state.parents[id(self)] = value def set_callable(self, state, callable_): """Set a callable function for this attribute on the given object. This callable will be executed when the attribute is next accessed, and is assumed to construct part of the instances previously stored state. When its value or values are loaded, they will be established as part of the instance's *committed state*. While *trackparent* information will be assembled for these instances, attribute-level event handlers will not be fired. The callable overrides the class level callable set in the ``InstrumentedAttribute` constructor. """ if callable_ is None: self.initialize(state) else: state.callables[self.key] = callable_ def get_history(self, state, passive=False): raise NotImplementedError() def _get_callable(self, state): if self.key in state.callables: return state.callables[self.key] elif self.callable_ is not None: return self.callable_(state.obj()) else: return None def initialize(self, state): """Initialize this attribute on the given object instance with an empty value.""" state.dict[self.key] = None return None def get(self, state, passive=False): """Retrieve a value from the given object. If a callable is assembled on this object's attribute, and passive is False, the callable will be executed and the resulting value will be set as the new value for this attribute. """ try: return state.dict[self.key] except KeyError: # if no history, check for lazy callables, etc. if self.key not in state.committed_state: callable_ = self._get_callable(state) if callable_ is not None: if passive: return PASSIVE_NORESULT value = callable_() if value is not ATTR_WAS_SET: return self.set_committed_value(state, value) else: if self.key not in state.dict: return self.get(state, passive=passive) return state.dict[self.key] # Return a new, empty value return self.initialize(state) def append(self, state, value, initiator, passive=False): self.set(state, value, initiator) def remove(self, state, value, initiator, passive=False): self.set(state, None, initiator) def set(self, state, value, initiator): raise NotImplementedError() def get_committed_value(self, state): """return the unchanged value of this attribute""" if self.key in state.committed_state: if state.committed_state[self.key] is NO_VALUE: return None else: return state.committed_state.get(self.key) else: return self.get(state) def set_committed_value(self, state, value): """set an attribute value on the given instance and 'commit' it.""" state.commit_attr(self, value) return value class ScalarAttributeImpl(AttributeImpl): """represents a scalar value-holding InstrumentedAttribute.""" accepts_scalar_loader = True def delete(self, state): if self.key not in state.committed_state: state.committed_state[self.key] = state.dict.get(self.key, NO_VALUE) # TODO: catch key errors, convert to attributeerror? del state.dict[self.key] state.modified=True def get_history(self, state, passive=False): return _create_history(self, state, state.dict.get(self.key, NO_VALUE)) def set(self, state, value, initiator): if initiator is self: return if self.key not in state.committed_state: state.committed_state[self.key] = state.dict.get(self.key, NO_VALUE) state.dict[self.key] = value state.modified=True def type(self): self.property.columns[0].type type = property(type) class MutableScalarAttributeImpl(ScalarAttributeImpl): """represents a scalar value-holding InstrumentedAttribute, which can detect changes within the value itself. """ def __init__(self, class_, key, callable_, copy_function=None, compare_function=None, **kwargs): super(ScalarAttributeImpl, self).__init__(class_, key, callable_, compare_function=compare_function, **kwargs) class_._class_state.has_mutable_scalars = True if copy_function is None: raise exceptions.ArgumentError("MutableScalarAttributeImpl requires a copy function") self.copy = copy_function def get_history(self, state, passive=False): return _create_history(self, state, state.dict.get(self.key, NO_VALUE)) def commit_to_state(self, state, value): state.committed_state[self.key] = self.copy(value) def check_mutable_modified(self, state): (added, unchanged, deleted) = self.get_history(state, passive=True) if added or deleted: state.modified = True return True else: return False def set(self, state, value, initiator): if initiator is self: return if self.key not in state.committed_state: if self.key in state.dict: state.committed_state[self.key] = self.copy(state.dict[self.key]) else: state.committed_state[self.key] = NO_VALUE state.dict[self.key] = value state.modified=True class ScalarObjectAttributeImpl(ScalarAttributeImpl): """represents a scalar-holding InstrumentedAttribute, where the target object is also instrumented. Adds events to delete/set operations. """ accepts_scalar_loader = False def __init__(self, class_, key, callable_, trackparent=False, extension=None, copy_function=None, compare_function=None, **kwargs): super(ScalarObjectAttributeImpl, self).__init__(class_, key, callable_, trackparent=trackparent, extension=extension, compare_function=compare_function, **kwargs) if compare_function is None: self.is_equal = identity_equal def delete(self, state): old = self.get(state) # TODO: catch key errors, convert to attributeerror? del state.dict[self.key] self.fire_remove_event(state, old, self) def get_history(self, state, passive=False): if self.key in state.dict: return _create_history(self, state, state.dict[self.key]) else: current = self.get(state, passive=passive) if current is PASSIVE_NORESULT: return (None, None, None) else: return _create_history(self, state, current) def set(self, state, value, initiator): """Set a value on the given InstanceState. `initiator` is the ``InstrumentedAttribute`` that initiated the ``set()` operation and is used to control the depth of a circular setter operation. """ if initiator is self: return if value is not None and not hasattr(value, '_state'): raise TypeError("Can not assign %s instance to %s's %r attribute, " "a mapped instance was expected." % ( type(value).__name__, type(state.obj()).__name__, self.key)) # TODO: add options to allow the get() to be passive old = self.get(state) state.dict[self.key] = value self.fire_replace_event(state, value, old, initiator) def fire_remove_event(self, state, value, initiator): if self.key not in state.committed_state: state.committed_state[self.key] = value state.modified = True if self.trackparent and value is not None: self.sethasparent(value._state, False) instance = state.obj() for ext in self.extensions: ext.remove(instance, value, initiator or self) def fire_replace_event(self, state, value, previous, initiator): if self.key not in state.committed_state: state.committed_state[self.key] = previous state.modified = True if self.trackparent: if value is not None: self.sethasparent(value._state, True) if previous is not value and previous is not None: self.sethasparent(previous._state, False) instance = state.obj() for ext in self.extensions: ext.set(instance, value, previous, initiator or self) class CollectionAttributeImpl(AttributeImpl): """A collection-holding attribute that instruments changes in membership. Only handles collections of instrumented objects. InstrumentedCollectionAttribute holds an arbitrary, user-specified container object (defaulting to a list) and brokers access to the CollectionAdapter, a "view" onto that object that presents consistent bag semantics to the orm layer independent of the user data implementation. """ accepts_scalar_loader = False def __init__(self, class_, key, callable_, typecallable=None, trackparent=False, extension=None, copy_function=None, compare_function=None, **kwargs): super(CollectionAttributeImpl, self).__init__(class_, key, callable_, trackparent=trackparent, extension=extension, compare_function=compare_function, **kwargs) if copy_function is None: copy_function = self.__copy self.copy = copy_function if typecallable is None: typecallable = list self.collection_factory = \ collections._prepare_instrumentation(typecallable) # may be removed in 0.5: self.collection_interface = \ util.duck_type_collection(self.collection_factory()) def __copy(self, item): return [y for y in list(collections.collection_adapter(item))] def get_history(self, state, passive=False): current = self.get(state, passive=passive) if current is PASSIVE_NORESULT: return (None, None, None) else: return _create_history(self, state, current) def fire_append_event(self, state, value, initiator): if self.key not in state.committed_state and self.key in state.dict: state.committed_state[self.key] = self.copy(state.dict[self.key]) state.modified = True if self.trackparent and value is not None: self.sethasparent(value._state, True) instance = state.obj() for ext in self.extensions: ext.append(instance, value, initiator or self) def fire_pre_remove_event(self, state, initiator): if self.key not in state.committed_state and self.key in state.dict: state.committed_state[self.key] = self.copy(state.dict[self.key]) def fire_remove_event(self, state, value, initiator): if self.key not in state.committed_state and self.key in state.dict: state.committed_state[self.key] = self.copy(state.dict[self.key]) state.modified = True if self.trackparent and value is not None: self.sethasparent(value._state, False) instance = state.obj() for ext in self.extensions: ext.remove(instance, value, initiator or self) def delete(self, state): if self.key not in state.dict: return state.modified = True collection = self.get_collection(state) collection.clear_with_event() # TODO: catch key errors, convert to attributeerror? del state.dict[self.key] def initialize(self, state): """Initialize this attribute on the given object instance with an empty collection.""" _, user_data = self._build_collection(state) state.dict[self.key] = user_data return user_data def append(self, state, value, initiator, passive=False): if initiator is self: return collection = self.get_collection(state, passive=passive) if collection is PASSIVE_NORESULT: state.get_pending(self.key).append(value) self.fire_append_event(state, value, initiator) else: collection.append_with_event(value, initiator) def remove(self, state, value, initiator, passive=False): if initiator is self: return collection = self.get_collection(state, passive=passive) if collection is PASSIVE_NORESULT: state.get_pending(self.key).remove(value) self.fire_remove_event(state, value, initiator) else: collection.remove_with_event(value, initiator) def set(self, state, value, initiator): """Set a value on the given object. `initiator` is the ``InstrumentedAttribute`` that initiated the ``set()` operation and is used to control the depth of a circular setter operation. """ if initiator is self: return self._set_iterable( state, value, lambda adapter, i: adapter.adapt_like_to_iterable(i)) def _set_iterable(self, state, iterable, adapter=None): """Set a collection value from an iterable of state-bearers. ``adapter`` is an optional callable invoked with a CollectionAdapter and the iterable. Should return an iterable of state-bearing instances suitable for appending via a CollectionAdapter. Can be used for, e.g., adapting an incoming dictionary into an iterator of values rather than keys. """ # pulling a new collection first so that an adaptation exception does # not trigger a lazy load of the old collection. new_collection, user_data = self._build_collection(state) if adapter: new_values = list(adapter(new_collection, iterable)) else: new_values = list(iterable) old = self.get(state) # ignore re-assignment of the current collection, as happens # implicitly with in-place operators (foo.collection |= other) if old is iterable: return if self.key not in state.committed_state: state.committed_state[self.key] = self.copy(old) old_collection = self.get_collection(state, old) state.dict[self.key] = user_data state.modified = True collections.bulk_replace(new_values, old_collection, new_collection) old_collection.unlink(old) def set_committed_value(self, state, value): """Set an attribute value on the given instance and 'commit' it. Loads the existing collection from lazy callables in all cases. """ collection, user_data = self._build_collection(state) if value: for item in value: collection.append_without_event(item) state.callables.pop(self.key, None) state.dict[self.key] = user_data if self.key in state.pending: # pending items. commit loaded data, add/remove new data state.committed_state[self.key] = list(value or []) added = state.pending[self.key].added_items removed = state.pending[self.key].deleted_items for item in added: collection.append_without_event(item) for item in removed: collection.remove_without_event(item) del state.pending[self.key] elif self.key in state.committed_state: # no pending items. remove committed state if any. # (this can occur with an expired attribute) del state.committed_state[self.key] return user_data def _build_collection(self, state): """build a new, blank collection and return it wrapped in a CollectionAdapter.""" user_data = self.collection_factory() collection = collections.CollectionAdapter(self, state, user_data) return collection, user_data def get_collection(self, state, user_data=None, passive=False): """retrieve the CollectionAdapter associated with the given state. Creates a new CollectionAdapter if one does not exist. """ if user_data is None: user_data = self.get(state, passive=passive) if user_data is PASSIVE_NORESULT: return user_data try: return getattr(user_data, '_sa_adapter') except AttributeError: # TODO: this codepath never occurs, and this # except/initialize should be removed collections.CollectionAdapter(self, state, user_data) return getattr(user_data, '_sa_adapter') class GenericBackrefExtension(interfaces.AttributeExtension): """An extension which synchronizes a two-way relationship. A typical two-way relationship is a parent object containing a list of child objects, where each child object references the parent. The other are two objects which contain scalar references to each other. """ def __init__(self, key): self.key = key def set(self, instance, child, oldchild, initiator): if oldchild is child: return if oldchild is not None: # With lazy=None, there's no guarantee that the full collection is # present when updating via a backref. impl = getattr(oldchild.__class__, self.key).impl try: impl.remove(oldchild._state, instance, initiator, passive=True) except (ValueError, KeyError, IndexError): pass if child is not None: getattr(child.__class__, self.key).impl.append(child._state, instance, initiator, passive=True) def append(self, instance, child, initiator): getattr(child.__class__, self.key).impl.append(child._state, instance, initiator, passive=True) def remove(self, instance, child, initiator): if child is not None: getattr(child.__class__, self.key).impl.remove(child._state, instance, initiator, passive=True) class ClassState(object): """tracks state information at the class level.""" def __init__(self): self.mappers = {} self.attrs = {} self.has_mutable_scalars = False import sets _empty_set = sets.ImmutableSet() class InstanceState(object): """tracks state information at the instance level.""" def __init__(self, obj): self.class_ = obj.__class__ self.obj = weakref.ref(obj, self.__cleanup) self.dict = obj.__dict__ self.committed_state = {} self.modified = False self.callables = {} self.parents = {} self.pending = {} self.appenders = {} self.instance_dict = None self.runid = None self.expired_attributes = _empty_set def __cleanup(self, ref): # tiptoe around Python GC unpredictableness instance_dict = self.instance_dict if instance_dict is None: return instance_dict = instance_dict() if instance_dict is None or instance_dict._mutex is None: return # the mutexing here is based on the assumption that gc.collect() # may be firing off cleanup handlers in a different thread than that # which is normally operating upon the instance dict. instance_dict._mutex.acquire() try: try: self.__resurrect(instance_dict) except: # catch app cleanup exceptions. no other way around this # without warnings being produced pass finally: instance_dict._mutex.release() def _check_resurrect(self, instance_dict): instance_dict._mutex.acquire() try: return self.obj() or self.__resurrect(instance_dict) finally: instance_dict._mutex.release() def get_pending(self, key): if key not in self.pending: self.pending[key] = PendingCollection() return self.pending[key] def is_modified(self): if self.modified: return True elif self.class_._class_state.has_mutable_scalars: for attr in _managed_attributes(self.class_): if hasattr(attr.impl, 'check_mutable_modified') and attr.impl.check_mutable_modified(self): return True else: return False else: return False def __resurrect(self, instance_dict): if self.is_modified(): # store strong ref'ed version of the object; will revert # to weakref when changes are persisted obj = new_instance(self.class_, state=self) self.obj = weakref.ref(obj, self.__cleanup) self._strong_obj = obj obj.__dict__.update(self.dict) self.dict = obj.__dict__ return obj else: del instance_dict[self.dict['_instance_key']] return None def __getstate__(self): return {'committed_state':self.committed_state, 'pending':self.pending, 'parents':self.parents, 'modified':self.modified, 'instance':self.obj(), 'expired_attributes':self.expired_attributes, 'callables':self.callables} def __setstate__(self, state): self.committed_state = state['committed_state'] self.parents = state['parents'] self.pending = state['pending'] self.modified = state['modified'] self.obj = weakref.ref(state['instance']) self.class_ = self.obj().__class__ self.dict = self.obj().__dict__ self.callables = state['callables'] self.runid = None self.appenders = {} self.expired_attributes = state['expired_attributes'] def initialize(self, key): getattr(self.class_, key).impl.initialize(self) def set_callable(self, key, callable_): self.dict.pop(key, None) self.callables[key] = callable_ def __call__(self): """__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable. """ instance = self.obj() unmodified = self.unmodified self.class_._class_state.deferred_scalar_loader(instance, [ attr.impl.key for attr in _managed_attributes(self.class_) if attr.impl.accepts_scalar_loader and attr.impl.key in self.expired_attributes and attr.impl.key in unmodified ]) for k in self.expired_attributes: self.callables.pop(k, None) self.expired_attributes.clear() return ATTR_WAS_SET def unmodified(self): """a set of keys which have no uncommitted changes""" return util.Set([ attr.impl.key for attr in _managed_attributes(self.class_) if attr.impl.key not in self.committed_state and (not hasattr(attr.impl, 'commit_to_state') or not attr.impl.check_mutable_modified(self)) ]) unmodified = property(unmodified) def expire_attributes(self, attribute_names): self.expired_attributes = util.Set(self.expired_attributes) if attribute_names is None: for attr in _managed_attributes(self.class_): self.dict.pop(attr.impl.key, None) self.expired_attributes.add(attr.impl.key) if attr.impl.accepts_scalar_loader: self.callables[attr.impl.key] = self self.committed_state = {} else: for key in attribute_names: self.dict.pop(key, None) self.committed_state.pop(key, None) self.expired_attributes.add(key) if getattr(self.class_, key).impl.accepts_scalar_loader: self.callables[key] = self def reset(self, key): """remove the given attribute and any callables associated with it.""" self.dict.pop(key, None) self.callables.pop(key, None) def commit_attr(self, attr, value): """set the value of an attribute and mark it 'committed'.""" if hasattr(attr, 'commit_to_state'): attr.commit_to_state(self, value) else: self.committed_state.pop(attr.key, None) self.dict[attr.key] = value self.pending.pop(attr.key, None) self.appenders.pop(attr.key, None) # we have a value so we can also unexpire it self.callables.pop(attr.key, None) if attr.key in self.expired_attributes: self.expired_attributes.remove(attr.key) def commit(self, keys): """commit all attributes named in the given list of key names. This is used by a partial-attribute load operation to mark committed those attributes which were refreshed from the database. Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict. """ if self.class_._class_state.has_mutable_scalars: for key in keys: attr = getattr(self.class_, key).impl if hasattr(attr, 'commit_to_state') and attr.key in self.dict: attr.commit_to_state(self, self.dict[attr.key]) else: self.committed_state.pop(attr.key, None) self.pending.pop(key, None) self.appenders.pop(key, None) else: for key in keys: self.committed_state.pop(key, None) self.pending.pop(key, None) self.appenders.pop(key, None) # unexpire attributes which have loaded for key in self.expired_attributes.intersection(keys): if key in self.dict: self.expired_attributes.remove(key) self.callables.pop(key, None) def commit_all(self): """commit all attributes unconditionally. This is used after a flush() or a regular instance load or refresh operation to mark committed all populated attributes. Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict. """ self.committed_state = {} self.modified = False self.pending = {} self.appenders = {} # unexpire attributes which have loaded for key in list(self.expired_attributes): if key in self.dict: self.expired_attributes.remove(key) self.callables.pop(key, None) if self.class_._class_state.has_mutable_scalars: for attr in _managed_attributes(self.class_): if hasattr(attr.impl, 'commit_to_state') and attr.impl.key in self.dict: attr.impl.commit_to_state(self, self.dict[attr.impl.key]) # remove strong ref self._strong_obj = None class WeakInstanceDict(UserDict.UserDict): """similar to WeakValueDictionary, but wired towards 'state' objects.""" def __init__(self, *args, **kw): self._wr = weakref.ref(self) # RLock because the mutex is used by a cleanup handler, which can be # called at any time (including within an already mutexed block) self._mutex = util.threading.RLock() UserDict.UserDict.__init__(self, *args, **kw) def __getitem__(self, key): state = self.data[key] o = state.obj() if o is None: o = state._check_resurrect(self) if o is None: raise KeyError, key return o def __contains__(self, key): try: state = self.data[key] o = state.obj() if o is None: o = state._check_resurrect(self) except KeyError: return False return o is not None def has_key(self, key): return key in self def __repr__(self): return "<InstanceDict at %s>" % id(self) def __setitem__(self, key, value): if key in self.data: self._mutex.acquire() try: if key in self.data: self.data[key].instance_dict = None finally: self._mutex.release() self.data[key] = value._state value._state.instance_dict = self._wr def __delitem__(self, key): state = self.data[key] state.instance_dict = None del self.data[key] def get(self, key, default=None): try: state = self.data[key] except KeyError: return default else: o = state.obj() if o is None: # This should only happen return default else: return o def items(self): L = [] for key, state in self.data.items(): o = state.obj() if o is not None: L.append((key, o)) return L def iteritems(self): for state in self.data.itervalues(): value = state.obj() if value is not None: yield value._instance_key, value def iterkeys(self): return self.data.iterkeys() def __iter__(self): return self.data.iterkeys() def __len__(self): return len(self.values()) def itervalues(self): for state in self.data.itervalues(): instance = state.obj() if instance is not None: yield instance def values(self): L = [] for state in self.data.values(): o = state.obj() if o is not None: L.append(o) return L def popitem(self): raise NotImplementedError() def pop(self, key, *args): raise NotImplementedError() def setdefault(self, key, default=None): raise NotImplementedError() def update(self, dict=None, **kwargs): raise NotImplementedError() def copy(self): raise NotImplementedError() def all_states(self): return self.data.values() class StrongInstanceDict(dict): def all_states(self): return [o._state for o in self.values()] def _create_history(attr, state, current): original = state.committed_state.get(attr.key, NEVER_SET) if hasattr(attr, 'get_collection'): current = attr.get_collection(state, current) if original is NO_VALUE: return (list(current), [], []) elif original is NEVER_SET: return ([], list(current), []) else: collection = util.OrderedIdentitySet(current) s = util.OrderedIdentitySet(original) return (list(collection.difference(s)), list(collection.intersection(s)), list(s.difference(collection))) else: if current is NO_VALUE: if original not in [None, NEVER_SET, NO_VALUE]: deleted = [original] else: deleted = [] return ([], [], deleted) elif original is NO_VALUE: return ([current], [], []) elif original is NEVER_SET or attr.is_equal(current, original) is True: # dont let ClauseElement expressions here trip things up return ([], [current], []) else: if original is not None: deleted = [original] else: deleted = [] return ([current], [], deleted) class PendingCollection(object): """stores items appended and removed from a collection that has not been loaded yet. When the collection is loaded, the changes present in PendingCollection are applied to produce the final result. """ def __init__(self): self.deleted_items = util.IdentitySet() self.added_items = util.OrderedIdentitySet() def append(self, value): if value in self.deleted_items: self.deleted_items.remove(value) self.added_items.add(value) def remove(self, value): if value in self.added_items: self.added_items.remove(value) self.deleted_items.add(value) def _managed_attributes(class_): """return all InstrumentedAttributes associated with the given class_ and its superclasses.""" return chain(*[cl._class_state.attrs.values() for cl in class_.__mro__[:-1] if hasattr(cl, '_class_state')]) def get_history(state, key, **kwargs): return getattr(state.class_, key).impl.get_history(state, **kwargs) def get_as_list(state, key, passive=False): """return an InstanceState attribute as a list, regardless of it being a scalar or collection-based attribute. returns None if passive=True and the getter returns PASSIVE_NORESULT. """ attr = getattr(state.class_, key).impl x = attr.get(state, passive=passive) if x is PASSIVE_NORESULT: return None elif hasattr(attr, 'get_collection'): return attr.get_collection(state, x, passive=passive) elif isinstance(x, list): return x else: return [x] def has_parent(class_, instance, key, optimistic=False): return getattr(class_, key).impl.hasparent(instance._state, optimistic=optimistic) def _create_prop(class_, key, uselist, callable_, typecallable, useobject, mutable_scalars, impl_class, **kwargs): if impl_class: return impl_class(class_, key, typecallable, **kwargs) elif uselist: return CollectionAttributeImpl(class_, key, callable_, typecallable, **kwargs) elif useobject: return ScalarObjectAttributeImpl(class_, key, callable_,**kwargs) elif mutable_scalars: return MutableScalarAttributeImpl(class_, key, callable_, **kwargs) else: return ScalarAttributeImpl(class_, key, callable_, **kwargs) def manage(instance): """initialize an InstanceState on the given instance.""" if not hasattr(instance, '_state'): instance._state = InstanceState(instance) def new_instance(class_, state=None): """create a new instance of class_ without its __init__() method being called. Also initializes an InstanceState on the new instance. """ s = class_.__new__(class_) if state: s._state = state else: s._state = InstanceState(s) return s def _init_class_state(class_): if not '_class_state' in class_.__dict__: class_._class_state = ClassState() def register_class(class_, extra_init=None, on_exception=None, deferred_scalar_loader=None): _init_class_state(class_) class_._class_state.deferred_scalar_loader=deferred_scalar_loader oldinit = None doinit = False def init(instance, *args, **kwargs): if not hasattr(instance, '_state'): instance._state = InstanceState(instance) if extra_init: extra_init(class_, oldinit, instance, args, kwargs) try: if doinit: oldinit(instance, *args, **kwargs) elif args or kwargs: # simulate error message raised by object(), but don't copy # the text verbatim raise TypeError("default constructor for object() takes no parameters") except: if on_exception: on_exception(class_, oldinit, instance, args, kwargs) raise # override oldinit oldinit = class_.__init__ if oldinit is None or not hasattr(oldinit, '_oldinit'): init._oldinit = oldinit class_.__init__ = init # if oldinit is already one of our 'init' methods, replace it elif hasattr(oldinit, '_oldinit'): init._oldinit = oldinit._oldinit class_.__init = init oldinit = oldinit._oldinit if oldinit is not None: doinit = oldinit is not object.__init__ try: init.__name__ = oldinit.__name__ init.__doc__ = oldinit.__doc__ except: # cant set __name__ in py 2.3 ! pass def unregister_class(class_): if hasattr(class_, '__init__') and hasattr(class_.__init__, '_oldinit'): if class_.__init__._oldinit is not None: class_.__init__ = class_.__init__._oldinit else: delattr(class_, '__init__') if '_class_state' in class_.__dict__: _class_state = class_.__dict__['_class_state'] for key, attr in _class_state.attrs.iteritems(): if key in class_.__dict__: delattr(class_, attr.impl.key) delattr(class_, '_class_state') def register_attribute(class_, key, uselist, useobject, callable_=None, proxy_property=None, mutable_scalars=False, impl_class=None, **kwargs): _init_class_state(class_) typecallable = kwargs.pop('typecallable', None) if isinstance(typecallable, InstrumentedAttribute): typecallable = None comparator = kwargs.pop('comparator', None) if key in class_.__dict__ and isinstance(class_.__dict__[key], InstrumentedAttribute): # this currently only occurs if two primary mappers are made for the same class. # TODO: possibly have InstrumentedAttribute check "entity_name" when searching for impl. # raise an error if two attrs attached simultaneously otherwise return if proxy_property: proxy_type = proxied_attribute_factory(proxy_property) inst = proxy_type(key, proxy_property, comparator) else: inst = InstrumentedAttribute(_create_prop(class_, key, uselist, callable_, useobject=useobject, typecallable=typecallable, mutable_scalars=mutable_scalars, impl_class=impl_class, **kwargs), comparator=comparator) setattr(class_, key, inst) class_._class_state.attrs[key] = inst def unregister_attribute(class_, key): class_state = class_._class_state if key in class_state.attrs: del class_._class_state.attrs[key] delattr(class_, key) def init_collection(instance, key): """Initialize a collection attribute and return the collection adapter.""" attr = getattr(instance.__class__, key).impl state = instance._state user_data = attr.initialize(state) return attr.get_collection(state, user_data)
mit
-8,474,694,774,015,333,000
34.677196
226
0.612948
false
4.308616
false
false
false
oxo42/FpTest
samples/test_GPONLink_Terminate.py
1
2504
""" Test the Terminate/GPONLink Product Order The product order takes a serial number, calls LST-ONTDETAIL to get the details of the ONT then DEL-ONT to remove it. This test case ensures that the right commands happen in the right order """ import fptest class TerminateGponLinkTest(fptest.FpTest): def test_workorders(self): expected_workorders = [('LST-ONTDETAIL', 'WOS_Completed'), ('DEL-ONT', 'WOS_Completed')] actual_workorders = [(wo.name, wo.status) for wo in self.cart_order_tracing.outgoing_workorders] self.assertListEqual(expected_workorders, actual_workorders) def test_command_for_lst_ontdetail(self): self.assertEqual(['LST-ONTDETAIL::ALIAS=9999999999999999:0::;'], self.cart_order_tracing.outgoing_workorders[0].params['#NE_COMMAND']) def test_alias(self): lst_ontdetail = self.get_first_wo('LST-ONTDETAIL') self.assertRegex(lst_ontdetail.params['#NE_COMMAND'][0], r'ALIAS=9999999999999999') def test_status(self): self.assertEqual('OK', self.get_fp_status()) def request(self): return """ <request> <so> <orderId>1412685518565</orderId> <sod> <domain>GPON</domain> <verb>Terminate</verb> <customerId>RegressionTesting</customerId> <originator>WGET</originator> <priority>10</priority> <doCheckpoint>false</doCheckpoint> <dataset> <param> <name>routerName</name> <index>0</index> <value>router</value> </param> </dataset> <pod> <productName>GPONLink</productName> <productVerb>Terminate</productVerb> <dataset> <param> <name>ElementManager</name> <index>0</index> <value>Huawei_U2000</value> </param> <param> <name>serialNumber</name> <index>0</index> <value>9999999999999999</value> </param> <param> <name>pppUsername</name> <index>0</index> <value>foo@example.com</value> </param> </dataset> </pod> </sod> </so> </request> """
apache-2.0
8,545,692,665,036,219,000
34.28169
117
0.522364
false
4.15257
true
false
false
nedlowe/amaas-core-sdk-python
amaascore/tools/generate_transaction.py
1
6700
from __future__ import absolute_import, division, print_function, unicode_literals from amaasutils.random_utils import random_string import datetime from decimal import Decimal import random from amaascore.core.comment import Comment from amaascore.core.reference import Reference from amaascore.transactions.cash_transaction import CashTransaction from amaascore.transactions.children import Charge, Code, Link, Party, Rate from amaascore.transactions.enums import TRANSACTION_ACTIONS, CASH_TRANSACTION_TYPES from amaascore.transactions.position import Position from amaascore.transactions.transaction import Transaction CHARGE_TYPES = ['Tax', 'Commission'] CODE_TYPES = ['Settle Code', 'Client Classifier'] COMMENT_TYPES = ['Trader'] PARTY_TYPES = ['Prime Broker'] RATE_TYPES = ['Tax', 'Commission'] REFERENCE_TYPES = ['External'] def generate_common(asset_manager_id, asset_book_id, counterparty_book_id, asset_id, quantity, transaction_date, transaction_id, transaction_action, transaction_type, transaction_status): common = {'asset_manager_id': asset_manager_id or random.randint(1, 1000), 'asset_book_id': asset_book_id or random_string(8), 'counterparty_book_id': counterparty_book_id or random_string(8), 'asset_id': asset_id or str(random.randint(1, 1000)), 'quantity': quantity or Decimal(random.randint(0, 5000)), 'transaction_date': transaction_date or datetime.date.today(), 'transaction_action': transaction_action or random.choice(list(TRANSACTION_ACTIONS)), 'transaction_id': transaction_id, 'transaction_status': transaction_status or 'New', 'transaction_type': transaction_type or 'Trade' } common['settlement_date'] = (datetime.timedelta(days=2) + common['transaction_date']) return common def generate_transaction(asset_manager_id=None, asset_book_id=None, counterparty_book_id=None, asset_id=None, quantity=None, transaction_date=None, transaction_id=None, price=None, transaction_action=None, transaction_type=None, transaction_status=None, transaction_currency=None, settlement_currency=None, net_affecting_charges=None, charge_currency=None): # Explicitly handle price is None (in case price is 0) price = Decimal(random.uniform(1.0, 1000.0)).quantize(Decimal('0.01')) if price is None else price transaction_currency = transaction_currency or random.choice(['SGD', 'USD']) settlement_currency = settlement_currency or transaction_currency or random.choice(['SGD', 'USD']) common = generate_common(asset_manager_id=asset_manager_id, asset_book_id=asset_book_id, counterparty_book_id=counterparty_book_id, asset_id=asset_id, quantity=quantity, transaction_date=transaction_date, transaction_id=transaction_id, transaction_action=transaction_action, transaction_status=transaction_status, transaction_type=transaction_type) transaction = Transaction(price=price, transaction_currency=transaction_currency, settlement_currency=settlement_currency, **common) charges = {charge_type: Charge(charge_value=Decimal(random.uniform(1.0, 100.0)).quantize(Decimal('0.01')), currency=charge_currency or random.choice(['USD', 'SGD']), net_affecting=net_affecting_charges or random.choice([True, False])) for charge_type in CHARGE_TYPES} links = {'Single': Link(linked_transaction_id=random_string(8)), 'Multiple': {Link(linked_transaction_id=random_string(8)) for x in range(3)}} codes = {code_type: Code(code_value=random_string(8)) for code_type in CODE_TYPES} comments = {comment_type: Comment(comment_value=random_string(8)) for comment_type in COMMENT_TYPES} parties = {party_type: Party(party_id=random_string(8)) for party_type in PARTY_TYPES} rates = {rate_type: Rate(rate_value=Decimal(random.uniform(1.0, 100.0)).quantize(Decimal('0.01'))) for rate_type in RATE_TYPES} references = {ref_type: Reference(reference_value=random_string(10)) for ref_type in REFERENCE_TYPES} transaction.charges.update(charges) transaction.codes.update(codes) transaction.comments.update(comments) transaction.links.update(links) transaction.parties.update(parties) transaction.rates.update(rates) transaction.references.update(references) return transaction def generate_cash_transaction(asset_manager_id=None, asset_book_id=None, counterparty_book_id=None, asset_id=None, quantity=None, transaction_date=None, transaction_id=None, transaction_action=None, transaction_type=None, transaction_status=None): transaction_type = transaction_type or random.choice(list(CASH_TRANSACTION_TYPES)) common = generate_common(asset_manager_id=asset_manager_id, asset_book_id=asset_book_id, counterparty_book_id=counterparty_book_id, asset_id=asset_id, quantity=quantity, transaction_date=transaction_date, transaction_id=transaction_id, transaction_action=transaction_action, transaction_status=transaction_status, transaction_type=transaction_type) transaction = CashTransaction(**common) return transaction def generate_position(asset_manager_id=None, book_id=None, asset_id=None, quantity=None): position = Position(asset_manager_id=asset_manager_id or random.randint(1, 1000), book_id=book_id or random_string(8), asset_id=asset_id or str(random.randint(1, 1000)), quantity=quantity or Decimal(random.randint(1, 50000))) return position def generate_transactions(asset_manager_ids=[], number=5): transactions = [] for i in range(number): transaction = generate_transaction(asset_manager_id=random.choice(asset_manager_ids)) transactions.append(transaction) return transactions def generate_positions(asset_manager_ids=[], book_ids=[], number=5): positions = [] for i in range(number): position = generate_position(asset_manager_id=random.choice(asset_manager_ids), book_id=random.choice(book_ids) if book_ids else None) positions.append(position) return positions
apache-2.0
-2,945,252,358,435,631,600
53.471545
112
0.667761
false
4.028863
false
false
false
AntoDev96/GuidaSky
controller/channel_controller.py
1
1075
import codecs import json import urllib.request from constants import constants, command_name_list from telepot.namedtuple import KeyboardButton, ReplyKeyboardMarkup from model.repositories import channel_repository from bot import bot from decorators.command import command @command(command_name_list["listacanali"]) def get_all_channels(chat_id, message, **kwargs): bot.sendChatAction(chat_id, "typing") result = [] for channel in channel_repository.find_all_channels(): result.append([KeyboardButton(text = channel.name)]) keyboard = ReplyKeyboardMarkup(keyboard=result, one_time_keyboard=True, selective=True) bot.sendMessage(chat_id, constants["selectChannel"], reply_markup=keyboard) return "/listaprogrammi" def find_channel(name): url = constants["linkSky"] + "/" + constants["linkChannelList"] httpResult = urllib.request.urlopen(url) httpResult = codecs.getreader("UTF-8")(httpResult) channels = json.load(httpResult) for channel in channels: if name == channel["name"]: return channel["id"]
gpl-3.0
6,275,880,955,524,322,000
38.851852
91
0.736744
false
3.909091
false
false
false
PaddlePaddle/models
PaddleCV/3d_vision/PointRCNN/tools/kitti_eval.py
1
2220
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import argparse def parse_args(): parser = argparse.ArgumentParser( "KITTI mAP evaluation script") parser.add_argument( '--result_dir', type=str, default='./result_dir', help='detection result directory to evaluate') parser.add_argument( '--data_dir', type=str, default='./data', help='KITTI dataset root directory') parser.add_argument( '--split', type=str, default='val', help='evaluation split, default val') parser.add_argument( '--class_name', type=str, default='Car', help='evaluation class name, default Car') args = parser.parse_args() return args def kitti_eval(): if float(sys.version[:3]) < 3.6: print("KITTI mAP evaluation can only run with python3.6+") sys.exit(1) args = parse_args() label_dir = os.path.join(args.data_dir, 'KITTI/object/training', 'label_2') split_file = os.path.join(args.data_dir, 'KITTI/ImageSets', '{}.txt'.format(args.split)) final_output_dir = os.path.join(args.result_dir, 'final_result', 'data') name_to_class = {'Car': 0, 'Pedestrian': 1, 'Cyclist': 2} from tools.kitti_object_eval_python.evaluate import evaluate as kitti_evaluate ap_result_str, ap_dict = kitti_evaluate( label_dir, final_output_dir, label_split_file=split_file, current_class=name_to_class[args.class_name]) print("KITTI evaluate: ", ap_result_str, ap_dict) if __name__ == "__main__": kitti_eval()
apache-2.0
1,994,207,320,236,597,000
30.267606
83
0.640991
false
3.58643
false
false
false
klmitch/tendril
tendril/__init__.py
1
12025
## Copyright (C) 2012 by Kevin L. Mitchell <klmitch@mit.edu> ## ## 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/>. """ ============================================== Tendril Frame-based Network Connection Tracker ============================================== Tendril is a network communication library based on two main features: it is based on sending and receiving frames, and it tracks the state of an abstract connection as defined by the application. Tendril is designed to be easy to use: creating an application requires subclassing the ``Application`` class and providing an implementation for the recv_frame() method; then get a ``TendrilManager`` class instance and start it, and Tendril manages the rest. Tendril Concepts ================ Frames ------ Tendril is based on the concept of passing around frames or packets of data. The fact is, most network protocols are based on sending and receiving frames; for instance, in the SMTP protocol used for sending email, the sender will start off sending the frame "MAIL FROM email@example.com" followed by a line termination sequence (a carriage return followed by a newline). The SMTP server will then respond with another frame acknowledging the "MAIL FROM" frame, and that frame will also end with a line termination sequence. Thus, even though SMTP is defined on top of the TCP protocol, which provides an undivided stream of data between the client and server, a framing boundary is imposed upon it--in this case, the carriage return followed by a newline that terminates each frame. Tendril includes the concept of *framers*. A framer is nothing more than a subclass of ``Framer`` which has one method which extracts a single frame from the stream of undifferentiated data, and another method which converts a frame into an appropriate representation. In the case of the SMTP protocol exchange above, the ``frameify()`` method finds each line terminated by the carriage return-newline pair, strips off those characters, and returns just the frame. In the same way, the corresponding ``streamify()`` method takes the frame and appends a carriage return-newline pair. For text-based protocols such as SMTP, this may seem like overkill. However, for binary-based protocols, a lot of code is dedicated to determining the boundaries between frames, and in some cases even decoding the frame. Tendril's concept of a framer for a connection enables the framing logic to be isolated from the rest of the application, and even reused: Tendril comes with several pre-built framers, including framers designed to work with a text-based protocol such as SMTP. Another important advantage of the framer concept is the ability to switch between framers as needed. Taking again the example of the SMTP protocol--the actual email data is transferred to the server by the client first sending a "DATA" frame; the server responds indicating that it is ready to begin receiving the message data, and then the client simply sends the message data, ending it with a line containing only a single period ("."). In this case, an SMTP server application based on Tendril may wish to receive the message data as a single frame; it can do this by creating a framer which buffers stream data until it sees that ending sentinel (the period on a line by itself), then returns the whole message as a single frame. Once the server receives the "DATA" frame from the client, all it has to do is temporarily switch out the framer in use for the receiving side of the connection, then switch it back to the standard line-based framer once it has received the message frame. Tendril allows for different framers to be used on the receiving side and sending side of the connection. This could be used in a case like the SMTP server example cited above, where the server still wishes to send line-oriented frames to the client, even while buffering a message data frame. In addition, although the provided framers deal with byte data, Tendril itself treats the frames as opaque; applications can use this to build a framer that additionally parses a given frame into a class object that the rest of the application then processes as necessary. Connection Tracking ------------------- Tendril is also based on the concept of tracking connection state. For connection-oriented protocols such as TCP, obviously, this is not a big problem; however, Tendril is also designed to support connectionless protocols such as UDP, where some applications need to manage state information relevant to a given exchange. As an admittedly contrived example, consider DNS, which is based on UDP. A client of the DNS system will send a request to a DNS server over UDP; when a response is received from that DNS server, the connection state information tracked by Tendril can help connect that response with the appropriate request, ensuring that the response goes to the right place. This connection state tracking is primarily intended to assist applications which desire to be available over both connection-oriented protocols such as TCP and over connectionless protocols such as UDP. Although Tendril does not address reliability or frame ordering, its connection state tracking eases the implementation of an application which utilizes both types of protocols. Extensibility ------------- Careful readers may have noticed the use of the terms, "such as TCP" and "such as UDP." Although Tendril only has built-in support for TCP and UDP connections, it is possible to extend Tendril to support other protocols. All that is required is to create subclasses of ``Tendril`` (representing an individual connection) and of ``TendrilManager`` (which accepts and creates connections and manages any necessary socket data flows), and to register the ``TendrilManager`` subclasses as ``pkg_resources`` entry points under the ``tendril.manager`` namespace. See the ``setup.py`` for Tendril for an example of how this may be done. In addition to allowing Tendril to support protocols other than TCP and UDP, it is also possible to implement new framers by subclassing the ``Framer`` class. (Note: as Tendril deals with ``Framer`` objects, it is not necessary to register these framers using ``pkg_resources`` entry points.) Objects of these classes may then simply be assigned to the appropriate ``framers`` attribute on the ``Tendril`` instance representing the connection. Advanced Interfaces ------------------- Tendril also provides an advanced interface that allows a given raw socket to be "wrapped." Using this feature, an ordinary TCP socket could be converted into an SSL socket. Other uses for this interface are possible, such as setting socket options for the socket. Tendril also provides an interface to allow multiple of these wrapper functions to be called in a given order. Standard Usage ============== The first step in using Tendril is to define an application by subclassing the ``Application`` class. (Subclassing is not strictly necessary--Tendril uses Python's standard ``abc`` package for defining abstract base classes--but using subclassing will pull in a few helpful and/or required methods.) The subclass need merely implement the recv_frame() method, which will be called when a frame is received. The ``Application`` subclass constructor itself can be the *acceptor* to be used by Tendril (more on acceptors in a moment). Once the ``Application`` subclass has been created, the developer then needs to get a ``TendrilManager`` instance, using the ``get_manager()`` factory function. The exact call to ``get_manager()`` depends on the needs; for making outgoing connections, simply calling ``get_manager("tcp")`` is sufficient. If listening on a port or making an outgoing connection from a specific address and/or port is desired, the second argument to ``get_manager()`` may be a tuple of the desired local IP address and the port number (i.e., ``("127.0.0.1", 80)``). All managers must be started, and ``get_manager()`` does not start the manager by itself. Check the manager's ``running`` attribute to see if the manager is already running, and if it is not, call its ``start()`` method. To accept connections, pass ``start()`` the *acceptor* (usually the ``Application`` subclass). The ``start()`` method also accepts a *wrapper*, which will be called with the listening socket when it is created. If, instead of accepting connections (as a server would do), the desire is to make outgoing connections, simply call ``start()`` with no arguments, then call the ``connect()`` method of the manager. This method takes the *target* of the connection (i.e., the IP address and port number, as a tuple) and the *acceptor*. (It also has an optional *wrapper*, which will be called with the outgoing socket just prior to initiating the connection.) Acceptors --------- An *acceptor* is simply a callable taking a single argument--the ``Tendril`` instance representing the connection--and returning an instance of a subclass of ``Application``, which will be assigned to the ``application`` attribute of the ``Tendril`` instance. The acceptor initializes the application; it also has the opportunity to manipulate that ``Tendril``, such as setting framers, calling the ``Tendril`` instance's ``wrap()`` method, or simply closing the connection. Although the ``TendrilManager`` does not provide the opportunity to pass arguments to the acceptor, it is certainly possible to do so. The standard Python ``functools.partial()`` is one obvious interface, but Tendril additionally provides its own ``TendrilPartial`` utility; the advantage of ``TendrilPartial`` is that the positional argument passed to the acceptor--the ``Tendril`` instance--will be the first positional argument, rather than the last one, as would be the case with ``functools.partial()``. Wrappers -------- A *wrapper* is simply a callable again taking a single argument--in this case, the socket object--and returning a wrapped version of that argument; that wrapped version of the socket will then be used in subsequent network calls. A wrapper which manipulates socket options can simply return the socket object which was passed in, while one which performs SSL encapsulation can return the SSL wrapper. Again, although there is no opportunity to pass arguments to the wrapper in a manager ``start()`` or ``connect()`` call (or a ``Tendril`` object's ``wrap()`` call), ``functools.partial()`` or Tendril's ``TendrilPartial`` utility can be used. In particular, in conjunction with ``TendrilPartial``, the ``ssl.wrap_socket()`` call can be used as a socket wrapper directly, enabling an SSL connection to be set up easily. Of course, it may be necessary to perform multiple "wrapping" activities on a connection, such as setting socket options followed by wrapping the socket in an SSL connection. For this case, Tendril provides the ``WrapperChain``; it can be initialized in the same way that ``TendrilPartial`` is, but additional wrappers can be added by calling the ``chain()`` method; when called, the ``WrapperChain`` object will call each wrapper in the order defined, returning the final wrapped socket in the end. """ from application import * from connection import * from framers import * from manager import * from utils import * __all__ = (application.__all__ + connection.__all__ + framers.__all__ + manager.__all__ + utils.__all__)
gpl-3.0
6,401,577,186,917,081,000
48.485597
71
0.766486
false
4.216339
false
false
false
okolisny/integration_tests
cfme/middleware/server.py
1
17554
import re from navmazing import NavigateToSibling, NavigateToAttribute from selenium.common.exceptions import NoSuchElementException from wrapanapi.hawkular import CanonicalPath from cfme.common import Taggable, UtilizationMixin from cfme.exceptions import MiddlewareServerNotFound, \ MiddlewareServerGroupNotFound from cfme.middleware.domain import MiddlewareDomain from cfme.middleware.provider import ( MiddlewareBase, download ) from cfme.middleware.provider import (parse_properties, Container) from cfme.middleware.provider.hawkular import HawkularProvider from cfme.middleware.provider.middleware_views import (ServerAllView, ServerDetailsView, ServerDatasourceAllView, ServerDeploymentAllView, ServerMessagingAllView, ServerGroupDetailsView, AddDatasourceView, AddJDBCDriverView, AddDeploymentView) from cfme.middleware.server_group import MiddlewareServerGroup from cfme.utils import attributize_string from cfme.utils.appliance import Navigatable, current_appliance from cfme.utils.appliance.implementations.ui import navigator, CFMENavigateStep, navigate_to from cfme.utils.providers import get_crud_by_name, list_providers_by_class from cfme.utils.varmeth import variable def _db_select_query(name=None, feed=None, provider=None, server_group=None, product=None): """column order: `id`, `name`, `hostname`, `feed`, `product`, `provider_name`, `ems_ref`, `properties`, `server_group_name`""" t_ms = current_appliance.db.client['middleware_servers'] t_msgr = current_appliance.db.client['middleware_server_groups'] t_ems = current_appliance.db.client['ext_management_systems'] query = current_appliance.db.client.session.query( t_ms.id, t_ms.name, t_ms.hostname, t_ms.feed, t_ms.product, t_ems.name.label('provider_name'), t_ms.ems_ref, t_ms.properties, t_msgr.name.label('server_group_name'))\ .join(t_ems, t_ms.ems_id == t_ems.id)\ .outerjoin(t_msgr, t_ms.server_group_id == t_msgr.id) if name: query = query.filter(t_ms.name == name) if feed: query = query.filter(t_ms.feed == feed) if provider: query = query.filter(t_ems.name == provider.name) if server_group: query = query.filter(t_msgr.name == server_group.name) query = query.filter(t_msgr.feed == server_group.feed) if product: query = query.filter(t_ms.product == product) return query def _get_servers_page(provider=None, server_group=None): if provider: # if provider instance is provided navigate through provider's servers page return navigate_to(provider, 'ProviderServers') elif server_group: # if server group instance is provided navigate through it's servers page return navigate_to(server_group, 'ServerGroupServers') else: # if None(provider) given navigate through all middleware servers page return navigate_to(MiddlewareServer, 'All') class MiddlewareServer(MiddlewareBase, Taggable, Container, Navigatable, UtilizationMixin): """ MiddlewareServer class provides actions and details on Server page. Class method available to get existing servers list Args: name: name of the server hostname: Host name of the server provider: Provider object (HawkularProvider) product: Product type of the server feed: feed of the server db_id: database row id of server Usage: myserver = MiddlewareServer(name='Foo.war', provider=haw_provider) myserver.reload_server() myservers = MiddlewareServer.servers() """ property_tuples = [('name', 'Name'), ('feed', 'Feed'), ('bound_address', 'Bind Address')] taggable_type = 'MiddlewareServer' deployment_message = 'Deployment "{}" has been initiated on this server.' def __init__(self, name, provider=None, appliance=None, **kwargs): Navigatable.__init__(self, appliance=appliance) if name is None: raise KeyError("'name' should not be 'None'") self.name = name self.provider = provider self.product = kwargs['product'] if 'product' in kwargs else None self.hostname = kwargs['hostname'] if 'hostname' in kwargs else None self.feed = kwargs['feed'] if 'feed' in kwargs else None self.db_id = kwargs['db_id'] if 'db_id' in kwargs else None if 'properties' in kwargs: for prop in kwargs['properties']: # check the properties first, so it will not overwrite core attributes if getattr(self, attributize_string(prop), None) is None: setattr(self, attributize_string(prop), kwargs['properties'][prop]) @classmethod def servers(cls, provider=None, server_group=None, strict=True): servers = [] view = _get_servers_page(provider=provider, server_group=server_group) _provider = provider # In deployment UI, we cannot get provider name on list all page for _ in view.entities.paginator.pages(): for row in view.entities.elements: if strict: _provider = get_crud_by_name(row.provider.text) servers.append(MiddlewareServer( name=row.server_name.text, feed=row.feed.text, hostname=row.host_name.text, product=row.product.text if row.product.text else None, provider=_provider)) return servers @classmethod def headers(cls): view = navigate_to(MiddlewareServer, 'All') headers = [hdr.encode("utf-8") for hdr in view.entities.elements.headers if hdr] return headers @classmethod def servers_in_db(cls, name=None, feed=None, provider=None, product=None, server_group=None, strict=True): servers = [] rows = _db_select_query(name=name, feed=feed, provider=provider, product=product, server_group=server_group).all() _provider = provider for server in rows: if strict: _provider = get_crud_by_name(server.provider_name) servers.append(MiddlewareServer( name=server.name, hostname=server.hostname, feed=server.feed, product=server.product, db_id=server.id, provider=_provider, properties=parse_properties(server.properties))) return servers @classmethod def _servers_in_mgmt(cls, provider, server_group=None): servers = [] rows = provider.mgmt.inventory.list_server(feed_id=server_group.feed if server_group else None) for row in rows: server = MiddlewareServer( name=re.sub('(Domain )|(WildFly Server \\[)|(\\])', '', row.name), hostname=row.data['Hostname'] if 'Hostname' in row.data else None, feed=row.path.feed_id, product=row.data['Product Name'] if 'Product Name' in row.data else None, provider=provider) # if server_group is given, filter those servers which belongs to it if not server_group or cls._belongs_to_group(server, server_group): servers.append(server) return servers @classmethod def servers_in_mgmt(cls, provider=None, server_group=None): if provider is None: servers = [] for _provider in list_providers_by_class(HawkularProvider): servers.extend(cls._servers_in_mgmt(_provider, server_group)) return servers else: return cls._servers_in_mgmt(provider, server_group) @classmethod def _belongs_to_group(cls, server, server_group): server_mgmt = server.server(method='mgmt') return getattr(server_mgmt, attributize_string('Server Group'), None) == server_group.name def load_details(self, refresh=False): view = navigate_to(self, 'Details') if not self.db_id or refresh: tmp_ser = self.server(method='db') self.db_id = tmp_ser.db_id if refresh: view.browser.selenium.refresh() view.flush_widget_cache() return view @variable(alias='ui') def server(self): self.load_details(refresh=False) return self @server.variant('mgmt') def server_in_mgmt(self): db_srv = _db_select_query(name=self.name, provider=self.provider, feed=self.feed).first() if db_srv: path = CanonicalPath(db_srv.ems_ref) mgmt_srv = self.provider.mgmt.inventory.get_config_data(feed_id=path.feed_id, resource_id=path.resource_id) if mgmt_srv: return MiddlewareServer( provider=self.provider, name=db_srv.name, feed=db_srv.feed, properties=mgmt_srv.value) return None @server.variant('db') def server_in_db(self): server = _db_select_query(name=self.name, provider=self.provider, feed=self.feed).first() if server: return MiddlewareServer( db_id=server.id, provider=self.provider, feed=server.feed, name=server.name, hostname=server.hostname, properties=parse_properties(server.properties)) return None @server.variant('rest') def server_in_rest(self): raise NotImplementedError('This feature not implemented yet') @variable(alias='ui') def server_group(self): self.load_details() return MiddlewareServerGroup( provider=self.provider, name=self.get_detail("Properties", "Name"), domain=MiddlewareDomain( provider=self.provider, name=self.get_detail("Relationships", "Middleware Domain"))) @variable(alias='ui') def is_reload_required(self): self.load_details(refresh=True) return self.get_detail("Properties", "Server State") == 'Reload-required' @variable(alias='ui') def is_running(self): self.load_details(refresh=True) return self.get_detail("Properties", "Server State") == 'Running' @variable(alias='db') def is_suspended(self): server = _db_select_query(name=self.name, provider=self.provider, feed=self.feed).first() if not server: raise MiddlewareServerNotFound("Server '{}' not found in DB!".format(self.name)) return parse_properties(server.properties)['Suspend State'] == 'SUSPENDED' @variable(alias='ui') def is_starting(self): self.load_details(refresh=True) return self.get_detail("Properties", "Server State") == 'Starting' @variable(alias='ui') def is_stopping(self): self.load_details(refresh=True) return self.get_detail("Properties", "Server State") == 'Stopping' @variable(alias='ui') def is_stopped(self): self.load_details(refresh=True) return self.get_detail("Properties", "Server State") == 'Stopped' def shutdown_server(self, timeout=10, cancel=False): view = self.load_details(refresh=True) view.toolbar.power.item_select('Gracefully shutdown Server') view.power_operation_form.fill({ "timeout": timeout, }) if cancel: view.power_operation_form.cancel_button.click() else: view.power_operation_form.shutdown_button.click() view.flash.assert_success_message('Shutdown initiated for selected server(s)') def restart_server(self): view = self.load_details(refresh=True) view.toolbar.power.item_select('Restart Server', handle_alert=True) view.flash.assert_success_message('Restart initiated for selected server(s)') def start_server(self): view = self.load_details(refresh=True) view.toolbar.power.item_select('Start Server', handle_alert=True) view.assert_success_message('Start initiated for selected server(s)') def suspend_server(self, timeout=10, cancel=False): view = self.load_details(refresh=True) view.toolbar.power.item_select('Suspend Server') view.power_operation_form.fill({ "timeout": timeout, }) if cancel: view.power_operation_form.cancel_button.click() else: view.power_operation_form.suspend_button.click() view.flash.assert_success_message('Suspend initiated for selected server(s)') def resume_server(self): view = self.load_details(refresh=True) view.toolbar.power.item_select('Resume Server', handle_alert=True) view.flash.assert_success_message('Resume initiated for selected server(s)') def reload_server(self): view = self.load_details(refresh=True) view.toolbar.power.item_select('Reload Server', handle_alert=True) view.flash.assert_success_message('Reload initiated for selected server(s)') def stop_server(self): view = self.load_details(refresh=True) view.toolbar.power.item_select('Stop Server', handle_alert=True) view.flash.assert_success_message('Stop initiated for selected server(s)') def kill_server(self): view = self.load_details(refresh=True) view.toolbar.power.item_select('Kill Server', handle_alert=True) view.flash.assert_success_message('Kill initiated for selected server(s)') @classmethod def download(cls, extension, provider=None, server_group=None): view = _get_servers_page(provider, server_group) download(view, extension) @navigator.register(MiddlewareServer, 'All') class All(CFMENavigateStep): VIEW = ServerAllView prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn') def step(self): self.prerequisite_view.navigation.select('Middleware', 'Servers') @navigator.register(MiddlewareServer, 'Details') class Details(CFMENavigateStep): VIEW = ServerDetailsView prerequisite = NavigateToSibling('All') def step(self, *args, **kwargs): try: if self.obj.feed: # TODO find_row_on_pages change to entities.get_entity() row = self.prerequisite_view.entities.paginator.find_row_on_pages( self.prerequisite_view.entities.elements, server_name=self.obj.name, feed=self.obj.feed) elif self.obj.hostname: row = self.prerequisite_view.entities.paginator.find_row_on_pages( self.prerequisite_view.entities.elements, server_name=self.obj.name, host_name=self.obj.hostname) else: row = self.prerequisite_view.entities.paginator.find_row_on_pages( self.prerequisite_view.entities.elements, server_name=self.obj.name) except NoSuchElementException: raise MiddlewareServerNotFound( "Server '{}' not found in table".format(self.obj.name)) row.click() @navigator.register(MiddlewareServer, 'ServerDatasources') class ServerDatasources(CFMENavigateStep): VIEW = ServerDatasourceAllView prerequisite = NavigateToSibling('Details') def step(self): self.prerequisite_view.entities.relationships.click_at('Middleware Datasources') @navigator.register(MiddlewareServer, 'ServerDeployments') class ServerDeployments(CFMENavigateStep): VIEW = ServerDeploymentAllView prerequisite = NavigateToSibling('Details') def step(self): self.prerequisite_view.entities.relationships.click_at('Middleware Deployments') @navigator.register(MiddlewareServer, 'ServerMessagings') class ServerMessagings(CFMENavigateStep): VIEW = ServerMessagingAllView prerequisite = NavigateToSibling('Details') def step(self): self.prerequisite_view.entities.relationships.click_at('Middleware Messagings') @navigator.register(MiddlewareServer, 'ServerGroup') class ServerGroup(CFMENavigateStep): VIEW = ServerGroupDetailsView prerequisite = NavigateToSibling('Details') def step(self): try: self.prerequisite_view.entities.relationships.click_at('Middleware Server Group') except NoSuchElementException: raise MiddlewareServerGroupNotFound('Server does not belong to Server Group') @navigator.register(MiddlewareServer, 'AddDatasource') class AddDatasource(CFMENavigateStep): VIEW = AddDatasourceView prerequisite = NavigateToSibling('Details') def step(self): self.prerequisite_view.toolbar.datasources.item_select('Add Datasource') @navigator.register(MiddlewareServer, 'AddJDBCDriver') class AddJDBCDriver(CFMENavigateStep): VIEW = AddJDBCDriverView prerequisite = NavigateToSibling('Details') def step(self): self.prerequisite_view.toolbar.drivers.item_select('Add JDBC Driver') @navigator.register(MiddlewareServer, 'AddDeployment') class AddDeployment(CFMENavigateStep): VIEW = AddDeploymentView prerequisite = NavigateToSibling('Details') def step(self): self.prerequisite_view.toolbar.deployments.item_select('Add Deployment')
gpl-2.0
6,179,716,487,599,874,000
39.540416
98
0.645779
false
4.032621
true
false
false
tynn/lunchdate.bot
setup.py
1
2335
#!/usr/bin/env python # vim: expandtab tabstop=4 shiftwidth=4 # # Copyright (c) 2016 Christian Schmitz <tynn.dev@gmail.com> # # This program 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. # # 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A Slackbot for matching people for lunch once a week. Just let lunchdate.bot have the hassle of pairing members of your team randomly, while they choose the date themselves. """ try: from setuptools import setup except ImportError: from distutils.core import setup setup( name ='launchdate.bot', version ='1.0', description ="Slackbot for matching people for lunch once a week", long_description=__doc__, author ="Christian Schmitz", author_email ="tynn.dev@gmail.com", url ="https://github.com/tynn/lunchdate.bot", license ='LGPLv3+', packages =[ 'launchdate-bot', 'launchdate-bot.api', 'launchdate-bot.messenger' ], package_dir ={'launchdate-bot': 'impl'}, platforms =['Linux'], classifiers =[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: ' 'GNU Lesser General Public License v3 or later (LGPLv3+)', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ])
lgpl-3.0
3,637,720,484,865,586,700
37.278689
79
0.642398
false
4.025862
false
false
false
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_04_01/aio/operations/_routes_operations.py
1
20983
# 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 Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class RoutesOperations: """RoutesOperations async 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.network.v2018_04_01.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) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _delete_initial( self, resource_group_name: str, route_table_name: str, route_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-01" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, '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') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore async def begin_delete( self, resource_group_name: str, route_table_name: str, route_name: str, **kwargs ) -> AsyncLROPoller[None]: """Deletes the specified route from a route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param route_name: The name of the route. :type route_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, route_table_name=route_table_name, route_name=route_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore async def get( self, resource_group_name: str, route_table_name: str, route_name: str, **kwargs ) -> "_models.Route": """Gets the specified route from a route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param route_name: The name of the route. :type route_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Route, or the result of cls(response) :rtype: ~azure.mgmt.network.v2018_04_01.models.Route :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Route"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, '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') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await 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) deserialized = self._deserialize('Route', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, route_table_name: str, route_name: str, route_parameters: "_models.Route", **kwargs ) -> "_models.Route": cls = kwargs.pop('cls', None) # type: ClsType["_models.Route"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, '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') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(route_parameters, 'Route') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('Route', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('Route', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, route_table_name: str, route_name: str, route_parameters: "_models.Route", **kwargs ) -> AsyncLROPoller["_models.Route"]: """Creates or updates a route in the specified route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param route_name: The name of the route. :type route_name: str :param route_parameters: Parameters supplied to the create or update route operation. :type route_parameters: ~azure.mgmt.network.v2018_04_01.models.Route :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Route or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2018_04_01.models.Route] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.Route"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, route_table_name=route_table_name, route_name=route_name, route_parameters=route_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Route', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore def list( self, resource_group_name: str, route_table_name: str, **kwargs ) -> AsyncIterable["_models.RouteListResult"]: """Gets all routes in a route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RouteListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_04_01.models.RouteListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.RouteListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-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.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, '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 async def extract_data(pipeline_response): deserialized = self._deserialize('RouteListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await 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 AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes'} # type: ignore
mit
1,575,352,485,687,395,300
48.025701
210
0.639327
false
4.261373
true
false
false
christopherpoole/CADMesh
cmake/generateSingleHeader.py
1
4672
import os import subprocess from glob import glob from pathlib import Path def readFile(filepath): try: with open(filepath) as f: lines = f.readlines() except: return [] return lines def readFiles(filepaths): names = map(lambda p: Path(p).stem, filepaths) files = map(readFile, filepaths) return dict(zip(names, files)) def inlineSourceFunctions(sources): # TODO: Tidy with clang first? for name in sources.keys(): source = sources[name] if name == "Exceptions": for i, line in enumerate(source): if line.strip().startswith("void ") and line.strip().endswith(")"): sources[name][i] = "inline " + line if name == "FileTypes": for i, line in enumerate(source): if line.strip().startswith("Type ") and line.strip().endswith(")"): sources[name][i] = "inline " + line else: for i, line in enumerate(source): if name + "::" in line and not line.startswith(" ") and not line.strip().endswith(";"): sources[name][i] = "inline " + line elif line.startswith("std::shared_ptr<BuiltInReader> BuiltIn()"): sources[name][i] = "inline " + line return sources def stripComments(lines): lines = [l for l in lines if not l.strip().startswith("/")] lines = [l for l in lines if not l.strip().startswith("*")] lines = [l.split("//")[0] for l in lines] return lines def stripMacros(lines): lines = [l for l in lines if not l.strip().startswith("#pragma")] return lines def isLocalInclude(line, localIncludes): if (not line.strip().startswith("#include")): return False include = Path(line.strip().split()[-1].strip("\"")).stem return include in localIncludes def stripLocalIncludes(lines, localIncludes): lines = [l for l in lines if not isLocalInclude(l, localIncludes)] return lines def gatherIncludes(lines): seen = [] unseen = [] for l in lines: if (l.startswith("#include")): if (l not in seen): seen.append(l) else: continue unseen.append(l) return unseen def addLicense(lines): license = readFile("../LICENSE") license = [ "// " + l for l in license ] license.append("\n\n") message = """// CADMESH - Load CAD files into Geant4 quickly and easily. // // Read all about it at: https://github.com/christopherpoole/CADMesh // // Basic usage: // // #include "CADMesh.hh" // This file. // ... // auto mesh = CADMesh::TessellatedMesh::FromSTL("mesh.stl"); // G4VSolid* solid = mesh->GetSolid(); // ... // // !! THIS FILE HAS BEEN AUTOMATICALLY GENERATED. DON'T EDIT IT DIRECTLY. !! """ return license + [ message ] + lines if __name__ == "__main__": includes = [ "FileTypes" , "Mesh" , "Reader" , "Lexer" , "ASSIMPReader" , "BuiltInReader" , "CADMeshTemplate" , "Exceptions" , "TessellatedMesh" , "TetrahedralMesh" ] excludes = [ "CADMesh" , "Configuration" ] sources = [ "FileTypes" , "Mesh" , "Reader" , "Lexer" , "CADMeshTemplate" , "Exceptions" , "TessellatedMesh" , "TetrahedralMesh" ] readers = [ "LexerMacros" , "STLReader" , "OBJReader" , "PLYReader" , "ASSIMPReader" , "BuiltInReader" ] hh = readFiles([os.path.join("../include", i + ".hh") for i in includes + readers]) cc = readFiles([os.path.join("../src", s + ".cc") for s in sources + readers]) cc = inlineSourceFunctions(cc) header = ["class " + h + ";\n" for h in hh] for i in includes: if i == "CADMeshTemplate": header += "#ifndef CADMESH_DEFAULT_READER\n#define CADMESH_DEFAULT_READER BuiltIn\n#endif\n\n" header += hh[i] for s in sources: header += cc[s] for r in readers: if r in includes and r in readers: continue header += hh[r] for r in readers: header += cc [r] header = stripComments(header) header = stripMacros(header) header = stripLocalIncludes(header, sources + readers + excludes) header = gatherIncludes(header) header = [ "#pragma once\n\n" ] + header header = addLicense(header) with open("CADMesh.hh", "w") as f: f.writelines(header) subprocess.run(["clang-format", "-i", "CADMesh.hh"])
mit
-8,369,801,982,411,803,000
20.730233
106
0.55244
false
3.684543
false
false
false
kennethreitz/pipenv
pipenv/patched/notpip/_internal/commands/__init__.py
1
4020
""" Package containing all pip commands """ # The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import importlib from collections import OrderedDict, namedtuple from pipenv.patched.notpip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any from pipenv.patched.notpip._internal.cli.base_command import Command CommandInfo = namedtuple('CommandInfo', 'module_path, class_name, summary') # The ordering matters for help display. # Also, even though the module path starts with the same # "pipenv.patched.notpip._internal.commands" prefix in each case, we include the full path # because it makes testing easier (specifically when modifying commands_dict # in test setup / teardown by adding info for a FakeCommand class defined # in a test-related module). # Finally, we need to pass an iterable of pairs here rather than a dict # so that the ordering won't be lost when using Python 2.7. commands_dict = OrderedDict([ ('install', CommandInfo( 'pipenv.patched.notpip._internal.commands.install', 'InstallCommand', 'Install packages.', )), ('download', CommandInfo( 'pipenv.patched.notpip._internal.commands.download', 'DownloadCommand', 'Download packages.', )), ('uninstall', CommandInfo( 'pipenv.patched.notpip._internal.commands.uninstall', 'UninstallCommand', 'Uninstall packages.', )), ('freeze', CommandInfo( 'pipenv.patched.notpip._internal.commands.freeze', 'FreezeCommand', 'Output installed packages in requirements format.', )), ('list', CommandInfo( 'pipenv.patched.notpip._internal.commands.list', 'ListCommand', 'List installed packages.', )), ('show', CommandInfo( 'pipenv.patched.notpip._internal.commands.show', 'ShowCommand', 'Show information about installed packages.', )), ('check', CommandInfo( 'pipenv.patched.notpip._internal.commands.check', 'CheckCommand', 'Verify installed packages have compatible dependencies.', )), ('config', CommandInfo( 'pipenv.patched.notpip._internal.commands.configuration', 'ConfigurationCommand', 'Manage local and global configuration.', )), ('search', CommandInfo( 'pipenv.patched.notpip._internal.commands.search', 'SearchCommand', 'Search PyPI for packages.', )), ('wheel', CommandInfo( 'pipenv.patched.notpip._internal.commands.wheel', 'WheelCommand', 'Build wheels from your requirements.', )), ('hash', CommandInfo( 'pipenv.patched.notpip._internal.commands.hash', 'HashCommand', 'Compute hashes of package archives.', )), ('completion', CommandInfo( 'pipenv.patched.notpip._internal.commands.completion', 'CompletionCommand', 'A helper command used for command completion.', )), ('debug', CommandInfo( 'pipenv.patched.notpip._internal.commands.debug', 'DebugCommand', 'Show information useful for debugging.', )), ('help', CommandInfo( 'pipenv.patched.notpip._internal.commands.help', 'HelpCommand', 'Show help for commands.', )), ]) # type: OrderedDict[str, CommandInfo] def create_command(name, **kwargs): # type: (str, **Any) -> Command """ Create an instance of the Command class with the given name. """ module_path, class_name, summary = commands_dict[name] module = importlib.import_module(module_path) command_class = getattr(module, class_name) command = command_class(name=name, summary=summary, **kwargs) return command def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
mit
-5,509,808,581,509,438,000
34.263158
90
0.677114
false
4.114637
false
false
false
brian-rose/climlab
climlab/tests/test_emanuel_convection.py
1
6379
from __future__ import division import numpy as np import climlab from climlab.convection import emanuel_convection from climlab.tests.xarray_test import to_xarray import pytest # These test data are based on direct single-column tests of the CONVECT43c.f # fortran source code. We are just checking to see if we get the right tendencies num_lev = 20 # INPUT DATA T = np.flipud([278.0, 273.9, 269.8, 265.7, 261.6, 257.5, 253.4, 249.3, 245.2, 241.1, 236.9, 232.8, 228.7, 224.6, 220.5, 216.4, 212.3, 214.0, 240., 270.]) Q = np.flipud([3.768E-03, 2.812E-03, 2.078E-03, 1.519E-03, 1.099E-03, 7.851E-04, 5.542E-04, 3.860E-04, 2.652E-04, 1.794E-04, 1.183E-04, 7.739E-05, 4.970E-05, 3.127E-05, 1.923E-05, 1.152E-05, 6.675E-06, 5.000E-06, 5.000E-06, 5.000E-06]) U = np.flipud([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0]) V = 5. * np.ones_like(U) DELT = 60.0*10. # TENDENCIES FROM FORTRAN CODE FT = np.flipud([-1.79016788E-05, -5.30500938E-06, -1.31774368E-05, -1.52709208E-06, 2.39793881E-05, 5.00326714E-05, 5.81094064E-05, 3.53246978E-05, 2.92667046E-05, 1.72944201E-05, -1.29259779E-05, -1.95585071E-05, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000]) FQ = np.flipud([-1.25266510E-07, -1.77205965E-08, 2.25621442E-08, 1.20601991E-08, -2.24871144E-09, -8.65546035E-09, 1.32086608E-08, 3.48950842E-08, 4.61437244E-09, 3.59271168E-09, 3.54269192E-09, 1.12591925E-09, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000 , 0.00000000, 0.00000000]) FU = np.flipud([6.96138741E-05, 2.54272982E-05, -4.23727352E-06, -2.25807025E-06, 5.97735743E-06, 1.29817499E-05, -7.07237768E-06, -5.06039614E-05, -8.67366180E-06, -1.08617351E-05, -1.97424633E-05, -1.05507343E-05, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000]) FV = np.zeros_like(FU) # Set thermodynamic constants to their defaults from Emanuel's code # so that we get same tendencies emanuel_convection.CPD=1005.7 emanuel_convection.CPV=1870.0 emanuel_convection.RV=461.5 emanuel_convection.RD=287.04 emanuel_convection.LV0=2.501E6 emanuel_convection.G=9.8 emanuel_convection.ROWL=1000.0 @pytest.mark.compiled @pytest.mark.fast def test_convect_tendencies(): # Temperatures in a single column state = climlab.column_state(num_lev=num_lev) state.Tatm[:] = T state['q'] = state.Tatm * 0. + Q state['U'] = state.Tatm * 0. + U state['V'] = state.Tatm * 0. + V assert hasattr(state, 'Tatm') assert hasattr(state, 'q') assert hasattr(state, 'U') assert hasattr(state, 'V') conv = emanuel_convection.EmanuelConvection(state=state, timestep=DELT) conv.step_forward() # Did we get all the correct output? assert conv.IFLAG == 1 # relative tolerance for these tests ... tol = 1E-5 assert conv.CBMF == pytest.approx(3.10377218E-02, rel=tol) tend = conv.tendencies assert FT == pytest.approx(tend['Tatm'], rel=tol) assert FQ == pytest.approx(tend['q'], rel=tol) assert FU == pytest.approx(tend['U'], rel=tol) assert FV == pytest.approx(tend['V'], rel=tol) @pytest.mark.compiled @pytest.mark.fast def test_multidim_tendencies(): # Same test just repeated in two parallel columns num_lat = 2 state = climlab.column_state(num_lev=num_lev, num_lat=num_lat) state['q'] = state.Tatm * 0. #+ Q state['U'] = state.Tatm * 0. #+ U state['V'] = state.Tatm * 0. #+ V for i in range(num_lat): state.Tatm[i,:] = T state['q'][i,:] += Q state['U'][i,:] += U state['V'][i,:] += V assert hasattr(state, 'Tatm') assert hasattr(state, 'q') assert hasattr(state, 'U') assert hasattr(state, 'V') conv = emanuel_convection.EmanuelConvection(state=state, timestep=DELT) conv.step_forward() # Did we get all the correct output? assert np.all(conv.IFLAG == 1) # relative tolerance for these tests ... tol = 1E-5 assert np.all(conv.CBMF == pytest.approx(3.10377218E-02, rel=tol)) tend = conv.tendencies assert np.tile(FT,(num_lat,1)) == pytest.approx(tend['Tatm'], rel=tol) assert np.tile(FQ,(num_lat,1)) == pytest.approx(tend['q'], rel=tol) assert np.tile(FU,(num_lat,1)) == pytest.approx(tend['U'], rel=tol) assert np.tile(FV,(num_lat,1)) == pytest.approx(tend['V'], rel=tol) @pytest.mark.compiled @pytest.mark.fast def test_rcm_emanuel(): num_lev = 30 water_depth = 5. # Temperatures in a single column state = climlab.column_state(num_lev=num_lev, water_depth=water_depth) # Initialize a nearly dry column (small background stratospheric humidity) state['q'] = np.ones_like(state.Tatm) * 5.E-6 # ASYNCHRONOUS COUPLING -- the radiation uses a much longer timestep short_timestep = climlab.constants.seconds_per_hour # The top-level model model = climlab.TimeDependentProcess(name='Radiative-Convective Model', state=state, timestep=short_timestep) # Radiation coupled to water vapor rad = climlab.radiation.RRTMG(name='Radiation', state=state, specific_humidity=state.q, albedo=0.3, timestep=24*short_timestep) # Convection scheme -- water vapor is a state variable conv = climlab.convection.EmanuelConvection(name='Convection', state=state, timestep=short_timestep) # Surface heat flux processes shf = climlab.surface.SensibleHeatFlux(name='SHF', state=state, Cd=0.5E-3, timestep=climlab.constants.seconds_per_hour) lhf = climlab.surface.LatentHeatFlux(name='LHF', state=state, Cd=0.5E-3, timestep=short_timestep) # Couple all the submodels together for proc in [rad, conv, shf, lhf]: model.add_subprocess(proc.name, proc) model.step_forward() to_xarray(model)
mit
1,299,065,267,706,858,000
42.691781
86
0.614046
false
2.680252
true
false
false
antofik/Wartech
WartechLogic/map/views.py
1
3743
# coding=utf-8 from django.db import transaction from django.http import HttpResponse import json from django.template import RequestContext from django.shortcuts import render_to_response from django.db.models import Q from models import * from random import randint from PIL import Image def JsonResponse(request, data): mimetype = 'text/plain' if 'HTTP_ACCEPT_ENCODING' in request.META.keys(): if "application/json" in request.META['HTTP_ACCEPT_ENCODING']: mimetype = 'application/json' response = HttpResponse(json.dumps(data), content_type=mimetype) response["Access-Control-Allow-Credentials"] = "true" response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" response["Access-Control-Max-Age"] = "86400" if request.method == "OPTIONS": response["Access-Control-Allow-Headers"] = "origin, content-type, x-requested-with, accept, authorization" return response def create_roughness(heights): for i in xrange(len(heights)): r = randint(0, 20) if r > 19: heights[i] += 3 elif r > 18: heights[i] -= 3 elif r > 16: heights[i] += 2 elif r > 14: heights[i] -= 2 elif r > 11: heights[i] += 1 elif r > 8: heights[i] -= 1 heights[i] = max(0, min(7, heights[i])) for x in xrange(1,99): for y in xrange(1,99): heights[y*100+x] = (heights[y*100+x] + heights[y*100+x+1] + heights[y*100+x-1] + heights[y*100+x+100] + heights[y*100+x-100])/5 def create_mountains(heights): def coordinates(width=0): return randint(width, 99-width), randint(width, 99-width) for i in xrange(randint(0, 100)): x, y = coordinates() def create_ravines(heights): pass def generate_map(sx, sy): """ sx,sy=0..999 """ sx, sy = int(sx), int(sy) im = Image.open("media/images/map.png") pixels = im.load() pixel = pixels[sx, sy] material = Materials.Water height = 0 if pixel == 75: material = Materials.Water height = 0 elif pixel == 2: material = Materials.Soil height = 2 elif pixel == 3: material = Materials.Soil height = 4 elif pixel == 5: material = Materials.Soil height = 6 elif pixel == 6: material = Materials.Soil height = 7 m = [material] * 10000 for x in xrange(10): for y in xrange(10): point = (sx*10 + x) * 1000000 + (sy*10 + y) heights = [height] * 10000 if material == Materials.Soil: create_roughness(heights) create_mountains(heights) create_ravines(heights) elif material == Materials.Rock: create_roughness(heights) create_mountains(heights) elif material == Materials.Sand: create_roughness(heights) m = ''.join(m) heights = ''.join(map(str, heights)) MapTile(point=point, type=4, data=m, heights=heights).save() def get_map(sx, sy): """ x=0..9999, y=0.9999 result contain 100x100 cells """ point = sx * 1000000 + sy try: m = MapTile.objects.get(Q(point=point), Q(type=4)) except MapTile.DoesNotExist: generate_map(sx//10, sy//10) m = MapTile.objects.get(Q(point=point), Q(type=4)) return m def get(request): sx = int(request.GET.get('x', 0)) sy = int(request.GET.get('y', 0)) map = get_map(sx, sy) jsonData = {'map': map.data, 'heights': map.heights} return JsonResponse(request, jsonData) #3, 2, 75, 5, 6
mit
8,021,711,613,826,038,000
27.792308
139
0.576543
false
3.421389
false
false
false
ak-67/ZeroNet
src/Db/Db.py
1
12059
import sqlite3 import json import time import logging import re import os import gevent from DbCursor import DbCursor opened_dbs = [] # Close idle databases to save some memory def dbCleanup(): while 1: time.sleep(60 * 5) for db in opened_dbs[:]: if time.time() - db.last_query_time > 60 * 3: db.close() gevent.spawn(dbCleanup) class Db: def __init__(self, schema, db_path): self.db_path = db_path self.db_dir = os.path.dirname(db_path) + "/" self.schema = schema self.schema["version"] = self.schema.get("version", 1) self.conn = None self.cur = None self.log = logging.getLogger("Db:%s" % schema["db_name"]) self.table_names = None self.collect_stats = False self.query_stats = {} self.db_keyvalues = {} self.last_query_time = time.time() def __repr__(self): return "<Db:%s>" % self.db_path def connect(self): if self not in opened_dbs: opened_dbs.append(self) self.log.debug("Connecting to %s (sqlite version: %s)..." % (self.db_path, sqlite3.version)) if not os.path.isdir(self.db_dir): # Directory not exist yet os.makedirs(self.db_dir) self.log.debug("Created Db path: %s" % self.db_dir) if not os.path.isfile(self.db_path): self.log.debug("Db file not exist yet: %s" % self.db_path) self.conn = sqlite3.connect(self.db_path) self.conn.row_factory = sqlite3.Row self.conn.isolation_level = None self.cur = self.getCursor() # We need more speed then security self.cur.execute("PRAGMA journal_mode = WAL") self.cur.execute("PRAGMA journal_mode = MEMORY") self.cur.execute("PRAGMA synchronous = OFF") # Execute query using dbcursor def execute(self, query, params=None): self.last_query_time = time.time() if not self.conn: self.connect() return self.cur.execute(query, params) def close(self): self.log.debug("Closing, opened: %s" % opened_dbs) if self in opened_dbs: opened_dbs.remove(self) if self.cur: self.cur.close() if self.conn: self.conn.close() self.conn = None self.cur = None # Gets a cursor object to database # Return: Cursor class def getCursor(self): if not self.conn: self.connect() return DbCursor(self.conn, self) # Get the table version # Return: Table version or None if not exist def getTableVersion(self, table_name): """if not self.table_names: # Get existing table names res = self.cur.execute("SELECT name FROM sqlite_master WHERE type='table'") self.table_names = [row["name"] for row in res] if table_name not in self.table_names: return False else:""" if not self.db_keyvalues: # Get db keyvalues try: res = self.cur.execute("SELECT * FROM keyvalue WHERE json_id=0") # json_id = 0 is internal keyvalues except sqlite3.OperationalError, err: # Table not exist self.log.debug("Query error: %s" % err) return False for row in res: self.db_keyvalues[row["key"]] = row["value"] return self.db_keyvalues.get("table.%s.version" % table_name, 0) # Check Db tables # Return: <list> Changed table names def checkTables(self): s = time.time() changed_tables = [] cur = self.getCursor() cur.execute("BEGIN") # Check internal tables # Check keyvalue table changed = cur.needTable("keyvalue", [ ["keyvalue_id", "INTEGER PRIMARY KEY AUTOINCREMENT"], ["key", "TEXT"], ["value", "INTEGER"], ["json_id", "INTEGER REFERENCES json (json_id)"], ], [ "CREATE UNIQUE INDEX key_id ON keyvalue(json_id, key)" ], version=self.schema["version"]) if changed: changed_tables.append("keyvalue") # Check json table if self.schema["version"] == 1: changed = cur.needTable("json", [ ["json_id", "INTEGER PRIMARY KEY AUTOINCREMENT"], ["path", "VARCHAR(255)"] ], [ "CREATE UNIQUE INDEX path ON json(path)" ], version=self.schema["version"]) else: changed = cur.needTable("json", [ ["json_id", "INTEGER PRIMARY KEY AUTOINCREMENT"], ["directory", "VARCHAR(255)"], ["file_name", "VARCHAR(255)"] ], [ "CREATE UNIQUE INDEX path ON json(directory, file_name)" ], version=self.schema["version"]) if changed: changed_tables.append("json") # Check schema tables for table_name, table_settings in self.schema["tables"].items(): changed = cur.needTable( table_name, table_settings["cols"], table_settings["indexes"], version=table_settings["schema_changed"] ) if changed: changed_tables.append(table_name) cur.execute("COMMIT") self.log.debug("Db check done in %.3fs, changed tables: %s" % (time.time() - s, changed_tables)) return changed_tables # Load json file to db # Return: True if matched def loadJson(self, file_path, file=None, cur=None): if not file_path.startswith(self.db_dir): return False # Not from the db dir: Skipping relative_path = re.sub("^%s" % self.db_dir, "", file_path) # File path realative to db file # Check if filename matches any of mappings in schema matched_maps = [] for match, map_settings in self.schema["maps"].items(): if re.match(match, relative_path): matched_maps.append(map_settings) # No match found for the file if not matched_maps: return False # Load the json file if not file: file = open(file_path) data = json.load(file) # No cursor specificed if not cur: cur = self.getCursor() cur.execute("BEGIN") cur.logging = False commit_after_done = True else: commit_after_done = False # Row for current json file json_row = cur.getJsonRow(relative_path) # Check matched mappings in schema for map in matched_maps: # Insert non-relational key values if map.get("to_keyvalue"): # Get current values res = cur.execute("SELECT * FROM keyvalue WHERE json_id = ?", (json_row["json_id"],)) current_keyvalue = {} current_keyvalue_id = {} for row in res: current_keyvalue[row["key"]] = row["value"] current_keyvalue_id[row["key"]] = row["keyvalue_id"] for key in map["to_keyvalue"]: if key not in current_keyvalue: # Keyvalue not exist yet in the db cur.execute( "INSERT INTO keyvalue ?", {"key": key, "value": data.get(key), "json_id": json_row["json_id"]} ) elif data.get(key) != current_keyvalue[key]: # Keyvalue different value cur.execute( "UPDATE keyvalue SET value = ? WHERE keyvalue_id = ?", (data.get(key), current_keyvalue_id[key]) ) """ for key in map.get("to_keyvalue", []): cur.execute("INSERT OR REPLACE INTO keyvalue ?", {"key": key, "value": data.get(key), "json_id": json_row["json_id"]} ) """ # Insert data to tables for table_settings in map.get("to_table", []): if isinstance(table_settings, dict): # Custom settings table_name = table_settings["table"] # Table name to insert datas node = table_settings.get("node", table_name) # Node keyname in data json file key_col = table_settings.get("key_col") # Map dict key as this col val_col = table_settings.get("val_col") # Map dict value as this col import_cols = table_settings.get("import_cols") replaces = table_settings.get("replaces") else: # Simple settings table_name = table_settings node = table_settings key_col = None val_col = None import_cols = None replaces = None cur.execute("DELETE FROM %s WHERE json_id = ?" % table_name, (json_row["json_id"],)) if node not in data: continue if key_col: # Map as dict for key, val in data[node].iteritems(): if val_col: # Single value cur.execute( "INSERT OR REPLACE INTO %s ?" % table_name, {key_col: key, val_col: val, "json_id": json_row["json_id"]} ) else: # Multi value if isinstance(val, dict): # Single row row = val if import_cols: row = {key: row[key] for key in import_cols} # Filter row by import_cols row[key_col] = key # Replace in value if necessary if replaces: for replace_key, replace in replaces.iteritems(): if replace_key in row: for replace_from, replace_to in replace.iteritems(): row[replace_key] = row[replace_key].replace(replace_from, replace_to) row["json_id"] = json_row["json_id"] cur.execute("INSERT OR REPLACE INTO %s ?" % table_name, row) else: # Multi row for row in val: row[key_col] = key row["json_id"] = json_row["json_id"] cur.execute("INSERT OR REPLACE INTO %s ?" % table_name, row) else: # Map as list for row in data[node]: row["json_id"] = json_row["json_id"] cur.execute("INSERT OR REPLACE INTO %s ?" % table_name, row) if commit_after_done: cur.execute("COMMIT") return True if __name__ == "__main__": s = time.time() console_log = logging.StreamHandler() logging.getLogger('').setLevel(logging.DEBUG) logging.getLogger('').addHandler(console_log) console_log.setLevel(logging.DEBUG) dbjson = Db(json.load(open("zerotalk.schema.json")), "data/users/zerotalk.db") dbjson.collect_stats = True dbjson.checkTables() cur = dbjson.getCursor() cur.execute("BEGIN") cur.logging = False dbjson.loadJson("data/users/content.json", cur=cur) for user_dir in os.listdir("data/users"): if os.path.isdir("data/users/%s" % user_dir): dbjson.loadJson("data/users/%s/data.json" % user_dir, cur=cur) # print ".", cur.logging = True cur.execute("COMMIT") print "Done in %.3fs" % (time.time() - s) for query, stats in sorted(dbjson.query_stats.items()): print "-", query, stats
gpl-2.0
8,408,613,494,907,893,000
38.02589
117
0.509495
false
4.178448
false
false
false
OpenSourcePolicyCenter/taxdata
puf_stage1/factors_finalprep.py
1
3867
""" Transform Stage_I_factors.csv (written by the stage1.py script) and benefit_growth_rates.csv into growfactors.csv (used by Tax-Calculator). """ import numpy as np import pandas as pd import os # pylint: disable=invalid-name CUR_PATH = os.path.abspath(os.path.dirname(__file__)) first_benefit_year = 2014 inben_filename = os.path.join(CUR_PATH, 'benefit_growth_rates.csv') first_data_year = 2011 infac_filename = os.path.join(CUR_PATH, 'Stage_I_factors.csv') output_filename = os.path.join(CUR_PATH, 'growfactors.csv') # -------------------------------------------------------------------------- # read in raw average benefit amounts by year and # convert into "one plus annual proportion change" factors bgr_all = pd.read_csv(inben_filename, index_col='YEAR') bnames = ['mcare', 'mcaid', 'ssi', 'snap', 'wic', 'housing', 'tanf', 'vet'] keep_cols = ['{}_average_benefit'.format(bname) for bname in bnames] bgr_raw = bgr_all[keep_cols] gf_bnames = ['ABEN{}'.format(bname.upper()) for bname in bnames] bgr_raw.columns = gf_bnames bgf = 1.0 + bgr_raw.astype('float64').pct_change() # specify first row values because pct_change() leaves first year undefined for var in list(bgf): bgf[var][first_benefit_year] = 1.0 # add rows of ones for years from first_data_year thru first_benefit_year-1 ones = [1.0] * len(bnames) for year in range(first_data_year, first_benefit_year): row = pd.DataFrame(data=[ones], columns=gf_bnames, index=[year]) bgf = pd.concat([bgf, row], verify_integrity=True) bgf.sort_index(inplace=True) # round converted factors to six decimal digits of accuracy bgf = bgf.round(6) # -------------------------------------------------------------------------- # read in blowup factors used internally in taxdata repository data = pd.read_csv(infac_filename, index_col='YEAR') # convert some aggregate factors into per-capita factors elderly_pop = data['APOPSNR'] data['ASOCSEC'] = data['ASOCSEC'] / elderly_pop pop = data['APOPN'] data['AWAGE'] = data['AWAGE'] / pop data['ATXPY'] = data['ATXPY'] / pop data['ASCHCI'] = data['ASCHCI'] / pop data['ASCHCL'] = data['ASCHCL'] / pop data['ASCHF'] = data['ASCHF'] / pop data['AINTS'] = data['AINTS'] / pop data['ADIVS'] = data['ADIVS'] / pop data['ASCHEI'] = data['ASCHEI'] / pop data['ASCHEL'] = data['ASCHEL'] / pop data['ACGNS'] = data['ACGNS'] / pop data['ABOOK'] = data['ABOOK'] / pop data['ABENEFITS'] = data['ABENEFITS'] / pop data.rename(columns={'ABENEFITS': 'ABENOTHER'}, inplace=True) # convert factors into "one plus annual proportion change" format data = 1.0 + data.pct_change() # specify first row values because pct_change() leaves first year undefined for var in list(data): data[var][first_data_year] = 1.0 # round converted factors to six decimal digits of accuracy data = data.round(6) # -------------------------------------------------------------------------- # combine data and bgf DataFrames gfdf = pd.concat([data, bgf], axis='columns', verify_integrity=True) # -------------------------------------------------------------------------- # delete from data the variables not used by Tax-Calculator (TC) TC_USED_VARS = set(['ABOOK', 'ACGNS', 'ACPIM', 'ACPIU', 'ADIVS', 'AINTS', 'AIPD', 'ASCHCI', 'ASCHCL', 'ASCHEI', 'ASCHEL', 'ASCHF', 'ASOCSEC', 'ATXPY', 'AUCOMP', 'AWAGE', 'ABENOTHER'] + gf_bnames) ALL_VARS = set(list(gfdf)) TC_UNUSED_VARS = ALL_VARS - TC_USED_VARS gfdf = gfdf.drop(TC_UNUSED_VARS, axis=1) # write out grow factors used in blowup logic in Tax-Calculator repository gfdf.to_csv(output_filename, index_label='YEAR')
mit
-5,736,347,475,636,523,000
36.543689
76
0.587794
false
3.230576
false
false
false
MatthieuDartiailh/pyvisa-sim
pyvisa-sim/parser.py
1
8388
# -*- coding: utf-8 -*- """ pyvisa-sim.parser ~~~~~~~~~~~~~~~~~ Parser function :copyright: 2014 by PyVISA-sim Authors, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ import os from io import open, StringIO from contextlib import closing from traceback import format_exc import pkg_resources import yaml from .component import NoResponse from .devices import Devices, Device from .channels import Channels def _ver_to_tuple(ver): return tuple(map(int, (ver.split(".")))) #: Version of the specification SPEC_VERSION = '1.1' SPEC_VERSION_TUPLE = _ver_to_tuple(SPEC_VERSION) class SimpleChainmap(object): """Combine multiple mappings for sequential lookup. """ def __init__(self, *maps): self._maps = maps def __getitem__(self, key): for mapping in self._maps: try: return mapping[key] except KeyError: pass raise KeyError(key) def _s(s): """Strip white spaces """ if s is NoResponse: return s return s.strip(' ') def _get_pair(dd): """Return a pair from a dialogue dictionary. :param dd: Dialogue dictionary. :type dd: Dict[str, str] :return: (query, response) :rtype: (str, str) """ return _s(dd['q']), _s(dd.get('r', NoResponse)) def _get_triplet(dd): """Return a triplet from a dialogue dictionary. :param dd: Dialogue dictionary. :type dd: Dict[str, str] :return: (query, response, error response) :rtype: (str, str | NoResponse, str | NoResponse) """ return _s(dd['q']), _s(dd.get('r', NoResponse)), _s(dd.get('e', NoResponse)) def _load(content_or_fp): """YAML Parse a file or str and check version. """ try: data = yaml.load(content_or_fp, Loader=yaml.loader.BaseLoader) except Exception as e: raise type(e)('Malformed yaml file:\n%r' % format_exc()) try: ver = data['spec'] except: raise ValueError('The file does not specify a spec version') try: ver = tuple(map(int, (ver.split(".")))) except: raise ValueError("Invalid spec version format. Expect 'X.Y'" " (X and Y integers), found %s" % ver) if ver > SPEC_VERSION_TUPLE: raise ValueError('The spec version of the file is ' '%s but the parser is %s. ' 'Please update pyvisa-sim.' % (ver, SPEC_VERSION)) return data def parse_resource(name): """Parse a resource file """ with closing(pkg_resources.resource_stream(__name__, name)) as fp: rbytes = fp.read() return _load(StringIO(rbytes.decode('utf-8'))) def parse_file(fullpath): """Parse a file """ with open(fullpath, encoding='utf-8') as fp: return _load(fp) def update_component(name, comp, component_dict): """Get a component from a component dict. """ for dia in component_dict.get('dialogues', ()): try: comp.add_dialogue(*_get_pair(dia)) except Exception as e: msg = 'In device %s, malformed dialogue %s\n%r' raise Exception(msg % (name, dia, e)) for prop_name, prop_dict in component_dict.get('properties', {}).items(): try: getter = (_get_pair(prop_dict['getter']) if 'getter' in prop_dict else None) setter = (_get_triplet(prop_dict['setter']) if 'setter' in prop_dict else None) comp.add_property(prop_name, prop_dict.get('default', ''), getter, setter, prop_dict.get('specs', {})) except Exception as e: msg = 'In device %s, malformed property %s\n%r' raise type(e)(msg % (name, prop_name, format_exc())) def get_bases(definition_dict, loader): """Collect dependencies. """ bases = definition_dict.get('bases', ()) if bases: bases = (loader.get_comp_dict(required_version=SPEC_VERSION_TUPLE[0], **b) for b in bases) return SimpleChainmap(definition_dict, *bases) else: return definition_dict def get_channel(device, ch_name, channel_dict, loader, resource_dict): """Get a channels from a channels dictionary. :param name: name of the device :param device_dict: device dictionary :rtype: Device """ channel_dict = get_bases(channel_dict, loader) r_ids = resource_dict.get('channel_ids', {}).get(ch_name, []) ids = r_ids if r_ids else channel_dict.get('ids', {}) can_select = False if channel_dict.get('can_select') == 'False' else True channels = Channels(device, ids, can_select) update_component(ch_name, channels, channel_dict) return channels def get_device(name, device_dict, loader, resource_dict): """Get a device from a device dictionary. :param name: name of the device :param device_dict: device dictionary :rtype: Device """ device = Device(name, device_dict.get('delimiter', ';').encode('utf-8')) device_dict = get_bases(device_dict, loader) err = device_dict.get('error', {}) device.add_error_handler(err) for itype, eom_dict in device_dict.get('eom', {}).items(): device.add_eom(itype, *_get_pair(eom_dict)) update_component(name, device, device_dict) for ch_name, ch_dict in device_dict.get('channels', {}).items(): device.add_channels(ch_name, get_channel(device, ch_name, ch_dict, loader, resource_dict)) return device class Loader(object): def __init__(self, filename, bundled): # (absolute path / resource name / None, bundled) -> dict # :type: dict[str | None, bool, dict] self._cache = {} self.data = self._load(filename, bundled, SPEC_VERSION_TUPLE[0]) self._filename = filename self._bundled = bundled self._basepath = os.path.dirname(filename) def load(self, filename, bundled, parent, required_version): if self._bundled and not bundled: msg = 'Only other bundled files can be loaded from bundled files.' raise ValueError(msg) if parent is None: parent = self._filename base = os.path.dirname(parent) filename = os.path.join(base, filename) return self._load(filename, bundled, required_version) def _load(self, filename, bundled, required_version): if (filename, bundled) in self._cache: return self._cache[(filename, bundled)] if bundled: data = parse_resource(filename) else: data = parse_file(filename) ver = _ver_to_tuple(data['spec'])[0] if ver != required_version: raise ValueError('Invalid version in %s (bundled = %s). ' 'Expected %s, found %s,' % (filename, bundled, required_version, ver) ) self._cache[(filename, bundled)] = data return data def get_device_dict(self, device, filename, bundled, required_version): if filename is None: data = self.data else: data = self.load(filename, bundled, required_version) return data['devices'][device] def get_devices(filename, bundled): """Get a Devices object from a file. :param filename: full path of the file to parse or name of the resource. :param is_resource: boolean indicating if it is a resource. :rtype: Devices """ loader = Loader(filename, bundled) data = loader.data devices = Devices() # Iterate through the resources and generate each individual device # on demand. for resource_name, resource_dict in data.get('resources', {}).items(): device_name = resource_dict['device'] dd = loader.get_device_dict(device_name, resource_dict.get('filename', None), resource_dict.get('bundled', False), required_version=SPEC_VERSION_TUPLE[0]) devices.add_device(resource_name, get_device(device_name, dd, loader, resource_dict)) return devices
mit
8,398,695,646,469,128,000
27.147651
80
0.580472
false
3.837145
false
false
false
npadgen/read-a-script
utils.py
1
1176
from enum import Enum import jouvence.document class ElementType(Enum): ACTION = jouvence.document.TYPE_ACTION CENTERED_ACTION = jouvence.document.TYPE_CENTEREDACTION CHARACTER = jouvence.document.TYPE_CHARACTER DIALOG = jouvence.document.TYPE_DIALOG PARENTHETICAL = jouvence.document.TYPE_PARENTHETICAL TRANSITION = jouvence.document.TYPE_TRANSITION LYRICS = jouvence.document.TYPE_LYRICS PAGE_BREAK = jouvence.document.TYPE_PAGEBREAK SECTION = jouvence.document.TYPE_SECTION SYNOPSIS = jouvence.document.TYPE_SYNOPSIS def mixrange(s): """ Expand a range which looks like "1-3,6,8-10" to [1, 2, 3, 6, 8, 9, 10] """ r = [] for i in s.split(","): if "-" not in i: r.append(int(i)) else: l, h = list(map(int, i.split("-"))) r += list(range(l, h + 1)) return r def merge(dict_1, dict_2): """Merge two dictionaries. Values that evaluate to true take priority over falsy values. `dict_1` takes priority over `dict_2`. """ return dict((str(key), dict_1.get(key) or dict_2.get(key)) for key in set(dict_2) | set(dict_1))
bsd-3-clause
-8,294,019,624,756,107,000
27
74
0.632653
false
3.0625
false
false
false
ngageoint/scale
scale/job/test/messages/test_uncancel_jobs.py
1
7505
from __future__ import unicode_literals import datetime import django from django.utils.timezone import now from django.test import TransactionTestCase from job.messages.uncancel_jobs import UncancelJobs from job.models import Job from job.test import utils as job_test_utils from recipe.test import utils as recipe_test_utils class TestUncancelJobs(TransactionTestCase): def setUp(self): django.setup() def test_json(self): """Tests coverting an UncancelJobs message to and from JSON""" old_when = now() when = old_when + datetime.timedelta(minutes=60) job_1 = job_test_utils.create_job(num_exes=0, status='PENDING', last_status_change=old_when) job_2 = job_test_utils.create_job(num_exes=0, status='CANCELED', last_status_change=old_when) job_3 = job_test_utils.create_job(num_exes=1, status='CANCELED', last_status_change=old_when) job_4 = job_test_utils.create_job(num_exes=1, status='FAILED', last_status_change=old_when) job_ids = [job_1.id, job_2.id, job_3.id, job_4.id] # Add jobs to message message = UncancelJobs() message.when = when if message.can_fit_more(): message.add_job(job_1.id) if message.can_fit_more(): message.add_job(job_2.id) if message.can_fit_more(): message.add_job(job_3.id) if message.can_fit_more(): message.add_job(job_4.id) # Convert message to JSON and back, and then execute message_json_dict = message.to_json() new_message = UncancelJobs.from_json(message_json_dict) result = new_message.execute() self.assertTrue(result) jobs = Job.objects.filter(id__in=job_ids).order_by('id') # Job 1 should not be updated because it was not CANCELED self.assertEqual(jobs[0].status, 'PENDING') self.assertEqual(jobs[0].last_status_change, old_when) # Job 2 should be uncanceled self.assertEqual(jobs[1].status, 'PENDING') self.assertEqual(jobs[1].last_status_change, when) # Job 3 should not be updated since it has already been queued self.assertEqual(jobs[2].status, 'CANCELED') self.assertEqual(jobs[2].last_status_change, old_when) # Job 4 should not be updated because it was not CANCELED self.assertEqual(jobs[3].status, 'FAILED') self.assertEqual(jobs[3].last_status_change, old_when) def test_execute(self): """Tests calling UncancelJobs.execute() successfully""" old_when = now() when = old_when + datetime.timedelta(minutes=60) recipe = recipe_test_utils.create_recipe() job_1 = job_test_utils.create_job(num_exes=0, status='PENDING', last_status_change=old_when) job_2 = job_test_utils.create_job(num_exes=0, status='CANCELED', last_status_change=old_when, recipe=recipe) job_3 = job_test_utils.create_job(num_exes=1, status='CANCELED', last_status_change=old_when) job_4 = job_test_utils.create_job(num_exes=1, status='FAILED', last_status_change=old_when) job_ids = [job_1.id, job_2.id, job_3.id, job_4.id] recipe_test_utils.create_recipe_job(recipe=recipe, job=job_2) # Add jobs to message message = UncancelJobs() message.when = when if message.can_fit_more(): message.add_job(job_1.id) if message.can_fit_more(): message.add_job(job_2.id) if message.can_fit_more(): message.add_job(job_3.id) if message.can_fit_more(): message.add_job(job_4.id) # Execute message result = message.execute() self.assertTrue(result) from recipe.diff.forced_nodes import ForcedNodes from recipe.diff.json.forced_nodes_v6 import convert_forced_nodes_to_v6 forced_nodes = ForcedNodes() forced_nodes.set_all_nodes() forced_nodes_dict = convert_forced_nodes_to_v6(forced_nodes).get_dict() jobs = Job.objects.filter(id__in=job_ids).order_by('id') # Job 1 should not be updated because it was not CANCELED self.assertEqual(jobs[0].status, 'PENDING') self.assertEqual(jobs[0].last_status_change, old_when) # Job 2 should be uncanceled self.assertEqual(jobs[1].status, 'PENDING') self.assertEqual(jobs[1].last_status_change, when) # Job 3 should not be updated since it has already been queued self.assertEqual(jobs[2].status, 'CANCELED') self.assertEqual(jobs[2].last_status_change, old_when) # Job 4 should not be updated because it was not CANCELED self.assertEqual(jobs[3].status, 'FAILED') self.assertEqual(jobs[3].last_status_change, old_when) # Make sure update_recipe and update_recipe_metrics messages were created self.assertEqual(len(message.new_messages), 2) update_recipe_msg = None update_recipe_metrics_msg = None for msg in message.new_messages: if msg.type == 'update_recipe': update_recipe_msg = msg elif msg.type == 'update_recipe_metrics': update_recipe_metrics_msg = msg self.assertIsNotNone(update_recipe_msg) self.assertIsNotNone(update_recipe_metrics_msg) self.assertEqual(update_recipe_msg.root_recipe_id, recipe.id) self.assertDictEqual(convert_forced_nodes_to_v6(update_recipe_msg.forced_nodes).get_dict(), forced_nodes_dict) self.assertListEqual(update_recipe_metrics_msg._recipe_ids, [recipe.id]) # Test executing message again newer_when = when + datetime.timedelta(minutes=60) message_json_dict = message.to_json() message = UncancelJobs.from_json(message_json_dict) message.when = newer_when result = message.execute() self.assertTrue(result) jobs = Job.objects.filter(id__in=job_ids).order_by('id') # Job 1 should not be updated because it was not CANCELED self.assertEqual(jobs[0].status, 'PENDING') self.assertEqual(jobs[0].last_status_change, old_when) # Job 2 should not be updated since it already was last mexxage execution self.assertEqual(jobs[1].status, 'PENDING') self.assertEqual(jobs[1].last_status_change, when) # Job 3 should not be updated since it has already been queued self.assertEqual(jobs[2].status, 'CANCELED') self.assertEqual(jobs[2].last_status_change, old_when) # Job 4 should not be updated because it was not CANCELED self.assertEqual(jobs[3].status, 'FAILED') self.assertEqual(jobs[3].last_status_change, old_when) # Make sure update_recipe and update_recipe_metrics messages were created self.assertEqual(len(message.new_messages), 2) update_recipe_msg = None update_recipe_metrics_msg = None for msg in message.new_messages: if msg.type == 'update_recipe': update_recipe_msg = msg elif msg.type == 'update_recipe_metrics': update_recipe_metrics_msg = msg self.assertIsNotNone(update_recipe_msg) self.assertIsNotNone(update_recipe_metrics_msg) self.assertEqual(update_recipe_msg.root_recipe_id, recipe.id) self.assertDictEqual(convert_forced_nodes_to_v6(update_recipe_msg.forced_nodes).get_dict(), forced_nodes_dict) self.assertListEqual(update_recipe_metrics_msg._recipe_ids, [recipe.id])
apache-2.0
-4,129,883,464,434,995,700
44.484848
118
0.650366
false
3.601248
true
false
false
Jchase2/py-pubsubhubbub-subscriber
fffp.py
1
2310
#!/usr/local/bin/python # Copyright 2015 JChase II # # 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/>. # # Addition permissions upon request on a case by case basis. # # This is a pubsubhubbub subscriber that subscribes to and handles a youtube # channel subscription via the youtube API v.3 print('Content-type: text/html\n') # So print actually prints to the webpage. w import requests # Library for sending http requests. # imported to get raw data from GET and POST requests. import os import sys # Change these values to your own. a_topic = 'insert topic url to subscribe to here' a_callback = 'insert webhook url pointing to this script.' a_mode = 'subscribe' a_verify = 'sync' a_hub = 'https://pubsubhubbub.appspot.com/' # First, we send a subscription request to googles subscriber... payload = {'hub.callback': a_callback, 'hub.mode': a_mode, 'hub.verify': a_verify, 'hub.topic': a_topic} returned = requests.post(a_hub, data=payload) # Check to make sure the hub responds with 204 or 202 (verified or accepted) if returned != 204 or 202: print ("Hub did not return 204 or 202") print("Status code is: ",returned.status_code) print("Text Value: ", returned.text) sys.exit('Error!') # Next, the hub needs to verify we sent a subscription request. # It'll send a GET request to the webhook including details of the # subscription... Also a hub.challenge. We must serve a 200 status and # output hub.challenge in the response. Qdict = {} QString = os.getenv("QUERY_STRING") Qdict = dict(item.split("=") for item in QString.split("&")) plzCheckTopic = Qdict['hub.topic']; if (plzCheckTopic == a_topic): print(Qdict["hub.challenge"]) print("204") else: print("404")
gpl-2.0
3,373,865,880,684,674,000
32.478261
79
0.724242
false
3.581395
false
false
false
patrick246/tdesktop
Telegram/SourceFiles/mtproto/generate.py
1
45625
''' This file is part of Telegram Desktop, the official desktop version of Telegram messaging app, see https://telegram.org Telegram Desktop 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. It 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. In addition, as a special exception, the copyright holders give permission to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014 John Preston, https://desktop.telegram.org ''' import glob import re import binascii # define some checked flag convertions # the key flag type should be a subset of the value flag type # with exact the same names, then the key flag can be implicitly # casted to the value flag type parentFlags = {}; parentFlagsList = []; def addChildParentFlags(child, parent): parentFlagsList.append(child); parentFlags[child] = parent; addChildParentFlags('MTPDmessageService', 'MTPDmessage'); addChildParentFlags('MTPDupdateShortMessage', 'MTPDmessage'); addChildParentFlags('MTPDupdateShortChatMessage', 'MTPDmessage'); addChildParentFlags('MTPDupdateShortSentMessage', 'MTPDmessage'); addChildParentFlags('MTPDreplyKeyboardHide', 'MTPDreplyKeyboardMarkup'); addChildParentFlags('MTPDreplyKeyboardForceReply', 'MTPDreplyKeyboardMarkup'); addChildParentFlags('MTPDinputPeerNotifySettings', 'MTPDpeerNotifySettings'); addChildParentFlags('MTPDpeerNotifySettings', 'MTPDinputPeerNotifySettings'); addChildParentFlags('MTPDchannelForbidden', 'MTPDchannel'); # this is a map (key flags -> map (flag name -> flag bit)) # each key flag of parentFlags should be a subset of the value flag here parentFlagsCheck = {}; layer = ''; funcs = 0 types = 0; consts = 0 funcsNow = 0 enums = []; funcsDict = {}; funcsList = []; typesDict = {}; TypesDict = {}; typesList = []; boxed = {}; funcsText = ''; typesText = ''; dataTexts = ''; creatorProxyText = ''; inlineMethods = ''; textSerializeInit = ''; textSerializeMethods = ''; forwards = ''; forwTypedefs = ''; out = open('scheme_auto.h', 'w') out.write('/*\n'); out.write('Created from \'/SourceFiles/mtproto/scheme.tl\' by \'/SourceFiles/mtproto/generate.py\' script\n\n'); out.write('WARNING! All changes made in this file will be lost!\n\n'); out.write('This file is part of Telegram Desktop,\n'); out.write('the official desktop version of Telegram messaging app, see https://telegram.org\n'); out.write('\n'); out.write('Telegram Desktop is free software: you can redistribute it and/or modify\n'); out.write('it under the terms of the GNU General Public License as published by\n'); out.write('the Free Software Foundation, either version 3 of the License, or\n'); out.write('(at your option) any later version.\n'); out.write('\n'); out.write('It is distributed in the hope that it will be useful,\n'); out.write('but WITHOUT ANY WARRANTY; without even the implied warranty of\n'); out.write('MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n'); out.write('GNU General Public License for more details.\n'); out.write('\n'); out.write('In addition, as a special exception, the copyright holders give permission\n'); out.write('to link the code of portions of this program with the OpenSSL library.\n'); out.write('\n'); out.write('Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE\n'); out.write('Copyright (c) 2014 John Preston, https://desktop.telegram.org\n'); out.write('*/\n'); out.write('#pragma once\n\n#include "mtproto/core_types.h"\n'); with open('scheme.tl') as f: for line in f: layerline = re.match(r'// LAYER (\d+)', line) if (layerline): layer = 'static constexpr mtpPrime CurrentLayer = ' + layerline.group(1) + ';'; nocomment = re.match(r'^(.*?)//', line) if (nocomment): line = nocomment.group(1); if (re.match(r'\-\-\-functions\-\-\-', line)): funcsNow = 1; continue; if (re.match(r'\-\-\-types\-\-\-', line)): funcsNow = 0; continue; if (re.match(r'^\s*$', line)): continue; nametype = re.match(r'([a-zA-Z\.0-9_]+)#([0-9a-f]+)([^=]*)=\s*([a-zA-Z\.<>0-9_]+);', line); if (not nametype): if (not re.match(r'vector#1cb5c415 \{t:Type\} # \[ t \] = Vector t;', line)): print('Bad line found: ' + line); continue; name = nametype.group(1); nameInd = name.find('.'); if (nameInd >= 0): Name = name[0:nameInd] + '_' + name[nameInd + 1:nameInd + 2].upper() + name[nameInd + 2:]; name = name.replace('.', '_'); else: Name = name[0:1].upper() + name[1:]; typeid = nametype.group(2); while (len(typeid) > 0 and typeid[0] == '0'): typeid = typeid[1:]; if (len(typeid) == 0): typeid = '0'; typeid = '0x' + typeid; cleanline = nametype.group(1) + nametype.group(3) + '= ' + nametype.group(4); cleanline = re.sub(r' [a-zA-Z0-9_]+\:flags\.[0-9]+\?true', '', cleanline); cleanline = cleanline.replace('<', ' ').replace('>', ' ').replace(' ', ' '); cleanline = re.sub(r'^ ', '', cleanline); cleanline = re.sub(r' $', '', cleanline); cleanline = cleanline.replace(':bytes ', ':string '); cleanline = cleanline.replace('?bytes ', '?string '); cleanline = cleanline.replace('{', ''); cleanline = cleanline.replace('}', ''); countTypeId = binascii.crc32(binascii.a2b_qp(cleanline)); if (countTypeId < 0): countTypeId += 2 ** 32; countTypeId = '0x' + re.sub(r'^0x|L$', '', hex(countTypeId)); if (typeid != countTypeId): print('Warning: counted ' + countTypeId + ' mismatch with provided ' + typeid + ' (' + cleanline + ')'); continue; params = nametype.group(3); restype = nametype.group(4); if (restype.find('<') >= 0): templ = re.match(r'^([vV]ector<)([A-Za-z0-9\._]+)>$', restype); if (templ): vectemplate = templ.group(2); if (re.match(r'^[A-Z]', vectemplate) or re.match(r'^[a-zA-Z0-9]+_[A-Z]', vectemplate)): restype = templ.group(1) + 'MTP' + vectemplate.replace('.', '_') + '>'; elif (vectemplate == 'int' or vectemplate == 'long' or vectemplate == 'string'): restype = templ.group(1) + 'MTP' + vectemplate.replace('.', '_') + '>'; else: foundmeta = ''; for metatype in typesDict: for typedata in typesDict[metatype]: if (typedata[0] == vectemplate): foundmeta = metatype; break; if (len(foundmeta) > 0): break; if (len(foundmeta) > 0): ptype = templ.group(1) + 'MTP' + foundmeta.replace('.', '_') + '>'; else: print('Bad vector param: ' + vectemplate); continue; else: print('Bad template type: ' + restype); continue; resType = restype.replace('.', '_'); if (restype.find('.') >= 0): parts = re.match(r'([a-z]+)\.([A-Z][A-Za-z0-9<>\._]+)', restype) if (parts): restype = parts.group(1) + '_' + parts.group(2)[0:1].lower() + parts.group(2)[1:]; else: print('Bad result type name with dot: ' + restype); continue; else: if (re.match(r'^[A-Z]', restype)): restype = restype[:1].lower() + restype[1:]; else: print('Bad result type name: ' + restype); continue; boxed[resType] = restype; boxed[Name] = name; enums.append('\tmtpc_' + name + ' = ' + typeid); paramsList = params.strip().split(' '); prms = {}; conditions = {}; trivialConditions = {}; # true type prmsList = []; conditionsList = []; isTemplate = hasFlags = hasTemplate = ''; for param in paramsList: if (re.match(r'^\s*$', param)): continue; templ = re.match(r'^{([A-Za-z]+):Type}$', param); if (templ): hasTemplate = templ.group(1); continue; pnametype = re.match(r'([a-z_][a-z0-9_]*):([A-Za-z0-9<>\._]+|![a-zA-Z]+|\#|[a-z_][a-z0-9_]*\.[0-9]+\?[A-Za-z0-9<>\._]+)$', param); if (not pnametype): print('Bad param found: "' + param + '" in line: ' + line); continue; pname = pnametype.group(1); ptypewide = pnametype.group(2); if (re.match(r'^!([a-zA-Z]+)$', ptypewide)): if ('!' + hasTemplate == ptypewide): isTemplate = pname; ptype = 'TQueryType'; else: print('Bad template param name: "' + param + '" in line: ' + line); continue; elif (ptypewide == '#'): hasFlags = pname; if funcsNow: ptype = 'flags<MTP' + name + '::Flags>'; else: ptype = 'flags<MTPD' + name + '::Flags>'; else: ptype = ptypewide; if (ptype.find('?') >= 0): pmasktype = re.match(r'([a-z_][a-z0-9_]*)\.([0-9]+)\?([A-Za-z0-9<>\._]+)', ptype); if (not pmasktype or pmasktype.group(1) != hasFlags): print('Bad param found: "' + param + '" in line: ' + line); continue; ptype = pmasktype.group(3); if (ptype.find('<') >= 0): templ = re.match(r'^([vV]ector<)([A-Za-z0-9\._]+)>$', ptype); if (templ): vectemplate = templ.group(2); if (re.match(r'^[A-Z]', vectemplate) or re.match(r'^[a-zA-Z0-9]+_[A-Z]', vectemplate)): ptype = templ.group(1) + 'MTP' + vectemplate.replace('.', '_') + '>'; elif (vectemplate == 'int' or vectemplate == 'long' or vectemplate == 'string'): ptype = templ.group(1) + 'MTP' + vectemplate.replace('.', '_') + '>'; else: foundmeta = ''; for metatype in typesDict: for typedata in typesDict[metatype]: if (typedata[0] == vectemplate): foundmeta = metatype; break; if (len(foundmeta) > 0): break; if (len(foundmeta) > 0): ptype = templ.group(1) + 'MTP' + foundmeta.replace('.', '_') + '>'; else: print('Bad vector param: ' + vectemplate); continue; else: print('Bad template type: ' + ptype); continue; if (not pname in conditions): conditionsList.append(pname); conditions[pname] = pmasktype.group(2); if (ptype == 'true'): trivialConditions[pname] = 1; elif (ptype.find('<') >= 0): templ = re.match(r'^([vV]ector<)([A-Za-z0-9\._]+)>$', ptype); if (templ): vectemplate = templ.group(2); if (re.match(r'^[A-Z]', vectemplate) or re.match(r'^[a-zA-Z0-9]+_[A-Z]', vectemplate)): ptype = templ.group(1) + 'MTP' + vectemplate.replace('.', '_') + '>'; elif (vectemplate == 'int' or vectemplate == 'long' or vectemplate == 'string'): ptype = templ.group(1) + 'MTP' + vectemplate.replace('.', '_') + '>'; else: foundmeta = ''; for metatype in typesDict: for typedata in typesDict[metatype]: if (typedata[0] == vectemplate): foundmeta = metatype; break; if (len(foundmeta) > 0): break; if (len(foundmeta) > 0): ptype = templ.group(1) + 'MTP' + foundmeta.replace('.', '_') + '>'; else: print('Bad vector param: ' + vectemplate); continue; else: print('Bad template type: ' + ptype); continue; prmsList.append(pname); prms[pname] = ptype.replace('.', '_'); if (isTemplate == '' and resType == 'X'): print('Bad response type "X" in "' + name +'" in line: ' + line); continue; if funcsNow: if (isTemplate != ''): funcsText += '\ntemplate <typename TQueryType>'; funcsText += '\nclass MTP' + name + ' { // RPC method \'' + nametype.group(1) + '\'\n'; # class funcsText += 'public:\n'; prmsStr = []; prmsInit = []; prmsNames = []; if (hasFlags != ''): funcsText += '\tenum class Flag : int32 {\n'; maxbit = 0; parentFlagsCheck['MTP' + name] = {}; for paramName in conditionsList: funcsText += '\t\tf_' + paramName + ' = (1 << ' + conditions[paramName] + '),\n'; parentFlagsCheck['MTP' + name][paramName] = conditions[paramName]; maxbit = max(maxbit, int(conditions[paramName])); if (maxbit > 0): funcsText += '\n'; funcsText += '\t\tMAX_FIELD = (1 << ' + str(maxbit) + '),\n'; funcsText += '\t};\n'; funcsText += '\tQ_DECLARE_FLAGS(Flags, Flag);\n'; funcsText += '\tfriend inline Flags operator~(Flag v) { return QFlag(~static_cast<int32>(v)); }\n'; funcsText += '\n'; if (len(conditions)): for paramName in conditionsList: if (paramName in trivialConditions): funcsText += '\tbool is_' + paramName + '() const { return v' + hasFlags + '.v & Flag::f_' + paramName + '; }\n'; else: funcsText += '\tbool has_' + paramName + '() const { return v' + hasFlags + '.v & Flag::f_' + paramName + '; }\n'; funcsText += '\n'; if (len(prms) > len(trivialConditions)): for paramName in prmsList: if (paramName in trivialConditions): continue; paramType = prms[paramName]; prmsInit.append('v' + paramName + '(_' + paramName + ')'); prmsNames.append('_' + paramName); if (paramName == isTemplate): ptypeFull = paramType; else: ptypeFull = 'MTP' + paramType; funcsText += '\t' + ptypeFull + ' v' + paramName + ';\n'; if (paramType in ['int', 'Int', 'bool', 'Bool', 'flags<Flags>']): prmsStr.append(ptypeFull + ' _' + paramName); else: prmsStr.append('const ' + ptypeFull + ' &_' + paramName); funcsText += '\n'; funcsText += '\tMTP' + name + '() {\n\t}\n'; # constructor funcsText += '\tMTP' + name + '(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons = mtpc_' + name + ') {\n\t\tread(from, end, cons);\n\t}\n'; # stream constructor if (len(prms) > len(trivialConditions)): funcsText += '\tMTP' + name + '(' + ', '.join(prmsStr) + ') : ' + ', '.join(prmsInit) + ' {\n\t}\n'; funcsText += '\n'; funcsText += '\tuint32 innerLength() const {\n'; # count size size = []; for k in prmsList: v = prms[k]; if (k in conditionsList): if (not k in trivialConditions): size.append('(has_' + k + '() ? v' + k + '.innerLength() : 0)'); else: size.append('v' + k + '.innerLength()'); if (not len(size)): size.append('0'); funcsText += '\t\treturn ' + ' + '.join(size) + ';\n'; funcsText += '\t}\n'; funcsText += '\tmtpTypeId type() const {\n\t\treturn mtpc_' + name + ';\n\t}\n'; # type id funcsText += '\tvoid read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons = mtpc_' + name + ') {\n'; # read method for k in prmsList: v = prms[k]; if (k in conditionsList): if (not k in trivialConditions): funcsText += '\t\tif (has_' + k + '()) { v' + k + '.read(from, end); } else { v' + k + ' = MTP' + v + '(); }\n'; else: funcsText += '\t\tv' + k + '.read(from, end);\n'; funcsText += '\t}\n'; funcsText += '\tvoid write(mtpBuffer &to) const {\n'; # write method for k in prmsList: v = prms[k]; if (k in conditionsList): if (not k in trivialConditions): funcsText += '\t\tif (has_' + k + '()) v' + k + '.write(to);\n'; else: funcsText += '\t\tv' + k + '.write(to);\n'; funcsText += '\t}\n'; if (isTemplate != ''): funcsText += '\n\ttypedef typename TQueryType::ResponseType ResponseType;\n'; else: funcsText += '\n\ttypedef MTP' + resType + ' ResponseType;\n'; # method return type funcsText += '};\n'; # class ending if (len(conditionsList)): funcsText += 'Q_DECLARE_OPERATORS_FOR_FLAGS(MTP' + name + '::Flags)\n\n'; if (isTemplate != ''): funcsText += 'template <typename TQueryType>\n'; funcsText += 'class MTP' + Name + ' : public MTPBoxed<MTP' + name + '<TQueryType> > {\n'; funcsText += 'public:\n'; funcsText += '\tMTP' + Name + '() {\n\t}\n'; funcsText += '\tMTP' + Name + '(const MTP' + name + '<TQueryType> &v) : MTPBoxed<MTP' + name + '<TQueryType> >(v) {\n\t}\n'; if (len(prms) > len(trivialConditions)): funcsText += '\tMTP' + Name + '(' + ', '.join(prmsStr) + ') : MTPBoxed<MTP' + name + '<TQueryType> >(MTP' + name + '<TQueryType>(' + ', '.join(prmsNames) + ')) {\n\t}\n'; funcsText += '};\n'; else: funcsText += 'class MTP' + Name + ' : public MTPBoxed<MTP' + name + '> {\n'; funcsText += 'public:\n'; funcsText += '\tMTP' + Name + '() {\n\t}\n'; funcsText += '\tMTP' + Name + '(const MTP' + name + ' &v) : MTPBoxed<MTP' + name + '>(v) {\n\t}\n'; funcsText += '\tMTP' + Name + '(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons = 0) : MTPBoxed<MTP' + name + '>(from, end, cons) {\n\t}\n'; if (len(prms) > len(trivialConditions)): funcsText += '\tMTP' + Name + '(' + ', '.join(prmsStr) + ') : MTPBoxed<MTP' + name + '>(MTP' + name + '(' + ', '.join(prmsNames) + ')) {\n\t}\n'; funcsText += '};\n'; funcs = funcs + 1; if (not restype in funcsDict): funcsList.append(restype); funcsDict[restype] = []; # TypesDict[restype] = resType; funcsDict[restype].append([name, typeid, prmsList, prms, hasFlags, conditionsList, conditions, trivialConditions]); else: if (isTemplate != ''): print('Template types not allowed: "' + resType + '" in line: ' + line); continue; if (not restype in typesDict): typesList.append(restype); typesDict[restype] = []; TypesDict[restype] = resType; typesDict[restype].append([name, typeid, prmsList, prms, hasFlags, conditionsList, conditions, trivialConditions]); consts = consts + 1; # text serialization: types and funcs def addTextSerialize(lst, dct, dataLetter): result = ''; for restype in lst: v = dct[restype]; for data in v: name = data[0]; prmsList = data[2]; prms = data[3]; hasFlags = data[4]; conditionsList = data[5]; conditions = data[6]; trivialConditions = data[7]; result += 'void _serialize_' + name + '(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag) {\n'; if (len(conditions)): result += '\tMTP' + dataLetter + name + '::Flags flag(iflag);\n\n'; if (len(prms)): result += '\tif (stage) {\n'; result += '\t\tto.add(",\\n").addSpaces(lev);\n'; result += '\t} else {\n'; result += '\t\tto.add("{ ' + name + '");\n'; result += '\t\tto.add("\\n").addSpaces(lev);\n'; result += '\t}\n'; result += '\tswitch (stage) {\n'; stage = 0; for k in prmsList: v = prms[k]; result += '\tcase ' + str(stage) + ': to.add(" ' + k + ': "); ++stages.back(); '; if (k == hasFlags): result += 'if (start >= end) throw Exception("start >= end in flags"); else flags.back() = *start; '; if (k in trivialConditions): result += 'if (flag & MTP' + dataLetter + name + '::Flag::f_' + k + ') { '; result += 'to.add("YES [ BY BIT ' + conditions[k] + ' IN FIELD ' + hasFlags + ' ]"); '; result += '} else { to.add("[ SKIPPED BY BIT ' + conditions[k] + ' IN FIELD ' + hasFlags + ' ]"); } '; else: if (k in conditions): result += 'if (flag & MTP' + dataLetter + name + '::Flag::f_' + k + ') { '; result += 'types.push_back('; vtypeget = re.match(r'^[Vv]ector<MTP([A-Za-z0-9\._]+)>', v); if (vtypeget): if (not re.match(r'^[A-Z]', v)): result += 'mtpc_vector'; else: result += '0'; restype = vtypeget.group(1); try: if boxed[restype]: restype = 0; except KeyError: if re.match(r'^[A-Z]', restype): restype = 0; else: restype = v; try: if boxed[restype]: restype = 0; except KeyError: if re.match(r'^[A-Z]', restype): restype = 0; if (restype): try: conses = typesDict[restype]; if (len(conses) > 1): print('Complex bare type found: "' + restype + '" trying to serialize "' + k + '" of type "' + v + '"'); continue; if (vtypeget): result += '); vtypes.push_back('; result += 'mtpc_' + conses[0][0]; if (not vtypeget): result += '); vtypes.push_back(0'; except KeyError: if (vtypeget): result += '); vtypes.push_back('; if (re.match(r'^flags<', restype)): result += 'mtpc_flags'; else: result += 'mtpc_' + restype + '+0'; if (not vtypeget): result += '); vtypes.push_back(0'; else: result += '0); vtypes.push_back(0'; result += '); stages.push_back(0); flags.push_back(0); '; if (k in conditions): result += '} else { to.add("[ SKIPPED BY BIT ' + conditions[k] + ' IN FIELD ' + hasFlags + ' ]"); } '; result += 'break;\n'; stage = stage + 1; result += '\tdefault: to.add("}"); types.pop_back(); vtypes.pop_back(); stages.pop_back(); flags.pop_back(); break;\n'; result += '\t}\n'; else: result += '\tto.add("{ ' + name + ' }"); types.pop_back(); vtypes.pop_back(); stages.pop_back(); flags.pop_back();\n'; result += '}\n\n'; return result; # text serialization: types and funcs def addTextSerializeInit(lst, dct): result = ''; for restype in lst: v = dct[restype]; for data in v: name = data[0]; result += '\t\t_serializers.insert(mtpc_' + name + ', _serialize_' + name + ');\n'; return result; textSerializeMethods += addTextSerialize(typesList, typesDict, 'D'); textSerializeInit += addTextSerializeInit(typesList, typesDict) + '\n'; textSerializeMethods += addTextSerialize(funcsList, funcsDict, ''); textSerializeInit += addTextSerializeInit(funcsList, funcsDict) + '\n'; for restype in typesList: v = typesDict[restype]; resType = TypesDict[restype]; withData = 0; creatorsText = ''; constructsText = ''; constructsInline = ''; forwards += 'class MTP' + restype + ';\n'; forwTypedefs += 'typedef MTPBoxed<MTP' + restype + '> MTP' + resType + ';\n'; withType = (len(v) > 1); switchLines = ''; friendDecl = ''; getters = ''; reader = ''; writer = ''; sizeList = []; sizeFast = ''; newFast = ''; sizeCases = ''; for data in v: name = data[0]; typeid = data[1]; prmsList = data[2]; prms = data[3]; hasFlags = data[4]; conditionsList = data[5]; conditions = data[6]; trivialConditions = data[7]; dataText = ''; dataText += '\nclass MTPD' + name + ' : public mtpDataImpl<MTPD' + name + '> {\n'; # data class dataText += 'public:\n'; sizeList = []; creatorParams = []; creatorParamsList = []; readText = ''; writeText = ''; if (hasFlags != ''): dataText += '\tenum class Flag : int32 {\n'; maxbit = 0; parentFlagsCheck['MTPD' + name] = {}; for paramName in conditionsList: dataText += '\t\tf_' + paramName + ' = (1 << ' + conditions[paramName] + '),\n'; parentFlagsCheck['MTPD' + name][paramName] = conditions[paramName]; maxbit = max(maxbit, int(conditions[paramName])); if (maxbit > 0): dataText += '\n'; dataText += '\t\tMAX_FIELD = (1 << ' + str(maxbit) + '),\n'; dataText += '\t};\n'; dataText += '\tQ_DECLARE_FLAGS(Flags, Flag);\n'; dataText += '\tfriend inline Flags operator~(Flag v) { return QFlag(~static_cast<int32>(v)); }\n'; dataText += '\n'; if (len(conditions)): for paramName in conditionsList: if (paramName in trivialConditions): dataText += '\tbool is_' + paramName + '() const { return v' + hasFlags + '.v & Flag::f_' + paramName + '; }\n'; else: dataText += '\tbool has_' + paramName + '() const { return v' + hasFlags + '.v & Flag::f_' + paramName + '; }\n'; dataText += '\n'; dataText += '\tMTPD' + name + '() {\n\t}\n'; # default constructor switchLines += '\t\tcase mtpc_' + name + ': '; # for by-type-id type constructor if (len(prms) > len(trivialConditions)): switchLines += 'setData(new MTPD' + name + '()); '; withData = 1; getters += '\n\tMTPD' + name + ' &_' + name + '() {\n'; # splitting getter getters += '\t\tif (!data) throw mtpErrorUninitialized();\n'; if (withType): getters += '\t\tif (_type != mtpc_' + name + ') throw mtpErrorWrongTypeId(_type, mtpc_' + name + ');\n'; getters += '\t\tsplit();\n'; getters += '\t\treturn *(MTPD' + name + '*)data;\n'; getters += '\t}\n'; getters += '\tconst MTPD' + name + ' &c_' + name + '() const {\n'; # const getter getters += '\t\tif (!data) throw mtpErrorUninitialized();\n'; if (withType): getters += '\t\tif (_type != mtpc_' + name + ') throw mtpErrorWrongTypeId(_type, mtpc_' + name + ');\n'; getters += '\t\treturn *(const MTPD' + name + '*)data;\n'; getters += '\t}\n'; constructsText += '\texplicit MTP' + restype + '(MTPD' + name + ' *_data);\n'; # by-data type constructor constructsInline += 'inline MTP' + restype + '::MTP' + restype + '(MTPD' + name + ' *_data) : mtpDataOwner(_data)'; if (withType): constructsInline += ', _type(mtpc_' + name + ')'; constructsInline += ' {\n}\n'; dataText += '\tMTPD' + name + '('; # params constructor prmsStr = []; prmsInit = []; for paramName in prmsList: if (paramName in trivialConditions): continue; paramType = prms[paramName]; if (paramType in ['int', 'Int', 'bool', 'Bool']): prmsStr.append('MTP' + paramType + ' _' + paramName); creatorParams.append('MTP' + paramType + ' _' + paramName); else: prmsStr.append('const MTP' + paramType + ' &_' + paramName); creatorParams.append('const MTP' + paramType + ' &_' + paramName); creatorParamsList.append('_' + paramName); prmsInit.append('v' + paramName + '(_' + paramName + ')'); if (withType): readText += '\t\t'; writeText += '\t\t'; if (paramName in conditions): readText += '\tif (v.has_' + paramName + '()) { v.v' + paramName + '.read(from, end); } else { v.v' + paramName + ' = MTP' + paramType + '(); }\n'; writeText += '\tif (v.has_' + paramName + '()) v.v' + paramName + '.write(to);\n'; sizeList.append('(v.has_' + paramName + '() ? v.v' + paramName + '.innerLength() : 0)'); else: readText += '\tv.v' + paramName + '.read(from, end);\n'; writeText += '\tv.v' + paramName + '.write(to);\n'; sizeList.append('v.v' + paramName + '.innerLength()'); forwards += 'class MTPD' + name + ';\n'; # data class forward declaration dataText += ', '.join(prmsStr) + ') : ' + ', '.join(prmsInit) + ' {\n\t}\n'; dataText += '\n'; for paramName in prmsList: # fields declaration if (paramName in trivialConditions): continue; paramType = prms[paramName]; dataText += '\tMTP' + paramType + ' v' + paramName + ';\n'; sizeCases += '\t\tcase mtpc_' + name + ': {\n'; sizeCases += '\t\t\tconst MTPD' + name + ' &v(c_' + name + '());\n'; sizeCases += '\t\t\treturn ' + ' + '.join(sizeList) + ';\n'; sizeCases += '\t\t}\n'; sizeFast = '\tconst MTPD' + name + ' &v(c_' + name + '());\n\treturn ' + ' + '.join(sizeList) + ';\n'; newFast = 'new MTPD' + name + '()'; else: sizeFast = '\treturn 0;\n'; switchLines += 'break;\n'; dataText += '};\n'; # class ending if (len(prms) > len(trivialConditions)): dataTexts += dataText; # add data class if (not friendDecl): friendDecl += '\tfriend class MTP::internal::TypeCreator;\n'; creatorProxyText += '\tinline static MTP' + restype + ' new_' + name + '(' + ', '.join(creatorParams) + ') {\n'; if (len(prms) > len(trivialConditions)): # creator with params creatorProxyText += '\t\treturn MTP' + restype + '(new MTPD' + name + '(' + ', '.join(creatorParamsList) + '));\n'; else: if (withType): # creator by type creatorProxyText += '\t\treturn MTP' + restype + '(mtpc_' + name + ');\n'; else: # single creator creatorProxyText += '\t\treturn MTP' + restype + '();\n'; creatorProxyText += '\t}\n'; if (len(conditionsList)): creatorsText += 'Q_DECLARE_OPERATORS_FOR_FLAGS(MTPD' + name + '::Flags)\n'; creatorsText += 'inline MTP' + restype + ' MTP_' + name + '(' + ', '.join(creatorParams) + ') {\n'; creatorsText += '\treturn MTP::internal::TypeCreator::new_' + name + '(' + ', '.join(creatorParamsList) + ');\n'; creatorsText += '}\n'; if (withType): reader += '\t\tcase mtpc_' + name + ': _type = cons; '; # read switch line if (len(prms) > len(trivialConditions)): reader += '{\n'; reader += '\t\t\tif (!data) setData(new MTPD' + name + '());\n'; reader += '\t\t\tMTPD' + name + ' &v(_' + name + '());\n'; reader += readText; reader += '\t\t} break;\n'; writer += '\t\tcase mtpc_' + name + ': {\n'; # write switch line writer += '\t\t\tconst MTPD' + name + ' &v(c_' + name + '());\n'; writer += writeText; writer += '\t\t} break;\n'; else: reader += 'break;\n'; else: if (len(prms) > len(trivialConditions)): reader += '\n\tif (!data) setData(new MTPD' + name + '());\n'; reader += '\tMTPD' + name + ' &v(_' + name + '());\n'; reader += readText; writer += '\tconst MTPD' + name + ' &v(c_' + name + '());\n'; writer += writeText; forwards += '\n'; typesText += '\nclass MTP' + restype; # type class declaration if (withData): typesText += ' : private mtpDataOwner'; # if has data fields typesText += ' {\n'; typesText += 'public:\n'; typesText += '\tMTP' + restype + '()'; # default constructor inits = []; if (withType): if (withData): inits.append('mtpDataOwner(0)'); inits.append('_type(0)'); else: if (withData): inits.append('mtpDataOwner(' + newFast + ')'); if (withData and not withType): typesText += ';\n'; inlineMethods += '\ninline MTP' + restype + '::MTP' + restype + '()'; if (inits): inlineMethods += ' : ' + ', '.join(inits); inlineMethods += ' {\n}\n'; else: if (inits): typesText += ' : ' + ', '.join(inits); typesText += ' {\n\t}\n'; inits = []; if (withData): inits.append('mtpDataOwner(0)'); if (withType): inits.append('_type(0)'); typesText += '\tMTP' + restype + '(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons'; if (not withType): typesText += ' = mtpc_' + name; typesText += ')'; # read constructor if (inits): typesText += ' : ' + ', '.join(inits); typesText += ' {\n\t\tread(from, end, cons);\n\t}\n'; if (withData): typesText += getters; typesText += '\n\tuint32 innerLength() const;\n'; # size method inlineMethods += '\ninline uint32 MTP' + restype + '::innerLength() const {\n'; if (withType and sizeCases): inlineMethods += '\tswitch (_type) {\n'; inlineMethods += sizeCases; inlineMethods += '\t}\n'; inlineMethods += '\treturn 0;\n'; else: inlineMethods += sizeFast; inlineMethods += '}\n'; typesText += '\tmtpTypeId type() const;\n'; # type id method inlineMethods += 'inline mtpTypeId MTP' + restype + '::type() const {\n'; if (withType): inlineMethods += '\tif (!_type) throw mtpErrorUninitialized();\n'; inlineMethods += '\treturn _type;\n'; else: inlineMethods += '\treturn mtpc_' + v[0][0] + ';\n'; inlineMethods += '}\n'; typesText += '\tvoid read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons'; # read method if (not withType): typesText += ' = mtpc_' + name; typesText += ');\n'; inlineMethods += 'inline void MTP' + restype + '::read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons) {\n'; if (withData): if (withType): inlineMethods += '\tif (cons != _type) setData(0);\n'; else: inlineMethods += '\tif (cons != mtpc_' + v[0][0] + ') throw mtpErrorUnexpected(cons, "MTP' + restype + '");\n'; if (withType): inlineMethods += '\tswitch (cons) {\n' inlineMethods += reader; inlineMethods += '\t\tdefault: throw mtpErrorUnexpected(cons, "MTP' + restype + '");\n'; inlineMethods += '\t}\n'; else: inlineMethods += reader; inlineMethods += '}\n'; typesText += '\tvoid write(mtpBuffer &to) const;\n'; # write method inlineMethods += 'inline void MTP' + restype + '::write(mtpBuffer &to) const {\n'; if (withType and writer != ''): inlineMethods += '\tswitch (_type) {\n'; inlineMethods += writer; inlineMethods += '\t}\n'; else: inlineMethods += writer; inlineMethods += '}\n'; typesText += '\n\ttypedef void ResponseType;\n'; # no response types declared typesText += '\nprivate:\n'; # private constructors if (withType): # by-type-id constructor typesText += '\texplicit MTP' + restype + '(mtpTypeId type);\n'; inlineMethods += 'inline MTP' + restype + '::MTP' + restype + '(mtpTypeId type) : '; if (withData): inlineMethods += 'mtpDataOwner(0), '; inlineMethods += '_type(type)'; inlineMethods += ' {\n'; inlineMethods += '\tswitch (type) {\n'; # type id check inlineMethods += switchLines; inlineMethods += '\t\tdefault: throw mtpErrorBadTypeId(type, "MTP' + restype + '");\n\t}\n'; inlineMethods += '}\n'; # by-type-id constructor end if (withData): typesText += constructsText; inlineMethods += constructsInline; if (friendDecl): typesText += '\n' + friendDecl; if (withType): typesText += '\n\tmtpTypeId _type;\n'; # type field var typesText += '};\n'; # type class ended inlineMethods += creatorsText; typesText += 'typedef MTPBoxed<MTP' + restype + '> MTP' + resType + ';\n'; # boxed type definition for childName in parentFlagsList: parentName = parentFlags[childName]; for flag in parentFlagsCheck[childName]: if (not flag in parentFlagsCheck[parentName]): print('Flag ' + flag + ' not found in ' + parentName + ' which should be a flags-parent of ' + childName); error elif (parentFlagsCheck[childName][flag] != parentFlagsCheck[parentName][flag]): print('Flag ' + flag + ' has different value in ' + parentName + ' which should be a flags-parent of ' + childName); error inlineMethods += 'inline ' + parentName + '::Flags mtpCastFlags(' + childName + '::Flags flags) { return ' + parentName + '::Flags(QFlag(flags)); }\n'; inlineMethods += 'inline ' + parentName + '::Flags mtpCastFlags(MTPflags<' + childName + '::Flags> flags) { return mtpCastFlags(flags.v); }\n'; # manual types added here textSerializeMethods += 'void _serialize_rpc_result(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag) {\n'; textSerializeMethods += '\tif (stage) {\n'; textSerializeMethods += '\t\tto.add(",\\n").addSpaces(lev);\n'; textSerializeMethods += '\t} else {\n'; textSerializeMethods += '\t\tto.add("{ rpc_result");\n'; textSerializeMethods += '\t\tto.add("\\n").addSpaces(lev);\n'; textSerializeMethods += '\t}\n'; textSerializeMethods += '\tswitch (stage) {\n'; textSerializeMethods += '\tcase 0: to.add(" req_msg_id: "); ++stages.back(); types.push_back(mtpc_long); vtypes.push_back(0); stages.push_back(0); flags.push_back(0); break;\n'; textSerializeMethods += '\tcase 1: to.add(" result: "); ++stages.back(); types.push_back(0); vtypes.push_back(0); stages.push_back(0); flags.push_back(0); break;\n'; textSerializeMethods += '\tdefault: to.add("}"); types.pop_back(); vtypes.pop_back(); stages.pop_back(); flags.pop_back(); break;\n'; textSerializeMethods += '\t}\n'; textSerializeMethods += '}\n\n'; textSerializeInit += '\t\t_serializers.insert(mtpc_rpc_result, _serialize_rpc_result);\n'; textSerializeMethods += 'void _serialize_msg_container(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag) {\n'; textSerializeMethods += '\tif (stage) {\n'; textSerializeMethods += '\t\tto.add(",\\n").addSpaces(lev);\n'; textSerializeMethods += '\t} else {\n'; textSerializeMethods += '\t\tto.add("{ msg_container");\n'; textSerializeMethods += '\t\tto.add("\\n").addSpaces(lev);\n'; textSerializeMethods += '\t}\n'; textSerializeMethods += '\tswitch (stage) {\n'; textSerializeMethods += '\tcase 0: to.add(" messages: "); ++stages.back(); types.push_back(mtpc_vector); vtypes.push_back(mtpc_core_message); stages.push_back(0); flags.push_back(0); break;\n'; textSerializeMethods += '\tdefault: to.add("}"); types.pop_back(); vtypes.pop_back(); stages.pop_back(); flags.pop_back(); break;\n'; textSerializeMethods += '\t}\n'; textSerializeMethods += '}\n\n'; textSerializeInit += '\t\t_serializers.insert(mtpc_msg_container, _serialize_msg_container);\n'; textSerializeMethods += 'void _serialize_core_message(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag) {\n'; textSerializeMethods += '\tif (stage) {\n'; textSerializeMethods += '\t\tto.add(",\\n").addSpaces(lev);\n'; textSerializeMethods += '\t} else {\n'; textSerializeMethods += '\t\tto.add("{ core_message");\n'; textSerializeMethods += '\t\tto.add("\\n").addSpaces(lev);\n'; textSerializeMethods += '\t}\n'; textSerializeMethods += '\tswitch (stage) {\n'; textSerializeMethods += '\tcase 0: to.add(" msg_id: "); ++stages.back(); types.push_back(mtpc_long); vtypes.push_back(0); stages.push_back(0); flags.push_back(0); break;\n'; textSerializeMethods += '\tcase 1: to.add(" seq_no: "); ++stages.back(); types.push_back(mtpc_int); vtypes.push_back(0); stages.push_back(0); flags.push_back(0); break;\n'; textSerializeMethods += '\tcase 2: to.add(" bytes: "); ++stages.back(); types.push_back(mtpc_int); vtypes.push_back(0); stages.push_back(0); flags.push_back(0); break;\n'; textSerializeMethods += '\tcase 3: to.add(" body: "); ++stages.back(); types.push_back(0); vtypes.push_back(0); stages.push_back(0); flags.push_back(0); break;\n'; textSerializeMethods += '\tdefault: to.add("}"); types.pop_back(); vtypes.pop_back(); stages.pop_back(); flags.pop_back(); break;\n'; textSerializeMethods += '\t}\n'; textSerializeMethods += '}\n\n'; textSerializeInit += '\t\t_serializers.insert(mtpc_core_message, _serialize_core_message);\n'; textSerializeFull = '\nvoid mtpTextSerializeType(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpPrime cons, uint32 level, mtpPrime vcons) {\n'; textSerializeFull += '\tif (_serializers.isEmpty()) initTextSerializers();\n\n'; textSerializeFull += '\tQVector<mtpTypeId> types, vtypes;\n'; textSerializeFull += '\tQVector<int32> stages, flags;\n'; textSerializeFull += '\ttypes.reserve(20); vtypes.reserve(20); stages.reserve(20); flags.reserve(20);\n'; textSerializeFull += '\ttypes.push_back(mtpTypeId(cons)); vtypes.push_back(mtpTypeId(vcons)); stages.push_back(0); flags.push_back(0);\n\n'; textSerializeFull += '\tconst mtpPrime *start = from;\n'; textSerializeFull += '\tmtpTypeId type = cons, vtype = vcons;\n'; textSerializeFull += '\tint32 stage = 0, flag = 0;\n\n'; textSerializeFull += '\twhile (!types.isEmpty()) {\n'; textSerializeFull += '\t\ttype = types.back();\n'; textSerializeFull += '\t\tvtype = vtypes.back();\n'; textSerializeFull += '\t\tstage = stages.back();\n'; textSerializeFull += '\t\tflag = flags.back();\n'; textSerializeFull += '\t\tif (!type) {\n'; textSerializeFull += '\t\t\tif (from >= end) {\n'; textSerializeFull += '\t\t\t\tthrow Exception("from >= end");\n'; textSerializeFull += '\t\t\t} else if (stage) {\n'; textSerializeFull += '\t\t\t\tthrow Exception("unknown type on stage > 0");\n'; textSerializeFull += '\t\t\t}\n'; textSerializeFull += '\t\t\ttypes.back() = type = *from;\n'; textSerializeFull += '\t\t\tstart = ++from;\n'; textSerializeFull += '\t\t}\n\n'; textSerializeFull += '\t\tint32 lev = level + types.size() - 1;\n'; textSerializeFull += '\t\tTextSerializers::const_iterator it = _serializers.constFind(type);\n'; textSerializeFull += '\t\tif (it != _serializers.cend()) {\n'; textSerializeFull += '\t\t\t(*it.value())(to, stage, lev, types, vtypes, stages, flags, start, end, flag);\n'; textSerializeFull += '\t\t} else {\n'; textSerializeFull += '\t\t\tmtpTextSerializeCore(to, from, end, type, lev, vtype);\n'; textSerializeFull += '\t\t\ttypes.pop_back(); vtypes.pop_back(); stages.pop_back(); flags.pop_back();\n'; textSerializeFull += '\t\t}\n'; textSerializeFull += '\t}\n'; textSerializeFull += '}\n'; out.write('\n// Creator current layer and proxy class declaration\n'); out.write('namespace MTP {\nnamespace internal {\n\n' + layer + '\n\n'); out.write('class TypeCreator;\n\n} // namespace internal\n} // namespace MTP\n'); out.write('\n// Type id constants\nenum {\n' + ',\n'.join(enums) + '\n};\n'); out.write('\n// Type forward declarations\n' + forwards); out.write('\n// Boxed types definitions\n' + forwTypedefs); out.write('\n// Type classes definitions\n' + typesText); out.write('\n// Type constructors with data\n' + dataTexts); out.write('\n// RPC methods\n' + funcsText); out.write('\n// Creator proxy class definition\nnamespace MTP {\nnamespace internal {\n\nclass TypeCreator {\npublic:\n' + creatorProxyText + '\t};\n\n} // namespace internal\n} // namespace MTP\n'); out.write('\n// Inline methods definition\n' + inlineMethods); out.write('\n// Human-readable text serialization\nvoid mtpTextSerializeType(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpPrime cons, uint32 level, mtpPrime vcons);\n'); outCpp = open('scheme_auto.cpp', 'w'); outCpp.write('/*\n'); outCpp.write('Created from \'/SourceFiles/mtproto/scheme.tl\' by \'/SourceFiles/mtproto/generate.py\' script\n\n'); outCpp.write('WARNING! All changes made in this file will be lost!\n\n'); outCpp.write('This file is part of Telegram Desktop,\n'); outCpp.write('the official desktop version of Telegram messaging app, see https://telegram.org\n'); outCpp.write('\n'); outCpp.write('Telegram Desktop is free software: you can redistribute it and/or modify\n'); outCpp.write('it under the terms of the GNU General Public License as published by\n'); outCpp.write('the Free Software Foundation, either version 3 of the License, or\n'); outCpp.write('(at your option) any later version.\n'); outCpp.write('\n'); outCpp.write('It is distributed in the hope that it will be useful,\n'); outCpp.write('but WITHOUT ANY WARRANTY; without even the implied warranty of\n'); outCpp.write('MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n'); outCpp.write('GNU General Public License for more details.\n'); outCpp.write('\n'); outCpp.write('Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE\n'); outCpp.write('Copyright (c) 2014 John Preston, https://desktop.telegram.org\n'); outCpp.write('*/\n'); outCpp.write('#include "stdafx.h"\n\n#include "mtproto/scheme_auto.h"\n\n'); outCpp.write('typedef QVector<mtpTypeId> Types;\ntypedef QVector<int32> StagesFlags;\n\n'); outCpp.write(textSerializeMethods); outCpp.write('namespace {\n'); outCpp.write('\ttypedef void(*mtpTextSerializer)(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag);\n'); outCpp.write('\ttypedef QMap<mtpTypeId, mtpTextSerializer> TextSerializers;\n\tTextSerializers _serializers;\n\n'); outCpp.write('\tvoid initTextSerializers() {\n'); outCpp.write(textSerializeInit); outCpp.write('\t}\n}\n'); outCpp.write(textSerializeFull + '\n'); print('Done, written {0} constructors, {1} functions.'.format(consts, funcs));
gpl-3.0
-8,282,897,700,748,940,000
45.17915
232
0.573874
false
3.265927
false
false
false
chen0040/pyalgs
pyalgs/algorithms/graphs/directed_cycle.py
1
1475
from pyalgs.data_structures.commons.stack import Stack from pyalgs.data_structures.graphs.graph import DirectedEdgeWeightedGraph, Digraph class DirectedCycle(object): marked = None onStack = None cycle = None edgeTo = None def __init__(self, G): if isinstance(G, DirectedEdgeWeightedGraph): G = G.to_digraph() if not isinstance(G, Digraph): raise ValueError('Graph must be unweighted digraph') vertex_count = G.vertex_count() self.marked = [False] * vertex_count self.onStack = [False] * vertex_count self.edgeTo = [-1] * vertex_count for v in range(vertex_count): if not self.marked[v]: self.dfs(G, v) def dfs(self, G, v): self.marked[v] = True self.onStack[v] = True for w in G.adj(v): if not self.marked[w]: self.edgeTo[w] = v self.dfs(G, w) elif self.cycle is not None: break elif self.onStack[w]: self.cycle = Stack.create() x = v while x != w: self.cycle.push(x) x = self.edgeTo[x] self.cycle.push(w) self.cycle.push(v) break self.onStack[v] = False def hasCycle(self): return self.cycle is not None def get_cycle(self): return self.cycle.iterate()
bsd-3-clause
-2,261,778,148,886,728,400
26.314815
82
0.522712
false
3.861257
false
false
false
ppmim/AFOSN
run_patch.py
1
7925
""" DESCRIPTION ----------- For each directory provided on the command line the headers all of the FITS files in that directory are modified to add information like LST, apparent object position, and more. See the full documentation for a list of the specific keywords that are modified. Header patching ^^^^^^^^^^^^^^^ This is basically a wrapper around the function :func:`patch_headers.patch_headers` with the options set so that: + "Bad" keywords written by MaxImDL 5 are purged. + ``IMAGETYP`` keyword is changed from default MaxIM DL style to IRAF style (e.g. "Bias Frame" to "BIAS") + Additional useful times like LST, JD are added to the header. + Apparent position (Alt/Az, hour angle) are added to the header. + Information about overscan is added to the header. + Files are overwritten. For more control over what is patched and where the patched files are saved see the documentation for ``patch_headers`` at :func:`patch_headers.patch_headers`. Adding OBJECT keyword ^^^^^^^^^^^^^^^^^^^^^ ``run_patch`` also adds the name of the object being observed when appropriate (i.e. only for light files) and possible. It needs to be given a list of objects; looking up the coordinates for those objects requires an Internet connection. See For a detailed description of the object list file see :func:`Object file format <patch_headers.read_object_list>`. for a detailed description of the function that actually adds the object name see :func:`patch_headers.add_object_info`. If no object list is specified or present in the directory being processed the `OBJECT` keyword is simply not added to the FITS header. .. Note:: This script is **NOT RECURSIVE**; it will not process files in subdirectories of the the directories supplied on the command line. .. WARNING:: This script OVERWRITES the image files in the directories specified on the command line unless you use the --destination-dir option. EXAMPLES -------- Invoking this script from the command line:: run_patch.py /my/folder/of/images To work on the same folder from within python, do this:: from msumastro.scripts import run_patch run_patch.main(['/my/folder/of/images']) To use the same object list for several different directories do this:: run_patch.py --object-list path/to/list.txt dir1 dir2 dir3 where ``path/to/list.txt`` is the path to your object list and ``dir1``, ``dir2``, etc. are the directories you want to process. From within python this would be:: from msumastro.scripts import run_patch run_patch.main(['--object-list', 'path/to/list.txt', 'dir1', 'dir2', 'dir3']) """ from __future__ import (print_function, division, absolute_import, unicode_literals) from os import getcwd from os import path import warnings import logging from ..header_processing import patch_headers, add_object_info, list_name_is_url from ..customlogger import console_handler, add_file_handlers from .script_helpers import (setup_logging, construct_default_parser, handle_destination_dir_logging_check, _main_function_docstring) logger = logging.getLogger() screen_handler = console_handler() logger.addHandler(screen_handler) DEFAULT_OBJ_LIST = 'obsinfo.txt' DEFAULT_OBJECT_URL = ('https://raw.github.com/mwcraig/feder-object-list' '/master/feder_object_list.csv') def patch_directories(directories, verbose=False, object_list=None, destination=None, no_log_destination=False, overscan_only=False, script_name='run_patch'): """ Patch all of the files in each of a list of directories. Parameters ---------- directories : str or list of str Directory or directories whose FITS files are to be processed. verbose : bool, optional Control amount of logging output. object_list : str, optional Path to or URL of a file containing a list of objects that might be in the files in `directory`. If not provided it defaults to looking for a file called `obsinfo.txt` in the directory being processed. destination : str, optional Path to directory in which patched images will be stored. Default value is None, which means that **files will be overwritten** in the directory being processed. """ no_explicit_object_list = (object_list is None) if not no_explicit_object_list: if list_name_is_url(object_list): obj_dir = None obj_name = object_list else: full_path = path.abspath(object_list) obj_dir, obj_name = path.split(full_path) for currentDir in directories: if destination is not None: working_dir = destination else: working_dir = currentDir if (not no_log_destination) and (destination is not None): add_file_handlers(logger, working_dir, 'run_patch') logger.info("Working on directory: %s", currentDir) with warnings.catch_warnings(): # suppress warning from overwriting FITS files ignore_from = 'astropy.io.fits.hdu.hdulist' warnings.filterwarnings('ignore', module=ignore_from) if overscan_only: patch_headers(currentDir, new_file_ext='', overwrite=True, save_location=destination, purge_bad=False, add_time=False, add_apparent_pos=False, add_overscan=True, fix_imagetype=False, add_unit=False) else: patch_headers(currentDir, new_file_ext='', overwrite=True, save_location=destination) default_object_list_present = path.exists(path.join(currentDir, DEFAULT_OBJ_LIST)) if (default_object_list_present and no_explicit_object_list): obj_dir = currentDir obj_name = DEFAULT_OBJ_LIST add_object_info(working_dir, new_file_ext='', overwrite=True, save_location=destination, object_list_dir=obj_dir, object_list=obj_name) def construct_parser(): parser = construct_default_parser(__doc__) object_list_help = ('Path to or URL of file containing list (and ' 'optionally coordinates of) objects that might be in ' 'these files. If not provided it defaults to looking ' 'for a file called obsinfo.txt in the directory ' 'being processed') parser.add_argument('-o', '--object-list', help=object_list_help, default=DEFAULT_OBJECT_URL) parser.add_argument('--overscan-only', action='store_true', help='Only add appropriate overscan keywords') return parser def main(arglist=None): """See script_helpers._main_function_docstring for actual documentation """ parser = construct_parser() args = parser.parse_args(arglist) setup_logging(logger, args, screen_handler) add_file_handlers(logger, getcwd(), 'run_patch') do_not_log_in_destination = handle_destination_dir_logging_check(args) patch_directories(args.dir, verbose=args.verbose, object_list=args.object_list, destination=args.destination_dir, no_log_destination=do_not_log_in_destination, overscan_only=args.overscan_only) main.__doc__ = _main_function_docstring(__name__)
gpl-2.0
-6,576,618,754,313,954,000
36.206573
80
0.627129
false
4.286101
false
false
false
Ripley6811/TAIMAU
src/db_tools/TM2014_tables_v3.py
1
20670
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Version 3 splits Order into Order and OrderItem, Shipment into Shipment and ShipmentItem. Just as Invoice was split from version 1 to 2. InvoiceItem and ShipmentItem now reference each other. Invoice number is removed as primary key and placed with integer. NOTE: Class functions can be changed and added without migration. """ import sqlalchemy as sqla from sqlalchemy.orm import relationship as rel from sqlalchemy.orm import backref, sessionmaker from sqlalchemy.ext.declarative import declarative_base import datetime import json Int = sqla.Integer #Str = sqla.String #TODO: Can probably delete this line Utf = sqla.Unicode Float = sqla.Float Col = sqla.Column Bool = sqla.Boolean Date = sqla.Date DateTime = sqla.DateTime ForeignKey = sqla.ForeignKey Base = declarative_base() def today(): return datetime.datetime.now() def AddDictRepr(aClass): def repr_str(obj): '''Returns a string representation of the dictionary object with underscored keywords removed ("_keyword"). ''' copy = obj.__dict__.copy() for key in copy.keys(): if key.startswith(u'_'): try: del copy[key] except KeyError: pass return repr(copy) aClass.__repr__ = repr_str return aClass #============================================================================== # Order class #============================================================================== @AddDictRepr class Order(Base): __tablename__ = 'order' id = Col(Int, primary_key=True) group = Col(Utf(4), ForeignKey('cogroup.name'), nullable=False) # Of second party main company seller = Col(Utf(4), ForeignKey('branch.name'), nullable=False) # For billing/receipts buyer = Col(Utf(4), ForeignKey('branch.name'), nullable=False) # For billing/receipts parent = rel('CoGroup') recorddate = Col(DateTime, nullable=False, default=today) # Date of entering a record # Keep all product information in the outgoing product list MPN = Col(Utf(20), ForeignKey('product.MPN'), nullable=False) # Product code price = Col(Float) # Price for one SKU or unit on this order discount = Col(Int, nullable=False, default=0) # Discount percentage as integer (0-100) #XXX: name change in version 3: totalskus = Col(Int) qty = Col(Int, nullable=False) applytax = Col(Bool, nullable=False) # True = 5%, False = 0% #XXX: Remove in version 3 #totalunits = Col(Float) # AUTO: unitssku * totalskus #subtotal = Col(Float) #TODO: Remove and leave final totals in attached invoice. #totalcharge = Col(Int) #TODO: Remove orderdate = Col(Date, nullable=False) # Order placement date duedate = Col(Date) # Expected delivery date date = Col(Date) # Extra date field if needed orderID = Col(Utf(20)) # PO Number ordernote = Col(Utf(100)) # Information concerning the order note = Col(Utf(100)) # Extra note field if needed. checked = Col(Bool, nullable=False, default=False) # Match against second party records is_sale = Col(Bool, nullable=False, default=False) # Boolean. Customer is_purchase = Col(Bool, nullable=False, default=False) # Boolean. Supplier shipments = rel('ShipmentItem', backref='order') invoices = rel('InvoiceItem', backref='order') product = rel('Product') #XXX: New in version 3 is_open = Col(Bool, nullable=False, default=True) # Active or closed PO @property def units(self): return self.qty * self.product.units def shipped_value(self): '''Return the value of total shipped items.''' value = self.qty_shipped() * self.price if self.product.unitpriced: value = value * self.product.units if self.applytax: value = value * 1.05 return value def qty_shipped(self): '''By number of SKUs''' if len(self.shipments) == 0: return 0 return sum([srec.qty if isinstance(srec.qty,int) else 0 for srec in self.shipments]) def qty_remaining(self): '''By number of SKUs remaining to be shipped''' return int(self.qty - self.qty_shipped()) def all_shipped(self): '''By number of SKUs''' if len(self.shipments) == 0: return False return self.qty == self.qty_shipped() def qty_invoiced(self): '''By number of SKUs''' if len(self.invoices) == 0: return 0 return sum([prec.qty if isinstance(prec.qty,int) else 0 for prec in self.invoices]) def all_invoiced(self): '''By number of SKUs''' # if len(self.invoices) == 0: # return False return self.qty_shipped() == self.qty_invoiced() def total_paid(self): if len(self.invoices) == 0: return 0 return sum([prec.qty if prec.paid else 0 for prec in self.invoices]) def all_paid(self): if len(self.invoices) == 0: return False return not (False in [prec.invoice.paid for prec in self.invoices]) def qty_quote(self, qty): subtotal = self.price * qty if self.product.unitpriced: subtotal *= self.product.units return int(round(subtotal)) #============================================================================== # Shipment (track multiple shipments in SKU's for one order) #============================================================================== @AddDictRepr class Shipment(Base): # Keep track of shipments/SKUs for one order ''' #TODO: Separate manifest info and manifest items. order : backref to Order ''' __tablename__ = 'shipment' id = Col(Int, primary_key=True) shipmentdate = Col(Date, nullable=False) shipment_no = Col(Utf(20), default=u'') # i.e., Manifest number shipmentnote = Col(Utf(100), default=u'') # Information concerning the delivery shipmentdest = Col(Utf(100), default=u'') driver = Col(Utf(4)) # Track vehicle driver (optional) truck = Col(Utf(10)) # Track vehicle by license (optional) note = Col(Utf(100)) # Extra note field if needed checked = Col(Bool, nullable=False, default=False) # Extra boolean for matching/verifying items = rel('ShipmentItem', backref='shipment') # # METHODS # def listbox_summary(self): # """ # Return a single line unicode summary intended for a listbox. # """ # txt = u'{date:<10} 編號: {s.shipment_no:<10} QTY: {s.items[0].qty:>5} {s.order.product.SKU:<6} 品名: {s.order.product.inventory_name}' # txt = txt.format(s=self, date=str(self.shipmentdate)) # return txt @AddDictRepr class ShipmentItem(Base): __tablename__ = 'shipmentitem' id = Col(Int, primary_key=True) order_id = Col(Int, ForeignKey('order.id'), nullable=False) shipment_id = Col(Int, ForeignKey('shipment.id')) qty = Col(Int, nullable=False) # Deduct from total SKUs due lot = Col(Utf(20)) lot_start = Col(Int) lot_end = Col(Int) rt_no = Col(Utf(20)) duedate = Col(Date) shipped = Col(Bool, default=False) invoiceitem = rel('InvoiceItem', backref='shipmentitem') #============================================================================== # Invoice class (track multiple invoices for one order) #============================================================================== @AddDictRepr class Invoice(Base): # Keep track of invoices/payments for one order __tablename__ = 'invoice' #XXX: New in version 3, primary key change id = Col(Int, primary_key=True) invoice_no = Col(Utf(20), default=u'') # i.e., Invoice number seller = Col(Utf(4), ForeignKey('branch.name'), nullable=False) # For billing/receipts buyer = Col(Utf(4), ForeignKey('branch.name'), nullable=False) # For billing/receipts invoicedate = Col(Date, nullable=False) invoicenote = Col(Utf(100)) # Information concerning the invoice check_no = Col(Utf(20)) paid = Col(Bool, nullable=False, default=False) paydate = Col(Date) note = Col(Utf(100)) # Extra note field if needed checked = Col(Bool, nullable=False, default=False) # Extra boolean for matching/verifying items = rel('InvoiceItem', backref='invoice') def subtotal(self): return sum([item.subtotal() for item in self.items]) def tax(self): '''Tax is rounded to nearest integer before returning value.''' return int(round(self.subtotal() * 0.05)) def taxtotal(self): total = self.subtotal() + (self.tax() if self.items[0].order.applytax else 0) return int(round(total)) #============================================================================== # InvoiceItem class (track multiple products for one invoice) #============================================================================== @AddDictRepr class InvoiceItem(Base): # Keep track of invoices/payments for one order ''' order : backref to Order invoice : backref to Invoice shipmentitem : backref to ShipmentItem ''' __tablename__ = 'invoiceitem' id = Col(Int, primary_key=True) invoice_id = Col(Int, ForeignKey('invoice.id'), nullable=False) shipmentitem_id = Col(Int, ForeignKey('shipmentitem.id'), nullable=False) order_id = Col(Int, ForeignKey('order.id'), nullable=False) qty = Col(Int, nullable=False) def subtotal(self): subtotal = self.order.price * self.qty if self.order.product.unitpriced: subtotal *= self.order.product.units return int(round(subtotal,0)) def total(self): subtotal = self.subtotal() if self.order.applytax: subtotal *= 1.05 return int(round(subtotal,0)) # def listbox_summary(self): # """ # Return a single line unicode summary intended for a listbox. # """ # txt = u'{date:<10} 編號: {s.invoice_no:<10} QTY: {s.qty:>5} {s.order.product.SKU:<6} Subtotal: ${total:<6} 品名: {s.order.product.inventory_name}' # txt = txt.format(s=self, date=str(self.invoice.invoicedate), total=self.subtotal()) # return txt #============================================================================== # CoGroup (company grouping class for branches) #============================================================================== @AddDictRepr class CoGroup(Base): __tablename__ = 'cogroup' name = Col(Utf(4), primary_key=True, nullable=False) # Abbreviated name of company (2 to 4 chars) is_active = Col(Bool, nullable=False, default=True) # Boolean for listing the company. Continuing business. is_supplier = Col(Bool, nullable=False, default=True) # Maybe use in later versions is_customer = Col(Bool, nullable=False, default=True) # Maybe use in later versions branches = rel('Branch', backref='cogroup', lazy='joined') # lazy -> Attaches on retrieving a cogroup orders = rel('Order') products = rel('Product', backref='cogroup') contacts = rel('Contact') purchases = rel('Order', primaryjoin="and_(CoGroup.name==Order.group, Order.is_sale==False)") #Purchases FROM this company sales = rel('Order', primaryjoin="and_(CoGroup.name==Order.group, Order.is_sale==True)") #Sales TO this company openpurchases = rel('Order', primaryjoin="and_(CoGroup.name==Order.group, Order.is_sale==False, Order.is_open==True)") #Purchases FROM this company opensales = rel('Order', primaryjoin="and_(CoGroup.name==Order.group, Order.is_sale==True, Order.is_open==True)") #Sales TO this company #============================================================================== # Branch class #============================================================================== @AddDictRepr class Branch(Base): __tablename__ = 'branch' name = Col(Utf(4), primary_key=True, nullable=False) # Abbreviated name of company (2 to 4 chars) group= Col(Utf(4), ForeignKey('cogroup.name'), nullable=False) # Name of main company representing all branches fullname = Col(Utf(100), default=u'') english_name = Col(Utf(100), default=u'') tax_id = Col(Utf(8), nullable=False, default=u'') phone = Col(Utf(20), default=u'') fax = Col(Utf(20), default=u'') email = Col(Utf(20), default=u'') note = Col(Utf(100), default=u'') address_office = Col(Utf(100), default=u'') address_shipping = Col(Utf(100), default=u'') address_billing = Col(Utf(100), default=u'') address = Col(Utf(100), default=u'') # Extra address space if needed is_active = Col(Bool, nullable=False, default=True) # Boolean for listing the company. Continuing business. # parent = rel('CoGroup') contacts = rel('Contact') purchases = rel('Order', primaryjoin="and_(Branch.name==Order.seller, Order.is_sale==False)") #Purchases FROM this company sales = rel('Order', primaryjoin="and_(Branch.name==Order.buyer, Order.is_sale==True)") #Sales TO this company #============================================================================== # Contact class #============================================================================== @AddDictRepr class Contact(Base): __tablename__ = 'contact' id = Col(Int, primary_key=True) group = Col(Utf(4), ForeignKey('cogroup.name'), nullable=False) branch = Col(Utf(4), ForeignKey('branch.name')) name = Col(Utf(20), nullable=False) position = Col(Utf(20), default=u'') phone = Col(Utf(20), default=u'') fax = Col(Utf(20), default=u'') email = Col(Utf(20), default=u'') note = Col(Utf(100), default=u'') #============================================================================== # Product class #============================================================================== @AddDictRepr class Product(Base): # Information for each unique product (including packaging) __tablename__ = 'product' MPN = Col(Utf(20), primary_key=True) group = Col(Utf(4), ForeignKey('cogroup.name'), nullable=False) product_label = Col(Utf(100), default=u'') #Optional 2nd party product name inventory_name = Col(Utf(100), nullable=False) #Required english_name = Col(Utf(100), default=u'') units = Col(Float, nullable=False) #Units per SKU UM = Col(Utf(10), nullable=False) #Unit measurement SKU = Col(Utf(10), nullable=False) #Stock keeping unit (countable package) SKUlong = Col(Utf(100), default=u'') unitpriced = Col(Bool, nullable=False) ASE_PN = Col(Utf(20)) # ASE product number ASE_RT = Col(Utf(20)) # ASE department routing number ASE_END = Col(Int) # Last used SKU index number for current lot note = Col(Utf(100)) # {JSON} contains extra data, i.e. current ASE and RT numbers # {JSON} must be appended to the end after any notes. Last char == '}' is_supply = Col(Bool, nullable=False) discontinued = Col(Bool, nullable=False, default=False) curr_price = Col(Float, default=0.0) stock = rel('Stock', backref='product') orders = rel('Order', primaryjoin="Product.MPN==Order.MPN") @property def price(self): if self.curr_price.is_integer(): return int(self.curr_price) return self.curr_price @property def PrMeas(self): '''Return the unit measure associated with the price. PrMeas = pricing measure ''' return self.UM if self.unitpriced or self.SKU == u'槽車' else self.SKU def qty_available(self): available = dict( units = 0.0, SKUs = 0.0, value = 0.0, unit_value = None, SKU_value = None ) for each in self.stock: available['units'] += each.adj_unit available['SKUs'] += each.adj_SKU available['value'] += each.adj_value if available['units'] != 0.0: available['unit_value'] = available['value'] / available['units'] if available['SKUs'] != 0.0: available['SKU_value'] = available['value'] / available['SKUs'] return available def label(self): '''Returns product_label, which is the client desired name. If a product_label does not exist, then return our inventory_name for the product. ''' if self.product_label != u'': return self.product_label else: return self.inventory_name @property def name(self): '''Returns product_label, which is the client desired name. If a product_label does not exist, then return our inventory_name for the product. ''' if self.product_label != u'': return self.product_label else: return self.inventory_name @property def specs(self): '''Short text of product key values. "## UM SKU" e.g. "20 kg barrel" ''' u = self.units units = int(u) if int(u)==u else u #Truncate if mantissa is zero if self.SKU == u'槽車': return u'槽車-{}'.format(self.UM) else: txt = u"{0} {1} {2}" return txt.format(units,self.UM,self.SKU) def json(self, new_dic=None): '''Saves 'new_dic' as a json string and overwrites previous json. Returns contents of json string as a dictionary object. Note: Commit session after making changes.''' if new_dic == None: if self.note.find(u'}') != -1: return json.loads(self.note[self.note.index(u'{'):]) else: return {} else: old_dic = dict() # Delete existing json string if self.note.find(u'}') != -1: old_dic = self.json() self.note = self.note.split(u'{')[0] # Merge and overwrite old with new. new_dic = dict(old_dic.items() + new_dic.items()) self.note += json.dumps(new_dic) return True return False #============================================================================== # Stock class #============================================================================== @AddDictRepr class Stock(Base): #For warehouse transactions __tablename__ = 'stock' id = Col(Int, primary_key=True) MPN = Col(Utf(20), ForeignKey('product.MPN'), nullable=False) date = Col(Date, nullable=False) adj_unit = Col(Float, nullable=False) #Use units for stock amounts adj_SKU = Col(Float) #Probably will NOT use this adj_value = Col(Float, nullable=False) #Value of units in transaction note = Col(Utf(100)) #============================================================================== # Vehicle class #============================================================================== @AddDictRepr class Vehicle(Base): __tablename__ = 'vehicle' id = Col(Utf(10), primary_key=True) #license plate number purchasedate = Col(Date) description = Col(Utf(100)) value = Col(Float) note = Col(Utf(100)) #============================================================================== # Database loading method #============================================================================== def get_database(db_path, echo=False): '''Opens a database and returns an 'engine' object.''' database = sqla.create_engine(db_path, echo=echo) Base.metadata.create_all(database) #FIRST TIME SETUP ONLY return database #============================================================================== # Testing and Debugging #============================================================================== if __name__ == '__main__': engine = get_database(u'test.db', echo=False) session = sessionmaker(bind=engine)() session.add(Vehicle(id=u'MONKEY')) veh = session.query(Vehicle).get(u'MONKEY') print veh print veh.__dict__ order = Order(orderID=u'ZV1234', seller=u'Oscorp', buyer=u'Marvel', group=u'DC comics', is_sale=True, MPN=666, subtotal=1000, duedate=datetime.date.today(), totalskus=24) product = Product(MPN=666, group=u'DC comics', units=12, UM=u'ounce', SKU=u'vial', unitpriced=False, is_supply=False, product_label=u'Muscle Juice', inventory_name=u'serim 234') shipment = Shipment(shipment_no=u'003568', qty=10, order=order, shipmentdate=datetime.date.today()) session.add(product) session.add(order) order = session.query(Order).first() print 'order', order print order.formatted() for each in order.shipments: print each.listbox_summary()
gpl-2.0
-3,743,926,320,139,685,400
35.795009
181
0.57446
false
3.853996
false
false
false
drewkhoury/aws-daredevil
daredevil.py
1
2729
import boto3 from pprint import pprint from datetime import datetime import time def make_tag_dict(ec2_object): """Given an tagable ec2_object, return dictionary of existing tags.""" tag_dict = {} if ec2_object.tags is None: return tag_dict for tag in ec2_object.tags: tag_dict[tag['Key']] = tag['Value'] return tag_dict def make_tag_string(ec2_object): """Given an tagable ec2_object, return string of existing tags.""" tag_string = '' if ec2_object.tags is None: return tag_string for tag in ec2_object.tags: tag_string = tag_string + tag['Key'] + "=" + tag['Value'] + " " return tag_string def time_difference(the_time): # convert to timestamp the_time_ts = time.mktime(the_time.timetuple()) # current time as timestamp now = datetime.utcnow() now_ts = time.mktime(now.timetuple()) # find the difference in days (how many days the instance has been up) difference_ts = now_ts-the_time_ts return ( difference_ts/60/60/24 ) def get_ec2_instances(region): print '' print "REGION: %s" % (region) print '-----------------------' ec2 = boto3.resource('ec2', region_name=region) instances = ec2.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) for instance in instances: # nicer structures tag_dict = make_tag_dict(instance) tag_string = make_tag_string(instance) # clean the name if 'Name' in tag_dict: clean_name = tag_dict['Name'] else: clean_name = '<no-name>' # find out how many days the EC2 has been running days_running = time_difference(instance.launch_time) days_running = round(days_running,2) # print the info print "%s - %s - %s - %s - %s - %s - %s - %s days running" % (instance.vpc_id, instance.subnet_id, instance.id, instance.image_id, instance.instance_type, instance.state['Name'], clean_name, days_running)#, instance.launch_time, tag_string) #pprint (instance.__dict__) #print "this is the {id} ".format(**instance.__dict__) def lambda_handler(event, context): print '-------------------------' print '----- start -----' print '' # regions = ['us-east-1','us-west-2','us-west-1','eu-west-1','eu-central-1','ap-southeast-1','ap-southeast-2','ap-northeast-1','sa-east-1'] # quicker regions = ['ap-southeast-2','ap-northeast-1'] for region in regions: get_ec2_instances(region) print '' print '----- end -----' print '-------------------------' return 'foo'
mit
3,425,234,492,745,836,500
30.744186
248
0.573104
false
3.61457
false
false
false
JPalmerio/GRB_population_code
catalogs/GBM_cat/GBM_Ep_constraint_testing.py
1
1178
import sys import platform if platform.system() == 'Linux': sys.path.insert(0,'/nethome/palmerio/Dropbox/Plotting_GUI/Src') elif platform.system() == 'Darwin': sys.path.insert(0,'/Users/palmerio/Dropbox/Plotting_GUI/Src') import numpy as np import matplotlib import matplotlib.pyplot as plt import plotting_functions as pf from matplotlib.transforms import blended_transform_factory plt.style.use('ggplot') fig = plt.figure() ax = fig.add_subplot(111) root_dir = '/nethome/palmerio/1ere_annee/Frederic/GRB_population_code/Model_outputs/' filename = root_dir +'run_LIA/EpGBM_constraint.dat' Ep_bins = pf.read_data(filename, 0) Ep_hist_mod = pf.read_data(filename, 1) Ep_hist_obs = pf.read_data(filename, 2) x=np.linspace(1.,4., 500) y = max(Ep_hist_obs) * pf.gaussian(x, 2.25, 0.35) y2 = max(Ep_hist_obs) * pf.gaussian(x, 2.25, 0.375) ep = np.linspace(1,4, 100) ep_gauss = pf.gaussian(ep, 2.2, 0.4)*max(Ep_hist_obs) ax.plot(Ep_bins, Ep_hist_obs, label = 'Observations') #ax.plot(Ep_bins, Ep_hist_mod, label = 'MC simulation') #ax.plot(ep, ep_gauss, ls=':', lw=2) ax.plot(x,y, label='gaussian') ax.plot(x,y2, label='gaussian2') ax.legend(loc='best') plt.show()
gpl-3.0
6,795,155,745,150,622,000
24.06383
85
0.705433
false
2.495763
false
true
false
Ken69267/gpytage
gpytage/rename.py
1
4560
#!/usr/bin/env python # # rename.py GPytage module # ############################################################################ # Copyright (C) 2009-2010 by Kenneth Prugh # # ken69267@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 under version 2 of the license. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the # # Free Software Foundation, Inc., # # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################ import pygtk; pygtk.require("2.0") import gtk from config import get_config_path from datastore import reinitializeDatabase from PackageFileObj import PackageFileObj from FolderObj import FolderObj from sys import stderr from os import rename from errorDialog import errorDialog from fileOperations import ensureNotModified msg = "A file cannot be renamed with unsaved changes. Please save your changes." def renameFile(*args): """ Renames the currently selected file """ from leftpanel import leftview model, iter = leftview.get_selection().get_selected() from datastore import F_REF try: object = model.get_value(iter, F_REF) if isinstance(object, PackageFileObj): # A file type = "File" if object.parent == None: setFolder = get_config_path() else: setFolder = object.parent.path elif isinstance(object, FolderObj): # A folder type = "Directory" setFolder = object.parent.path if ensureNotModified(msg): __createRenameDialog(object, type, setFolder) except TypeError,e: print >>stderr, "__renameFile:",e def __createRenameDialog(object, type, setFolder): """ Spawms the Rename Dialog where a user can choose what the file should be renamed to """ fc = gtk.FileChooserDialog("Rename file...", None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) fc.set_do_overwrite_confirmation(True) fc.set_filename(object.path) #Set the fc to the object to be renamed fc.set_extra_widget(gtk.Label("Renaming " + object.path)) response = fc.run() if response == gtk.RESPONSE_ACCEPT: if fc.get_filename() != None: __writeRenamedFile(object.path, fc.get_filename()) reinitializeDatabase() __reselectAfterRename(fc.get_filename(), type) else: print >>stderr, "Invalid rename request" fc.destroy() def __writeRenamedFile(oldFile, newFile): """ Performs the actual renaming of the file """ try: rename(oldFile, newFile) print oldFile + " renamed to " + newFile except OSError,e: print >>stderr, "Rename: ",e d = errorDialog("Error Renaming...", str(e)) d.spawn() def __reselectAfterRename(filePath, type): """ Reselects the parent folder of the deleted object """ from leftpanel import leftview model = leftview.get_model() model.foreach(getMatch, [filePath, leftview, type]) def getMatch(model, path, iter, data): """ Obtain the match and perform the selection """ testObject = model.get_value(iter, 1) #col 1 stores the reference # clarify values passed in from data list filePath = data[0] leftview = data[1] #type = data[2] if testObject.path == filePath: # We found the file object we just renamed, lets select it leftview.expand_to_path(path) leftview.set_cursor(path, None, False) return True else: return False
gpl-2.0
-8,155,855,760,534,155,000
41.616822
80
0.573465
false
4.359465
false
false
false
kevindiltinero/seass3
src/thefile.py
1
1064
def get_cmmds(filename): values = [] next = [] final = [] file = open(filename, 'r') for line in file: values.append(line.split(' ')) for i in range(len(values)): for j in range(4): temporary = values[i][j] if temporary.endswith('\n'): next.append(temporary[:-1]) else: next.append(temporary) for i in range(len(next)): temporary = next[i] if ',' in temporary: bridge = temporary.split(',') for element in bridge: final.append(element) else: final.append(temporary) sublist = [final[n:n+6] for n in range(0, len(final), 6)] return sublist def execute_cmmds(seats, cmmd, x1, y1, blank, x2, y2): if cmmd == toggle: seats = toggle.toggle_it(x1, y1, x2, y2, seats) elif cmmd == empty: seats = empty.empty_it(x1, y1, x2, y2, seats) elif cmmd == occupy: seats = occupy.occupy_seats(x1, y1, x2, y2, seats)
bsd-2-clause
-2,216,852,053,547,423,700
27.783784
61
0.511278
false
3.377778
false
false
false
anna-effeindzourou/trunk
examples/anna_scripts/tilt/tilttest_box.py
1
9173
# -*- coding: utf-8 from yade import ymport,utils,pack,export,qt,bodiesHandling import gts,os # for plotting from math import * from yade import plot ############################ ### DEFINING PARAMETERS ### ############################ #GEOMETRIC :dimension of the rectangular box a=.2 # side dimension h=.1 # height #MATERIAL PROPERTIES frictionAngle=radians(35) density=2700 Kn=25e7 #normal stiffness Plassiard thesis Ks=5e7 #tangential stiffness Plassiard thesis #PARTICLE SIZE Rs=0.015# mean particle radius Rf=0.5 # dispersion (Rs±Rf*Rs) nSpheres=2000# number of particles #ENGINES PARAMETERS g=9.81 damping_coeff = 0.5 #MATERIAL'S PARAMETERS #box young_box=30e5 poison_box=0.25 friction_box=radians(10) density_box=1576. #gravel G=40e5 poisson_g=0.25 young_g=30e5 m=1.878 v=(4*pi*pow(Rs,3))/3 #TIME STEP dt=1.e-7 #TAG #################### ### ENGINES ### #################### O.engines=[ ForceResetter(), InsertionSortCollider([ Bo1_Sphere_Aabb(), Bo1_GridConnection_Aabb(), Bo1_PFacet_Aabb() ]), InteractionLoop([ Ig2_GridNode_GridNode_GridNodeGeom6D(), Ig2_Sphere_PFacet_ScGridCoGeom(), Ig2_GridConnection_GridConnection_GridCoGridCoGeom(), Ig2_GridConnection_PFacet_ScGeom(), Ig2_Sphere_GridConnection_ScGridCoGeom(), Ig2_Sphere_Sphere_ScGeom(), Ig2_PFacet_PFacet_ScGeom() ], [Ip2_CohFrictMat_CohFrictMat_CohFrictPhys(setCohesionNow=True,setCohesionOnNewContacts=False), Ip2_FrictMat_FrictMat_FrictPhys()], [Law2_ScGeom6D_CohFrictPhys_CohesionMoment(), Law2_ScGeom_FrictPhys_CundallStrack(), Law2_ScGridCoGeom_FrictPhys_CundallStrack(),Law2_GridCoGridCoGeom_FrictPhys_CundallStrack() ] ), ] ############################ ### DEFINING MATERIAL ### ############################ O.materials.append(CohFrictMat(young=young_box,poisson=poison_box,density=density,frictionAngle=friction_box,normalCohesion=1e19,shearCohesion=1e19,momentRotationLaw=True,alphaKr=5,label='NodeMat')) boxMat = O.materials.append(FrictMat(young=young_box ,poisson=poison_box,frictionAngle=friction_box,density=density)) sphereMat = O.materials.append(FrictMat(young=young_box ,poisson=poison_box,frictionAngle=friction_box,density=density)) rWall=0.05 x=a/2.+rWall y=0 z=0 fac=2.+rWall clump=0 color=Vector3(1,0,0) fixed=False rWall=0.008 #### define box nodesIds=[] nodesIds.append( O.bodies.append(gridNode([-x,-y,h+fac*rWall],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([x,-y,h+fac*rWall],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([x,-y,2*h+fac*rWall],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([-x,-y,2*h+fac*rWall],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([-x,2*x,h+fac*rWall],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([x,2*x,h+fac*rWall],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([x,2*x,2*h+fac*rWall],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([-x,2*x,2*h+fac*rWall],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) cylIds=[] pfIds=[] pfIds.append(pfacetCreator3(nodesIds[0],nodesIds[1],nodesIds[2],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[0],nodesIds[2],nodesIds[3],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) #pfIds.append(pfacetCreator3(nodesIds[1],nodesIds[5],nodesIds[2],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) #pfIds.append(pfacetCreator3(nodesIds[5],nodesIds[6],nodesIds[2],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[5],nodesIds[6],nodesIds[1],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[6],nodesIds[2],nodesIds[1],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[7],nodesIds[6],nodesIds[4],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[6],nodesIds[5],nodesIds[4],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) #pfIds.append(pfacetCreator3(nodesIds[0],nodesIds[4],nodesIds[3],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) #pfIds.append(pfacetCreator3(nodesIds[4],nodesIds[7],nodesIds[3],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[7],nodesIds[0],nodesIds[4],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[0],nodesIds[7],nodesIds[3],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=True,mask=-1)) nbodies=[] #O.step() for i in nodesIds: O.bodies[i].state.blockedDOFs='x' #nbodies.append(O.bodies[i]) #clump,clumpIds=O.bodies.appendClumped(nbodies) #O.bodies[clump].state.blockedDOFs='xyzXYZ' fixed=True nodesIds=[] nodesIds.append( O.bodies.append(gridNode([-x,-y,0],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([x,-y,0],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([x,-y,h],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([-x,-y,h],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([-x,2*x,0],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([x,2*x,0],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([x,2*x,h],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) nodesIds.append( O.bodies.append(gridNode([-x,2*x,h],rWall,wire=False,fixed=fixed,material='NodeMat',color=color)) ) cylIds=[] pfIds=[] pfIds.append(pfacetCreator3(nodesIds[0],nodesIds[1],nodesIds[2],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[0],nodesIds[2],nodesIds[3],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[1],nodesIds[5],nodesIds[2],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[5],nodesIds[6],nodesIds[2],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[7],nodesIds[6],nodesIds[4],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[6],nodesIds[5],nodesIds[4],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[0],nodesIds[4],nodesIds[3],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[4],nodesIds[7],nodesIds[3],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[0],nodesIds[1],nodesIds[5],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) pfIds.append(pfacetCreator3(nodesIds[4],nodesIds[0],nodesIds[5],cylIds=cylIds,pfIds=pfIds,wire=False,material=boxMat,Ecyl=None,color=color,fixed=fixed,mask=-1)) ############################ ### DEFINING ENGINES ### ############################ init=0 para=1000 coll=100 def rotate(): global init init=O.iter Newton_Integrator.damping=0.2 #for i in nodesIds1: #O.bodies[i].state.blockedDOFs='x' #O.bodies[clump].state.blockedDOFs='x' O.engines+=[ RotationEngine(ids=idsToRotate,angularVelocity=angularVelocity,rotateAroundZero=True,zeroPoint=(-rWall,0,0),rotationAxis=(1,0,0),label='rotationEngine'), #VTKRecorder(iterPeriod=para,dead=True,initRun=True,fileName='paraview/'+O.tags['description']+'_',recorders=['spheres','velocity','intr','materialId'],label='parav'), #PyRunner(initRun=True,iterPeriod=coll,command='dataCollector()') ] angularVelocity=0.1 idsToRotate=nodesIds O.dt=0.0001 O.engines+=[NewtonIntegrator(gravity=(0,0,-9.81),damping=0.2,label='Newton_Integrator')] ############################ ### VISUALIZATION ### ############################ renderer = qt.Renderer() qt.View() O.saveTmp() #O.run() def getAngle(): alpha=angularVelocity*O.iter*O.dt/pi*180. print 'alpha = ', alpha
gpl-2.0
7,845,792,730,657,617,000
38.029787
198
0.744331
false
2.484963
false
false
false
sibskull/synaptiks
tests/kde/widgets/test_config.py
1
5513
# -*- coding: utf-8 -*- # Copyright (c) 2011, Sebastian Wiesner <lunaryorn@googlemail.com> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from __future__ import (print_function, division, unicode_literals, absolute_import) import pytest config = pytest.importorskip('synaptiks.kde.widgets.config') from PyQt4.QtCore import pyqtSignal from PyQt4.QtGui import QWidget, QHBoxLayout, QCheckBox, QLineEdit class DummyConfig(dict): """ A dummy configuration object for use in the tests. """ @property def defaults(self): return {'lineedit': 'spam', 'checkbox': False} class DummyConfigWidget(QWidget, config.ConfigurationWidgetMixin): NAME_PREFIX = 'dummy' PROPERTY_MAP = dict(QCheckBox='checked', QLineEdit='text') CHANGED_SIGNAL_MAP = dict(QCheckBox='toggled', QLineEdit='textChanged') configurationChanged = pyqtSignal(bool) def __init__(self, config, parent=None): QWidget.__init__(self, parent) layout = QHBoxLayout(self) self.setLayout(layout) self.checkbox = QCheckBox(self) self.checkbox.setObjectName('dummy_checkbox') layout.addWidget(self.checkbox) self.lineedit = QLineEdit(self) self.lineedit.setObjectName('dummy_lineedit') layout.addWidget(self.lineedit) self._setup(config) def change(self, text, check_state): self.lineedit.setText(text) self.checkbox.setChecked(check_state) def check(self, text, check_state): __tracebackhide__ = True assert unicode(self.lineedit.text()) == text assert self.checkbox.isChecked() == check_state def pytest_funcarg__config(request): return DummyConfig({'lineedit': 'spam', 'checkbox': False}) def pytest_funcarg__config_widget(request): # we must have a qt app object before we can construct widgets request.getfuncargvalue('qtapp') return DummyConfigWidget(request.getfuncargvalue('config')) class TestConfigurationWidgetMixin(object): def test_setup_no_defaults_attribute(self, qtapp, config): invalid_config = dict(config) assert not hasattr(invalid_config, 'defaults') with pytest.raises(TypeError) as exc_info: DummyConfigWidget(invalid_config) msg = 'The given configuration does not provide defaults' assert str(exc_info.value) == msg def test_setup(self, config_widget): config_widget.check('spam', False) def test_configuration_changed(self, config_widget): signal_calls = [] config_widget.configurationChanged.connect(signal_calls.append) config_widget.change('eggs', True) assert signal_calls == [True, True] del signal_calls[:] config_widget.apply_configuration() signal_calls == [False] del signal_calls[:] config_widget.load_defaults() assert signal_calls == [True, True] del signal_calls[:] config_widget.load_configuration() assert signal_calls == [True, False] def test_is_configuration_changed(self, config_widget): assert not config_widget.is_configuration_changed config_widget.change('eggs', True) assert config_widget.is_configuration_changed config_widget.apply_configuration() assert not config_widget.is_configuration_changed def test_load_defaults(self, config_widget): config_widget.change('eggs', True) assert not config_widget.shows_defaults() config_widget.load_defaults() assert config_widget.shows_defaults() config_widget.check('spam', False) def test_shows_defaults(self, config, config_widget): assert config_widget.shows_defaults() config_widget.change('eggs', True) assert not config_widget.shows_defaults() def test_load_configuration(self, config, config_widget): config['checkbox'] = True config['lineedit'] = 'eggs' config_widget.load_configuration() config_widget.check('eggs', True) def test_apply_configuration(self, config, config_widget): config_widget.change('eggs', True) config_widget.apply_configuration() assert config == {'lineedit': 'eggs', 'checkbox': True}
bsd-2-clause
-2,184,364,509,986,881,300
37.552448
77
0.695629
false
4.201982
true
false
false
toirl/cointrader
cointrader/strategy.py
1
2832
#!/usr/bin/env python import datetime import logging from cointrader.indicators import ( WAIT, BUY, SELL, Signal, macdh_momententum, macdh, double_cross ) log = logging.getLogger(__name__) class Strategy(object): """Docstring for Strategy. """ def __str__(self): return "{}".format(self.__class__) def __init__(self): self.signals = {} """Dictionary with details on the signal(s) {"indicator": {"signal": 1, "details": Foo}}""" def signal(self, chart): """Will return either a BUY, SELL or WAIT signal for the given market""" raise NotImplementedError class NullStrategy(Strategy): """The NullStrategy does nothing than WAIT. It will emit not BUY or SELL signal and is therefor the default strategy when starting cointrader to protect the user from loosing money by accident.""" def signal(self, chart): """Will return either a BUY, SELL or WAIT signal for the given market""" signal = Signal(WAIT, datetime.datetime.utcnow()) self.signals["WAIT"] = signal return signal class Klondike(Strategy): def signal(self, chart): signal = macdh_momententum(chart) self.signals["MACDH_MOMEMENTUM"] = signal if signal.buy: return signal elif signal.sell: return signal return Signal(WAIT, datetime.datetime.utcfromtimestamp(chart.date)) class Followtrend(Strategy): """Simple trend follow strategie.""" def __init__(self): Strategy.__init__(self) self._macd = WAIT def signal(self, chart): # Get current chart closing = chart.values() self._value = closing[-1][1] self._date = datetime.datetime.utcfromtimestamp(closing[-1][0]) # MACDH is an early indicator for trend changes. We are using the # MACDH as a precondition for trading signals here and required # the MACDH signal a change into a bullish/bearish market. This # signal stays true as long as the signal changes. macdh_signal = macdh(chart) if macdh_signal.value == BUY: self._macd = BUY if macdh_signal.value == SELL: self._macd = SELL log.debug("macdh signal: {}".format(self._macd)) # Finally we are using the double_cross signal as confirmation # of the former MACDH signal dc_signal = double_cross(chart) if self._macd == BUY and dc_signal.value == BUY: signal = dc_signal elif self._macd == SELL and dc_signal.value == SELL: signal = dc_signal else: signal = Signal(WAIT, dc_signal.date) log.debug("Final signal @{}: {}".format(signal.date, signal.value)) self.signals["DC"] = signal return signal
mit
1,515,232,139,479,647,000
29.782609
75
0.614054
false
3.900826
false
false
false
duembeg/gsat
modules/wnd_main_config.py
1
10359
"""---------------------------------------------------------------------------- wnd_main_config.py Copyright (C) 2013-2020 Wilhelm Duembeg This file is part of gsat. gsat is a cross-platform GCODE debug/step for Grbl like GCODE interpreters. With features similar to software debuggers. Features such as breakpoint, change current program counter, inspection and modification of variables. gsat 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. gsat 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 gsat. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------""" import os import sys import glob import serial import re import time import shutil import logging import wx import wx.combo # from wx import stc as stc # from wx.lib.mixins import listctrl as listmix from wx.lib.agw import aui as aui from wx.lib.agw import floatspin as fs from wx.lib.agw import genericmessagedialog as gmd # from wx.lib.agw import flatmenu as fm from wx.lib.wordwrap import wordwrap from wx.lib import scrolledpanel as scrolled import modules.config as gc import modules.machif_config as mi import images.icons as ico import modules.wnd_editor_config as edc import modules.wnd_machine_config as mcc import modules.wnd_jogging_config as jogc import modules.wnd_cli_config as clic import modules.wnd_compvision_config as compvc class gsatGeneralSettingsPanel(scrolled.ScrolledPanel): """ General panel settings """ def __init__(self, parent, configData, **args): scrolled.ScrolledPanel.__init__( self, parent, style=wx.TAB_TRAVERSAL | wx.NO_BORDER) self.configData = configData self.InitUI() self.SetAutoLayout(True) self.SetupScrolling() # self.FitInside() def InitUI(self): font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD) vBoxSizer = wx.BoxSizer(wx.VERTICAL) # run time dialog settings st = wx.StaticText(self, label="General") st.SetFont(font) vBoxSizer.Add(st, 0, wx.ALL, border=5) # Add file save backup check box self.cbDisplayRunTimeDialog = wx.CheckBox( self, wx.ID_ANY, "Display run time dialog at program end") self.cbDisplayRunTimeDialog.SetValue( self.configData.get('/mainApp/DisplayRunTimeDialog')) vBoxSizer.Add(self.cbDisplayRunTimeDialog, flag=wx.LEFT, border=25) # file settings st = wx.StaticText(self, label="Files") st.SetFont(font) vBoxSizer.Add(st, 0, wx.ALL, border=5) # Add file save backup check box self.cbBackupFile = wx.CheckBox( self, wx.ID_ANY, "Create a backup copy of file before saving") self.cbBackupFile.SetValue(self.configData.get('/mainApp/BackupFile')) vBoxSizer.Add(self.cbBackupFile, flag=wx.LEFT, border=25) # Add file history spin ctrl hBoxSizer = wx.BoxSizer(wx.HORIZONTAL) self.scFileHistory = wx.SpinCtrl(self, wx.ID_ANY, "") self.scFileHistory.SetRange(0, 100) self.scFileHistory.SetValue( self.configData.get('/mainApp/FileHistory/FilesMaxHistory')) hBoxSizer.Add(self.scFileHistory, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=5) st = wx.StaticText(self, wx.ID_ANY, "Recent file history size") hBoxSizer.Add(st, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=5) vBoxSizer.Add(hBoxSizer, 0, flag=wx.LEFT | wx.EXPAND, border=20) # tools settings st = wx.StaticText(self, label="Tools") font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD) st.SetFont(font) vBoxSizer.Add(st, 0, wx.ALL, border=5) # Add Inch to mm round digits spin ctrl hBoxSizer = wx.BoxSizer(wx.HORIZONTAL) self.scIN2MMRound = wx.SpinCtrl(self, wx.ID_ANY, "") self.scIN2MMRound.SetRange(0, 100) self.scIN2MMRound.SetValue( self.configData.get('/mainApp/RoundInch2mm')) hBoxSizer.Add(self.scIN2MMRound, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=5) st = wx.StaticText(self, wx.ID_ANY, "Inch to mm round digits") hBoxSizer.Add(st, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=5) vBoxSizer.Add(hBoxSizer, 0, flag=wx.LEFT | wx.EXPAND, border=20) # Add mm to Inch round digits spin ctrl hBoxSizer = wx.BoxSizer(wx.HORIZONTAL) self.scMM2INRound = wx.SpinCtrl(self, wx.ID_ANY, "") self.scMM2INRound.SetRange(0, 100) self.scMM2INRound.SetValue( self.configData.get('/mainApp/Roundmm2Inch')) hBoxSizer.Add(self.scMM2INRound, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=5) st = wx.StaticText(self, wx.ID_ANY, "mm to Inch round digits") hBoxSizer.Add(st, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=5) vBoxSizer.Add(hBoxSizer, 0, flag=wx.LEFT | wx.EXPAND, border=20) self.SetSizer(vBoxSizer) def UpdateConfigData(self): self.configData.set('/mainApp/DisplayRunTimeDialog', self.cbDisplayRunTimeDialog.GetValue()) self.configData.set('/mainApp/BackupFile', self.cbBackupFile.GetValue()) self.configData.set('/mainApp/FileHistory/FilesMaxHistory', self.scFileHistory.GetValue()) self.configData.set('/mainApp/RoundInch2mm', self.scIN2MMRound.GetValue()) self.configData.set('/mainApp/Roundmm2Inch', self.scMM2INRound.GetValue()) class gsatSettingsDialog(wx.Dialog): """ Dialog to control program settings """ def __init__(self, parent, configData, id=wx.ID_ANY, title="Settings", style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER): wx.Dialog.__init__(self, parent, id, title, style=style) self.configData = configData self.InitUI() def InitUI(self): sizer = wx.BoxSizer(wx.VERTICAL) # init note book self.imageList = wx.ImageList(16, 16) self.imageList.Add(ico.imgGeneralSettings.GetBitmap()) # self.imageList.Add(ico.imgPlugConnect.GetBitmap()) self.imageList.Add(ico.imgProgram.GetBitmap()) self.imageList.Add(ico.imgLog.GetBitmap()) self.imageList.Add(ico.imgCli.GetBitmap()) self.imageList.Add(ico.imgMachine.GetBitmap()) self.imageList.Add(ico.imgMove.GetBitmap()) self.imageList.Add(ico.imgEye.GetBitmap()) # for Windows and OS X, tabbed on the left don't work as well if sys.platform.startswith('linux'): self.noteBook = wx.Notebook( self, size=(700, 400), style=wx.BK_LEFT) else: self.noteBook = wx.Notebook(self, size=(700, 400)) self.noteBook.AssignImageList(self.imageList) # add pages self.AddGeneralPage(0) self.AddProgramPage(1) self.AddOutputPage(2) self.AddCliPage(3) self.AddMachinePage(4) self.AddJoggingPage(5) self.AddCV2Panel(6) # self.noteBook.Layout() sizer.Add(self.noteBook, 1, wx.ALL | wx.EXPAND, 5) # buttons line = wx.StaticLine(self, -1, size=(20, -1), style=wx.LI_HORIZONTAL) sizer.Add(line, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT | wx.TOP, border=5) btnsizer = wx.StdDialogButtonSizer() btn = wx.Button(self, wx.ID_OK) btnsizer.AddButton(btn) btn = wx.Button(self, wx.ID_CANCEL) btnsizer.AddButton(btn) btnsizer.Realize() sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5) self.SetSizerAndFit(sizer) # self.SetAutoLayout(True) self.Layout() def AddGeneralPage(self, page): self.generalPage = gsatGeneralSettingsPanel( self.noteBook, self.configData) self.noteBook.AddPage(self.generalPage, "General") self.noteBook.SetPageImage(page, page) def AddProgramPage(self, page): self.programPage = edc.gsatStyledTextCtrlSettingsPanel( self.noteBook, self.configData, "code") self.noteBook.AddPage(self.programPage, "Program") self.noteBook.SetPageImage(page, page) def AddOutputPage(self, page): self.outputPage = edc.gsatStyledTextCtrlSettingsPanel( self.noteBook, self.configData, "output") self.noteBook.AddPage(self.outputPage, "Output") self.noteBook.SetPageImage(page, page) def AddCliPage(self, page): self.cliPage = clic.gsatCliSettingsPanel(self.noteBook, self.configData) self.noteBook.AddPage(self.cliPage, "Cli") self.noteBook.SetPageImage(page, page) def AddMachinePage(self, page): self.machinePage = mcc.gsatMachineSettingsPanel( self.noteBook, self.configData) self.noteBook.AddPage(self.machinePage, "Machine") self.noteBook.SetPageImage(page, page) def AddJoggingPage(self, page): self.jogPage = jogc.gsatJoggingSettingsPanel( self.noteBook, self.configData) self.noteBook.AddPage(self.jogPage, "Jogging") self.noteBook.SetPageImage(page, page) def AddCV2Panel(self, page): self.CV2Page = compvc.gsatCV2SettingsPanel( self.noteBook, self.configData) self.noteBook.AddPage(self.CV2Page, " OpenCV2") self.noteBook.SetPageImage(page, page) def UpdateConfigData(self): self.generalPage.UpdateConfigData() self.programPage.UpdateConfigData() self.outputPage.UpdateConfigData() self.cliPage.UpdateConfigData() self.machinePage.UpdateConfigData() self.jogPage.UpdateConfigData() self.CV2Page.UpdateConfigData()
gpl-2.0
-5,809,503,624,998,932,000
36.129032
80
0.643498
false
3.600626
true
false
false
ifding/ifding.github.io
stylegan2-ada/metrics/clustering.py
1
4125
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """Inception Score (IS) from the paper "Improved techniques for training GANs".""" import pickle import numpy as np import tensorflow as tf import dnnlib import dnnlib.tflib as tflib from metrics import metric_base from training import dataset from sklearn.metrics.cluster import normalized_mutual_info_score, adjusted_rand_score def compute_purity(y_pred, y_true): """ Calculate the purity, a measurement of quality for the clustering results. Each cluster is assigned to the class which is most frequent in the cluster. Using these classes, the percent accuracy is then calculated. Returns: A number between 0 and 1. Poor clusterings have a purity close to 0 while a perfect clustering has a purity of 1. """ # get the set of unique cluster ids clusters = set(y_pred) # find out what class is most frequent in each cluster cluster_classes = {} correct = 0 for cluster in clusters: # get the indices of rows in this cluster indices = np.where(y_pred == cluster)[0] cluster_labels = y_true[indices] majority_label = np.argmax(np.bincount(cluster_labels)) correct += np.sum(cluster_labels == majority_label) #cor = np.sum(cluster_labels == majority_label) #print(cluster, len(indices), float(cor)/len(indices)) return float(correct) / len(y_pred) #---------------------------------------------------------------------------- class CL(metric_base.MetricBase): def __init__(self, num_images, num_splits, minibatch_per_gpu, **kwargs): super().__init__(**kwargs) self.num_images = num_images self.num_splits = num_splits self.minibatch_per_gpu = minibatch_per_gpu def _evaluate(self, E, G_kwargs, num_gpus, **_kwargs): # pylint: disable=arguments-differ minibatch_size = num_gpus * self.minibatch_per_gpu dataset_obj = dataset.load_dataset(**self._dataset_args) dataset_obj.configure(minibatch_size) trues = np.empty([self.num_images, 10], dtype=np.int32) preds = np.empty([self.num_images, 10], dtype=np.float32) # Construct TensorFlow graph. result_expr = [] true_labels = [] for gpu_idx in range(num_gpus): with tf.device(f'/gpu:{gpu_idx}'): E_clone = E.clone() images, labels = dataset_obj.get_minibatch_tf() outputs = E_clone.get_output_for(images, labels, **G_kwargs) output_logits = outputs[:, 512:] output_labels = tf.nn.softmax(output_logits) result_expr.append(output_labels) true_labels.append(labels) # Calculate activations for fakes. for begin in range(0, self.num_images, minibatch_size): self._report_progress(begin, self.num_images) end = min(begin + minibatch_size, self.num_images) trues[begin:end] = np.concatenate(tflib.run(true_labels), axis=0)[:end-begin] preds[begin:end] = np.concatenate(tflib.run(result_expr), axis=0)[:end-begin] labels_true = np.argmax(trues, axis=1) labels_pred = np.argmax(preds, axis=1) purity = compute_purity(labels_pred, labels_true) ari = adjusted_rand_score(labels_true, labels_pred) nmi = normalized_mutual_info_score(labels_true, labels_pred) self._report_result(purity, suffix='purity') self._report_result(ari, suffix='ari') self._report_result(nmi, suffix='nmi') #----------------------------------------------------------------------------
mit
7,644,442,276,359,923,000
38.663462
93
0.618667
false
3.958733
false
false
false
boriel/zxbasic
src/symbols/number.py
1
4546
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: ts=4:et:sw=4: # ---------------------------------------------------------------------- # Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel) # # This program is Free Software and is released under the terms of # the GNU General License # ---------------------------------------------------------------------- import numbers from typing import Optional from src.api.constants import CLASS from .symbol_ import Symbol from .type_ import SymbolTYPE from .type_ import Type as TYPE from .const import SymbolCONST def _get_val(other): """ Given a Number, a Numeric Constant or a python number return its value """ assert isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST)) if isinstance(other, SymbolNUMBER): return other.value if isinstance(other, SymbolCONST): return other.expr.value return other class SymbolNUMBER(Symbol): """ Defines an NUMBER symbol. """ def __init__(self, value, lineno: int, type_: Optional[SymbolTYPE] = None): assert lineno is not None assert type_ is None or isinstance(type_, SymbolTYPE) if isinstance(value, SymbolNUMBER): value = value.value assert isinstance(value, numbers.Number) super().__init__() self.class_ = CLASS.const if int(value) == value: value = int(value) else: value = float(value) self.value = value if type_ is not None: self.type_ = type_ elif isinstance(value, float): if -32768.0 < value < 32767: self.type_ = TYPE.fixed else: self.type_ = TYPE.float_ elif isinstance(value, int): if 0 <= value < 256: self.type_ = TYPE.ubyte elif -128 <= value < 128: self.type_ = TYPE.byte_ elif 0 <= value < 65536: self.type_ = TYPE.uinteger elif -32768 <= value < 32768: self.type_ = TYPE.integer elif value < 0: self.type_ = TYPE.long_ else: self.type_ = TYPE.ulong self.lineno = lineno def __str__(self): return str(self.value) def __repr__(self): return "%s:%s" % (self.type_, str(self)) def __hash__(self): return id(self) @property def t(self): return str(self) def __eq__(self, other): if not isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST)): return False return self.value == _get_val(other) def __lt__(self, other): return self.value < _get_val(other) def __le__(self, other): return self.value <= _get_val(other) def __gt__(self, other): return self.value > _get_val(other) def __ge__(self, other): return self.value >= _get_val(other) def __add__(self, other): return SymbolNUMBER(self.value + _get_val(other), self.lineno) def __radd__(self, other): return SymbolNUMBER(_get_val(other) + self.value, self.lineno) def __sub__(self, other): return SymbolNUMBER(self.value - _get_val(other), self.lineno) def __rsub__(self, other): return SymbolNUMBER(_get_val(other) - self.value, self.lineno) def __mul__(self, other): return SymbolNUMBER(self.value * _get_val(other), self.lineno) def __rmul__(self, other): return SymbolNUMBER(_get_val(other) * self.value, self.lineno) def __truediv__(self, other): return SymbolNUMBER(self.value / _get_val(other), self.lineno) def __div__(self, other): return self.__truediv__(other) def __rtruediv__(self, other): return SymbolNUMBER(_get_val(other) / self.value, self.lineno) def __rdiv__(self, other): return self.__rtruediv__(other) def __or__(self, other): return SymbolNUMBER(self.value | _get_val(other), self.lineno) def __ror__(self, other): return SymbolNUMBER(_get_val(other | self.value), self.lineno) def __and__(self, other): return SymbolNUMBER(self.value & _get_val(other), self.lineno) def __rand__(self, other): return SymbolNUMBER(_get_val(other) & self.value, self.lineno) def __mod__(self, other): return SymbolNUMBER(self.value % _get_val(other), self.lineno) def __rmod__(self, other): return SymbolNUMBER(_get_val(other) % self.value, self.lineno)
gpl-3.0
-1,612,557,358,971,773,200
27.4125
79
0.558293
false
3.892123
false
false
false
ftrimble/route-grower
pyroute/lib_gpx.py
1
2521
#!/usr/bin/python #----------------------------------------------------------------------------- # Library for handling GPX files # # Usage: # #----------------------------------------------------------------------------- # Copyright 2007, Oliver White # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #----------------------------------------------------------------------------- import os import cairo from xml.sax import make_parser, handler class lib_gpx(handler.ContentHandler): """ """ def __init__(self): self.lines = [] def draw(self,cr,proj): cr.set_line_cap(cairo.LINE_CAP_ROUND) cr.set_source_rgb(0.7,0.7,0) cr.set_line_width(5) for l in self.lines: first = 1 for p in l: x,y = proj.ll2xy(p[0], p[1]) if(first): cr.move_to(x,y) first = 0 else: cr.line_to(x,y) cr.stroke() def saveAs(self,filename, title="untitled"): file = open(filename,"w") file.write("<?xml version=\"1.0\"?>\n") file.write('<gpx>\n') file.write('<trk>\n') file.write('<name>%s</name>\n' % title) for l in self.lines: file.write('<trkseg>\n') for p in l: file.write('<trkpt lat="%f" lon="%f"/>\n'%(p[0], p[1])) file.write('</trkseg>\n') file.write('</trk>\n') file.write('</gpx>\n') file.close() def load(self, filename): if(not os.path.exists(filename)): print "No such tracklog \"%s\"" % filename return self.inField = False parser = make_parser() parser.setContentHandler(self) parser.parse(filename) def startElement(self, name, attrs): if name == 'trk': pass if name == 'trkseg': self.latest = [] self.lines.append(self.latest) pass if name == "trkpt": lat = float(attrs.get('lat')) lon = float(attrs.get('lon')) self.latest.append([lat,lon])
apache-2.0
-9,187,451,632,071,958,000
29.743902
78
0.548592
false
3.658926
false
false
false
EmilStenstrom/nephele
nephele.py
1
1817
#!/usr/bin/env python -u """ Nephele - Finding movies to watch on the internet is easy, finding GOOD movies to watch is hard. Let Nephele, the greek nymph of the clouds, help you. Usage: nephele.py get_popular [--limit=<n>] [--filter=<spec>] [--debug] nephele.py get_grades <directory> [--limit=<n>] [--filter=<spec>] [--debug] nephele.py clear <name> [--debug] Options: -h --help Show this screen. --debug Print debug information. --limit=<n> Limit number of returned hits [default: 10] --filter=<spec> Filter resulting movies on this specification <spec> takes a comma separated list of movie field names, followed by an operator and a value to compare to. Valid operators are: * Equal: == (if the value is a list, equal means "contains" instead) * Not equal: == (if the value is a list, not equal means "does not contain" instead) * Larger than: >, Less than: < * Larger than or equal: >=, Less than or equal: <= Examples: * --filter="imdb_rating>4.5" * --filter="filmtipset_my_grade>=4" * --filter="imdb_rating>5,filmtipset_my_grade>=4" * --filter="genre==Romance" * --filter="genre!=Animation" """ import importlib from docopt import docopt if __name__ == '__main__': arguments = docopt(__doc__) command_str = [ key for key, value in arguments.items() if value and not key.startswith("--") and not key.startswith("<") ][0] command = importlib.import_module("commands." + command_str) command.main(arguments)
mit
-386,543,294,171,400,450
36.081633
108
0.544304
false
3.924406
false
false
false
teto/libnl_old
python/netlink/route/link.py
1
16902
# # Copyright (c) 2011 Thomas Graf <tgraf@suug.ch> # """Module providing access to network links This module provides an interface to view configured network links, modify them and to add and delete virtual network links. The following is a basic example: import netlink.core as netlink import netlink.route.link as link sock = netlink.Socket() sock.connect(netlink.NETLINK_ROUTE) cache = link.LinkCache() # create new empty link cache cache.refill(sock) # fill cache with all configured links eth0 = cache['eth0'] # lookup link "eth0" print(eth0) # print basic configuration The module contains the following public classes: - Link -- Represents a network link. Instances can be created directly via the constructor (empty link objects) or via the refill() method of a LinkCache. - LinkCache -- Derived from netlink.Cache, holds any number of network links (Link instances). Main purpose is to keep a local list of all network links configured in the kernel. The following public functions exist: - get_from_kernel(socket, name) """ from __future__ import absolute_import __version__ = '0.1' __all__ = [ 'LinkCache', 'Link', 'get_from_kernel', ] import socket from .. import core as netlink from .. import capi as core_capi from . import capi as capi from .links import inet as inet from .. import util as util # Link statistics definitions RX_PACKETS = 0 TX_PACKETS = 1 RX_BYTES = 2 TX_BYTES = 3 RX_ERRORS = 4 TX_ERRORS = 5 RX_DROPPED = 6 TX_DROPPED = 7 RX_COMPRESSED = 8 TX_COMPRESSED = 9 RX_FIFO_ERR = 10 TX_FIFO_ERR = 11 RX_LEN_ERR = 12 RX_OVER_ERR = 13 RX_CRC_ERR = 14 RX_FRAME_ERR = 15 RX_MISSED_ERR = 16 TX_ABORT_ERR = 17 TX_CARRIER_ERR = 18 TX_HBEAT_ERR = 19 TX_WIN_ERR = 20 COLLISIONS = 21 MULTICAST = 22 IP6_INPKTS = 23 IP6_INHDRERRORS = 24 IP6_INTOOBIGERRORS = 25 IP6_INNOROUTES = 26 IP6_INADDRERRORS = 27 IP6_INUNKNOWNPROTOS = 28 IP6_INTRUNCATEDPKTS = 29 IP6_INDISCARDS = 30 IP6_INDELIVERS = 31 IP6_OUTFORWDATAGRAMS = 32 IP6_OUTPKTS = 33 IP6_OUTDISCARDS = 34 IP6_OUTNOROUTES = 35 IP6_REASMTIMEOUT = 36 IP6_REASMREQDS = 37 IP6_REASMOKS = 38 IP6_REASMFAILS = 39 IP6_FRAGOKS = 40 IP6_FRAGFAILS = 41 IP6_FRAGCREATES = 42 IP6_INMCASTPKTS = 43 IP6_OUTMCASTPKTS = 44 IP6_INBCASTPKTS = 45 IP6_OUTBCASTPKTS = 46 IP6_INOCTETS = 47 IP6_OUTOCTETS = 48 IP6_INMCASTOCTETS = 49 IP6_OUTMCASTOCTETS = 50 IP6_INBCASTOCTETS = 51 IP6_OUTBCASTOCTETS = 52 ICMP6_INMSGS = 53 ICMP6_INERRORS = 54 ICMP6_OUTMSGS = 55 ICMP6_OUTERRORS = 56 class LinkCache(netlink.Cache): """Cache of network links""" def __init__(self, family=socket.AF_UNSPEC, cache=None): if not cache: cache = self._alloc_cache_name('route/link') self._info_module = None self._protocol = netlink.NETLINK_ROUTE self._nl_cache = cache self._set_arg1(family) def __getitem__(self, key): if type(key) is int: link = capi.rtnl_link_get(self._nl_cache, key) else: link = capi.rtnl_link_get_by_name(self._nl_cache, key) if link is None: raise KeyError() else: return Link.from_capi(link) @staticmethod def _new_object(obj): return Link(obj) def _new_cache(self, cache): return LinkCache(family=self.arg1, cache=cache) class Link(netlink.Object): """Network link""" def __init__(self, obj=None): netlink.Object.__init__(self, 'route/link', 'link', obj) self._rtnl_link = self._obj2type(self._nl_object) if self.type: self._module_lookup('netlink.route.links.' + self.type) self.inet = inet.InetLink(self) self.af = {'inet' : self.inet } def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if exc_type is None: self.change() else: return false @classmethod def from_capi(cls, obj): return cls(capi.link2obj(obj)) @staticmethod def _obj2type(obj): return capi.obj2link(obj) def __cmp__(self, other): return self.ifindex - other.ifindex @staticmethod def _new_instance(obj): if not obj: raise ValueError() return Link(obj) @property @netlink.nlattr(type=int, immutable=True, fmt=util.num) def ifindex(self): """interface index""" return capi.rtnl_link_get_ifindex(self._rtnl_link) @ifindex.setter def ifindex(self, value): capi.rtnl_link_set_ifindex(self._rtnl_link, int(value)) # ifindex is immutable but we assume that if _orig does not # have an ifindex specified, it was meant to be given here if capi.rtnl_link_get_ifindex(self._orig) == 0: capi.rtnl_link_set_ifindex(self._orig, int(value)) @property @netlink.nlattr(type=str, fmt=util.bold) def name(self): """Name of link""" return capi.rtnl_link_get_name(self._rtnl_link) @name.setter def name(self, value): capi.rtnl_link_set_name(self._rtnl_link, value) # name is the secondary identifier, if _orig does not have # the name specified yet, assume it was meant to be specified # here. ifindex will always take priority, therefore if ifindex # is specified as well, this will be ignored automatically. if capi.rtnl_link_get_name(self._orig) is None: capi.rtnl_link_set_name(self._orig, value) @property @netlink.nlattr(type=str, fmt=util.string) def flags(self): """Flags Setting this property will *Not* reset flags to value you supply in Examples: link.flags = '+xxx' # add xxx flag link.flags = 'xxx' # exactly the same link.flags = '-xxx' # remove xxx flag link.flags = [ '+xxx', '-yyy' ] # list operation """ flags = capi.rtnl_link_get_flags(self._rtnl_link) return capi.rtnl_link_flags2str(flags, 256)[0].split(',') def _set_flag(self, flag): if flag.startswith('-'): i = capi.rtnl_link_str2flags(flag[1:]) capi.rtnl_link_unset_flags(self._rtnl_link, i) elif flag.startswith('+'): i = capi.rtnl_link_str2flags(flag[1:]) capi.rtnl_link_set_flags(self._rtnl_link, i) else: i = capi.rtnl_link_str2flags(flag) capi.rtnl_link_set_flags(self._rtnl_link, i) @flags.setter def flags(self, value): if not (type(value) is str): for flag in value: self._set_flag(flag) else: self._set_flag(value) @property @netlink.nlattr(type=int, fmt=util.num) def mtu(self): """Maximum Transmission Unit""" return capi.rtnl_link_get_mtu(self._rtnl_link) @mtu.setter def mtu(self, value): capi.rtnl_link_set_mtu(self._rtnl_link, int(value)) @property @netlink.nlattr(type=int, immutable=True, fmt=util.num) def family(self): """Address family""" return capi.rtnl_link_get_family(self._rtnl_link) @family.setter def family(self, value): capi.rtnl_link_set_family(self._rtnl_link, value) @property @netlink.nlattr(type=str, fmt=util.addr) def address(self): """Hardware address (MAC address)""" a = capi.rtnl_link_get_addr(self._rtnl_link) return netlink.AbstractAddress(a) @address.setter def address(self, value): capi.rtnl_link_set_addr(self._rtnl_link, value._addr) @property @netlink.nlattr(type=str, fmt=util.addr) def broadcast(self): """Hardware broadcast address""" a = capi.rtnl_link_get_broadcast(self._rtnl_link) return netlink.AbstractAddress(a) @broadcast.setter def broadcast(self, value): capi.rtnl_link_set_broadcast(self._rtnl_link, value._addr) @property @netlink.nlattr(type=str, immutable=True, fmt=util.string) def qdisc(self): """Name of qdisc (cannot be changed)""" return capi.rtnl_link_get_qdisc(self._rtnl_link) @qdisc.setter def qdisc(self, value): capi.rtnl_link_set_qdisc(self._rtnl_link, value) @property @netlink.nlattr(type=int, fmt=util.num) def txqlen(self): """Length of transmit queue""" return capi.rtnl_link_get_txqlen(self._rtnl_link) @txqlen.setter def txqlen(self, value): capi.rtnl_link_set_txqlen(self._rtnl_link, int(value)) @property @netlink.nlattr(type=str, immutable=True, fmt=util.string) def arptype(self): """Type of link (cannot be changed)""" type_ = capi.rtnl_link_get_arptype(self._rtnl_link) return core_capi.nl_llproto2str(type_, 64)[0] @arptype.setter def arptype(self, value): i = core_capi.nl_str2llproto(value) capi.rtnl_link_set_arptype(self._rtnl_link, i) @property @netlink.nlattr(type=str, immutable=True, fmt=util.string, title='state') def operstate(self): """Operational status""" operstate = capi.rtnl_link_get_operstate(self._rtnl_link) return capi.rtnl_link_operstate2str(operstate, 32)[0] @operstate.setter def operstate(self, value): i = capi.rtnl_link_str2operstate(value) capi.rtnl_link_set_operstate(self._rtnl_link, i) @property @netlink.nlattr(type=str, immutable=True, fmt=util.string) def mode(self): """Link mode""" mode = capi.rtnl_link_get_linkmode(self._rtnl_link) return capi.rtnl_link_mode2str(mode, 32)[0] @mode.setter def mode(self, value): i = capi.rtnl_link_str2mode(value) capi.rtnl_link_set_linkmode(self._rtnl_link, i) @property @netlink.nlattr(type=str, fmt=util.string) def alias(self): """Interface alias (SNMP)""" return capi.rtnl_link_get_ifalias(self._rtnl_link) @alias.setter def alias(self, value): capi.rtnl_link_set_ifalias(self._rtnl_link, value) @property @netlink.nlattr(type=str, fmt=util.string) def type(self): """Link type""" return capi.rtnl_link_get_type(self._rtnl_link) @type.setter def type(self, value): if capi.rtnl_link_set_type(self._rtnl_link, value) < 0: raise NameError('unknown info type') self._module_lookup('netlink.route.links.' + value) def get_stat(self, stat): """Retrieve statistical information""" if type(stat) is str: stat = capi.rtnl_link_str2stat(stat) if stat < 0: raise NameError('unknown name of statistic') return capi.rtnl_link_get_stat(self._rtnl_link, stat) def add(self, sock=None, flags=None): if not sock: sock = netlink.lookup_socket(netlink.NETLINK_ROUTE) if not flags: flags = netlink.NLM_F_CREATE ret = capi.rtnl_link_add(sock._sock, self._rtnl_link, flags) if ret < 0: raise netlink.KernelError(ret) def change(self, sock=None, flags=0): """Commit changes made to the link object""" if sock is None: sock = netlink.lookup_socket(netlink.NETLINK_ROUTE) if not self._orig: raise netlink.NetlinkError('Original link not available') ret = capi.rtnl_link_change(sock._sock, self._orig, self._rtnl_link, flags) if ret < 0: raise netlink.KernelError(ret) def delete(self, sock=None): """Attempt to delete this link in the kernel""" if sock is None: sock = netlink.lookup_socket(netlink.NETLINK_ROUTE) ret = capi.rtnl_link_delete(sock._sock, self._rtnl_link) if ret < 0: raise netlink.KernelError(ret) ################################################################### # private properties # # Used for formatting output. USE AT OWN RISK @property def _state(self): if 'up' in self.flags: buf = util.good('up') if 'lowerup' not in self.flags: buf += ' ' + util.bad('no-carrier') else: buf = util.bad('down') return buf @property def _brief(self): return self._module_brief() + self._foreach_af('brief') @property def _flags(self): ignore = [ 'up', 'running', 'lowerup', ] return ','.join([flag for flag in self.flags if flag not in ignore]) def _foreach_af(self, name, args=None): buf = '' for af in self.af: try: func = getattr(self.af[af], name) s = str(func(args)) if len(s) > 0: buf += ' ' + s except AttributeError: pass return buf def format(self, details=False, stats=False, indent=''): """Return link as formatted text""" fmt = util.MyFormatter(self, indent) buf = fmt.format('{a|ifindex} {a|name} {a|arptype} {a|address} '\ '{a|_state} <{a|_flags}> {a|_brief}') if details: buf += fmt.nl('\t{t|mtu} {t|txqlen} {t|weight} '\ '{t|qdisc} {t|operstate}') buf += fmt.nl('\t{t|broadcast} {t|alias}') buf += self._foreach_af('details', fmt) if stats: l = [['Packets', RX_PACKETS, TX_PACKETS], ['Bytes', RX_BYTES, TX_BYTES], ['Errors', RX_ERRORS, TX_ERRORS], ['Dropped', RX_DROPPED, TX_DROPPED], ['Compressed', RX_COMPRESSED, TX_COMPRESSED], ['FIFO Errors', RX_FIFO_ERR, TX_FIFO_ERR], ['Length Errors', RX_LEN_ERR, None], ['Over Errors', RX_OVER_ERR, None], ['CRC Errors', RX_CRC_ERR, None], ['Frame Errors', RX_FRAME_ERR, None], ['Missed Errors', RX_MISSED_ERR, None], ['Abort Errors', None, TX_ABORT_ERR], ['Carrier Errors', None, TX_CARRIER_ERR], ['Heartbeat Errors', None, TX_HBEAT_ERR], ['Window Errors', None, TX_WIN_ERR], ['Collisions', None, COLLISIONS], ['Multicast', None, MULTICAST], ['', None, None], ['Ipv6:', None, None], ['Packets', IP6_INPKTS, IP6_OUTPKTS], ['Bytes', IP6_INOCTETS, IP6_OUTOCTETS], ['Discards', IP6_INDISCARDS, IP6_OUTDISCARDS], ['Multicast Packets', IP6_INMCASTPKTS, IP6_OUTMCASTPKTS], ['Multicast Bytes', IP6_INMCASTOCTETS, IP6_OUTMCASTOCTETS], ['Broadcast Packets', IP6_INBCASTPKTS, IP6_OUTBCASTPKTS], ['Broadcast Bytes', IP6_INBCASTOCTETS, IP6_OUTBCASTOCTETS], ['Delivers', IP6_INDELIVERS, None], ['Forwarded', None, IP6_OUTFORWDATAGRAMS], ['No Routes', IP6_INNOROUTES, IP6_OUTNOROUTES], ['Header Errors', IP6_INHDRERRORS, None], ['Too Big Errors', IP6_INTOOBIGERRORS, None], ['Address Errors', IP6_INADDRERRORS, None], ['Unknown Protocol', IP6_INUNKNOWNPROTOS, None], ['Truncated Packets', IP6_INTRUNCATEDPKTS, None], ['Reasm Timeouts', IP6_REASMTIMEOUT, None], ['Reasm Requests', IP6_REASMREQDS, None], ['Reasm Failures', IP6_REASMFAILS, None], ['Reasm OK', IP6_REASMOKS, None], ['Frag Created', None, IP6_FRAGCREATES], ['Frag Failures', None, IP6_FRAGFAILS], ['Frag OK', None, IP6_FRAGOKS], ['', None, None], ['ICMPv6:', None, None], ['Messages', ICMP6_INMSGS, ICMP6_OUTMSGS], ['Errors', ICMP6_INERRORS, ICMP6_OUTERRORS]] buf += '\n\t%s%s%s%s\n' % (33 * ' ', util.title('RX'), 15 * ' ', util.title('TX')) for row in l: row[0] = util.kw(row[0]) row[1] = self.get_stat(row[1]) if row[1] else '' row[2] = self.get_stat(row[2]) if row[2] else '' buf += '\t{0[0]:27} {0[1]:>16} {0[2]:>16}\n'.format(row) buf += self._foreach_af('stats') return buf def get(name, sock=None): """Lookup Link object directly from kernel""" if not name: raise ValueError() if not sock: sock = netlink.lookup_socket(netlink.NETLINK_ROUTE) # returns a struct rtnl_link, defined in netlink-private/types.h link = capi.get_from_kernel(sock._sock, 0, name) if not link: return None return Link.from_capi(link) _link_cache = LinkCache() def resolve(name): _link_cache.refill() return _link_cache[name]
lgpl-2.1
-5,284,595,556,784,319,000
30.184502
83
0.580464
false
3.325202
false
false
false
liutairan/eMolFrag
Old versions/eMolFrag_2016_12_21_02/eMolFrag.py
1
37326
#Process: #1. Get a list of original sdf files #2. Use chopRDKit02.py generates fragments and list of files with total atom number, carbon atom number, nitrogen and oxygen atom number #3. Form lists of by atom numbers #4. Run rmRedLinker03.py or rmRedRigid01.py on different lists generated by step 3. Remove redundancy of linkers and rigids. #5. Remove temp file and dir. #main-script: # - eMolFrag.py #sub-scripts used: # - loader.py # - chopRDKit02.py, # - combineLinkers01.py # - rmRedRigid01.py, # - rmRedLinker03.py, # - mol-ali-04.py. #Usage: Read README file for detailed information. # 1. Configure path: python ConfigurePath.py # Path only need to be set before the first run if no changes to the paths. # 2. /Path_to_Python/python /Path_to_scripts/eMolFrag.py /Path_to_input_directory/ /Path_to_output_directory/ Number-Of-Cores #Args: # - /Path to Python/ ... Use python to run the script # - /Path to scripts/echop.py ... The directory of scripts and the name of the entrance to the software # - /Path to input directory/ ... The path to the input directory, in which is the input molecules in *.mol2 format # - /Path to output directory/ ... The path to the output directory, in which is the output files # - Number-Of-Cores ... Number of processings to be used in the run #Update Log: #This script is written by Tairan Liu. # Created 01/17/2016 - Chop # Modification 01/17/2016 - Remove bug # Modification 01/18/2016 - Reconnect linkers # Modification 01/21/2016 - Remove redundancy # Modification 02/29/2016 - Remove bug # Modification 03/16/2016 - Remove bug # Modification 03/17/2016 - Remove bug # Modification 03/24/2016 - Remove bug # Modification 03/25/2016 - Change each step to functions # Modification 04/03/2016 - Remove bug # Modification 04/06/2016 - Reduce temp output files # Modification 04/06/2016 - Remove bug # Modification 04/06/2016 - Start parallel with chop # Modification 04/17/2016 - Improve efficiency # Modification 04/18/2016 - Remove bug # Modification 05/24/2016 - Start parallel with remove redundancy # Modification 06/14/2016 - Add parallel option as arg # Modification 06/14/2016 - Remove bug # Modification 06/29/2016 - Remove bug # Modification 07/08/2016 - Change similarity criteria of rigids from 0.95 to 0.97 # Modification 07/11/2016 - Improve efficiency # Modification 07/18/2016 - Pack up, format. # Modification 07/19/2016 - Solve python 2.x/3.x compatibility problem. # Modification 07/20/2016 - Solve python 2.x/3.x compatibility problem. # Modification 07/21/2016 - Solve python 2.x/3.x compatibility problem. # Modification 07/22/2016 - Solve python 2.x/3.x compatibility problem. # Modification 07/22/2016 - Modify README file # Last revision 09/13/2016 - Solve output path conflict problem. import subprocess import os import path import os.path import shutil import sys import time from multiprocessing import Pool from functools import partial def ParseArgs(): #input and output path define and create args=sys.argv #inputFolderPath=args[1] #outputDir=args[2] mainEntryPath=os.path.abspath(args[0]) inputFolderPath = [] outputDir = [] processNum = 1 outputSelection = 0 outputFormat = 0 if len(args) > 1: argList = args[1:] else: print('Error Code: 1010. Incorrect arguments.') return if len(argList) == 10: # -i -o -p -m -c paraFlag = 1 #print('Show') if (argList[0] == '-i') and (argList[2] == '-o') and (argList[4] == '-p') and (argList[6] == '-m') and (argList[8] == '-c'): # input path tempPath1 = os.path.abspath(argList[1]) #print(tempPath1) if os.path.isdir(tempPath1): inputFolderPath = tempPath1 if inputFolderPath[-1]=='/': pass else: inputFolderPath=inputFolderPath+'/' else: paraFlag = 0 #print(paraFlag) # output path tempPath2 = os.path.abspath(argList[3]) #print(tempPath2) #if os.path.isdir(tempPath2): outputDir = tempPath2 if outputDir[-1]=='/': pass else: outputDir=outputDir+'/' #else: # paraFlag = 0 #print(outputDir) # parallel tempCoreNum = int(argList[5]) if (tempCoreNum >= 1) and (tempCoreNum <= 16): processNum = tempCoreNum else: paraFlag = 0 #print(paraFlag) # output select tempOutputSelection = int(argList[7]) if (tempOutputSelection >= 0) and (tempOutputSelection <= 2): outputSelection = tempOutputSelection else: paraFlag = 0 # output format tempOutputFormat = int(argList[9]) if (tempOutputFormat >= 0) and (tempOutputFormat <= 1): outputFormat = tempOutputFormat else: paraFlag = 0 else: paraFlag = 0 if paraFlag == 1: pass else: print('Error Code: 1012. Incorrect arguments.') return elif len(argList) == 8: # -i -o, two of three (-p -m -c) paraFlag = 1 if (argList[0] == '-i') and (argList[2] == '-o'): # input path tempPath1 = os.path.abspath(argList[1]) if os.path.isdir(tempPath1): inputFolderPath = tempPath1 if inputFolderPath[-1]=='/': pass else: inputFolderPath=inputFolderPath+'/' else: paraFlag = 0 # output path tempPath2 = os.path.abspath(argList[3]) #if os.path.isdir(tempPath2): outputDir = tempPath2 if outputDir[-1]=='/': pass else: outputDir=outputDir+'/' #else: # paraFlag = 0 else: paraFlag = 0 if (argList[4] == '-p') and (argList[6] == '-m'): # parallel tempCoreNum = int(argList[5]) if (tempCoreNum >= 1) and (tempCoreNum <= 16): processNum = tempCoreNum else: paraFlag = 0 # output select tempOutputSelection = int(argList[7]) if (tempOutputSelection >= 0) and (tempOutputSelection <= 2): outputSelection = tempOutputSelection else: paraFlag = 0 elif (argList[4] == '-p') and (argList[6] == '-c'): # parallel tempCoreNum = int(argList[5]) if (tempCoreNum >= 1) and (tempCoreNum <= 16): processNum = tempCoreNum else: paraFlag = 0 # output format tempOutputFormat = int(argList[9]) if (tempOutputFormat >= 0) and (tempOutputFormat <= 1): outputFormat = tempOutputFormat else: paraFlag = 0 elif (argList[4] == '-m') and (argList[6] == '-c'): # output select tempOutputSelection = int(argList[7]) if (tempOutputSelection >= 0) and (tempOutputSelection <= 2): outputSelection = tempOutputSelection else: paraFlag = 0 # output format tempOutputFormat = int(argList[9]) if (tempOutputFormat >= 0) and (tempOutputFormat <= 1): outputFormat = tempOutputFormat else: paraFlag = 0 else: paraFlag = 0 if paraFlag == 1: pass else: print('Error Code: 1013. Incorrect arguments.') return elif len(argList) == 6: # -i -o, one of three (-p -m -c) paraFlag = 1 if (argList[0] == '-i') and (argList[2] == '-o'): # input path tempPath1 = os.path.abspath(argList[1]) if os.path.isdir(tempPath1): inputFolderPath = tempPath1 if inputFolderPath[-1]=='/': pass else: inputFolderPath=inputFolderPath+'/' else: paraFlag = 0 # output path tempPath2 = os.path.abspath(argList[3]) #if os.path.isdir(tempPath2): outputDir = tempPath2 if outputDir[-1]=='/': pass else: outputDir=outputDir+'/' #else: # paraFlag = 0 else: paraFlag = 0 if (argList[4] == '-p'): # parallel tempCoreNum = int(argList[5]) if (tempCoreNum >= 1) and (tempCoreNum <= 16): processNum = tempCoreNum else: paraFlag = 0 elif (argList[4] == '-c'): # output format tempOutputFormat = int(argList[9]) if (tempOutputFormat >= 0) and (tempOutputFormat <= 1): outputFormat = tempOutputFormat else: paraFlag = 0 elif (argList[4] == '-m'): # output select tempOutputSelection = int(argList[7]) if (tempOutputSelection >= 0) and (tempOutputSelection <= 2): outputSelection = tempOutputSelection else: paraFlag = 0 else: paraFlag = 0 if paraFlag == 1: pass else: print('Error Code: 1014. Incorrect arguments.') return elif len(argList) == 4: # -i -o paraFlag = 1 if (argList[0] == '-i') and (argList[2] == '-o'): # input path tempPath1 = os.path.abspath(argList[1]) if os.path.isdir(tempPath1): inputFolderPath = tempPath1 if inputFolderPath[-1]=='/': pass else: inputFolderPath=inputFolderPath+'/' else: paraFlag = 0 # output path tempPath2 = os.path.abspath(argList[3]) #if os.path.isdir(tempPath2): outputDir = tempPath2 if outputDir[-1]=='/': pass else: outputDir=outputDir+'/' #else: # paraFlag = 0 else: paraFlag = 0 if paraFlag == 1: pass else: print('Error Code: 1015. Incorrect arguments.') return else: print('Error Code: 1011. Incorrect arguments.') return return [mainEntryPath, inputFolderPath, outputDir, processNum, outputSelection, outputFormat] def PrepareEnv(outputDir, mainEntryPath, processNum): try: # check output folder conflict or not # detect output folder if os.path.exists(outputDir): print('Designate output path already exists, do you want to use another path? [y/n]') flagSetPath = 1 ver = sys.version[0] p1 = '' p2 = '' while flagSetPath: if ver == '2': p1 = raw_input() if p1 == 'y': print('Please type a new output path') p2 = raw_input() outputDir=os.path.abspath(p2) print(outputDir) if outputDir[-1]=='/': pass else: outputDir=outputDir+'/' if os.path.exists(outputDir): print('Designate output path already exists, do you want to use another path? [y/n]') else: flagSetPath = 0 print('Output path successfully set. Continue...') elif p1 == 'n': print('Old files in this path will be deleted, continue? [y/n]') p3 = raw_input() if p3 == 'y': shutil.rmtree(outputDir) flagSetPath = 0 elif p3 == 'n': print('Designate output path already exists, do you want to use another path? [y/n]') else: print('Unrecognizable character, please type again: [y/n]') else: print('Unrecognizable character, please type again: [y/n]') elif ver == '3': p1 = input() if p1 == 'y': print('Please type a new output path') p2 = input() outputDir=os.path.abspath(p2) print(outputDir) if outputDir[-1]=='/': pass else: outputDir=outputDir+'/' if os.path.exists(outputDir): print('Designate output path already exists, do you want to use another path? [y/n]') else: flagSetPath = 0 print('Output path successfully set. Continue...') elif p1 == 'n': print('Old files in this path will be deleted, continue? [y/n]') p3 = input() if p3 == 'y': shutil.rmtree(outputDir) flagSetPath = 0 elif p3 == 'n': print('Designate output path already exists, do you want to use another path? [y/n]') else: print('Unrecognizable character, please type again: [y/n]') else: print('Unrecognizable character, please type again: [y/n]') else: print('Error Code: 1021. Get python version failed.') return except: print('Error Code: 1020.') return try: # check scripts existance and completeness if os.path.exists(mainEntryPath): mainPath=os.path.dirname(mainEntryPath) if os.path.exists(mainPath+'/loader.py'): os.chdir(mainPath) pass else: print('Error Code: 1032. Cannot find part of script files.\nExit.') sys.exit() else: print('Error Code: 1031. Error input format.\nExit.') sys.exit() except: print('Error Code: 1030.') return try: pool=Pool(processes=processNum) except: print('Error Code: 1040.') return try: outputFolderPath_log=outputDir+'output-log/' outputFolderPath_chop=outputDir+'output-chop/' outputFolderPath_active=outputDir+'output-rigid/' outputFolderPath_linker=outputDir+'output-linker/' outputFolderPath_sdf=outputDir+'output-sdf/' outputFolderPath_chop_comb=outputDir+'output-chop-comb/' if not os.path.exists(outputDir): os.mkdir(outputDir) #else: # print('Designate output path already exists, do you want to use another path?') if not os.path.exists(outputFolderPath_log): os.mkdir(outputFolderPath_log) if not os.path.exists(outputFolderPath_chop): os.mkdir(outputFolderPath_chop) if not os.path.exists(outputFolderPath_active): os.mkdir(outputFolderPath_active) if not os.path.exists(outputFolderPath_linker): os.mkdir(outputFolderPath_linker) if not os.path.exists(outputFolderPath_sdf): os.mkdir(outputFolderPath_sdf) if not os.path.exists(outputFolderPath_chop_comb): os.mkdir(outputFolderPath_chop_comb) except: print('Error Code: 1050.') return try: try: from loader import Loader except: print('Error Code: 1061. Failed to load loader.') return try: initState=Loader(mainEntryPath) except: print('Error Code: 1062. Failed to load scripts and configures.') return if initState == 0: pass else: print('Error Code: 1063. Cannot load prerequisit.\nExit.') sys.exit() except: print('Error Code: 1060.') return outputPathList = [outputDir, outputFolderPath_log, outputFolderPath_chop, outputFolderPath_active, outputFolderPath_linker, outputFolderPath_sdf, outputFolderPath_chop_comb] return [outputPathList, pool] def ProcessData(inputFolderPath, outputPathList, outputSelection, outputFormat, pool): try: [outputDir, outputFolderPath_log, outputFolderPath_chop, outputFolderPath_active, outputFolderPath_linker, outputFolderPath_sdf, outputFolderPath_chop_comb] = outputPathList except: print('Error Code: 1130. Failed to parse output path list.') return try: from combineLinkers01 import combineLinkers from rmRedLinker03 import RmLinkerRed from rmRedRigid01 import RmRigidRed from chopRDKit02 import ChopWithRDKit except: print('Error Code: 1070. Failed to load required lib files.') return # Create work try: path = outputFolderPath_log+'Process.log' msg = ' Create Work ' + inputFolderPath+' '+outputDir PrintLog(path, msg) except: print('Error Code: 1071. Failed to write log file.') try: GetInputList(inputFolderPath, outputFolderPath_log) except: print('Error Code: 1072.') return try: Chop(outputPathList, pool) except: print('Error Code: 1073.') return if (outputSelection == 0) or (outputSelection == 2): try: RmRigidRedundancy(outputPathList, pool) except: print('Error Code: 1074.') return try: RmLinkerRedundancy(outputPathList, pool) except: print('Error Code: 1075.') return else: pass # End Work try: path = outputFolderPath_log+'Process.log' msg = ' End Work ' PrintLog(path, msg) except: print('Error Code: 1076. Failed to write log file.') return def AdjustOutput(outputPathList, outputSelection, outputFormat): try: [outputDir, outputFolderPath_log, outputFolderPath_chop, outputFolderPath_active, outputFolderPath_linker, outputFolderPath_sdf, outputFolderPath_chop_comb] = outputPathList except: print('Error Code: 1130. Failed to parse output path list.') return #Step 5: Clear temp file and directory. if outputSelection == 0: # default output selection, full process and output, left 4 folders: log, rigid, linker, chop-comb shutil.rmtree(outputFolderPath_chop) shutil.rmtree(outputFolderPath_sdf) elif outputSelection == 1: # only chop and reconnect, not remove redundancy, left 2 folders: log, chop-comb shutil.rmtree(outputFolderPath_chop) shutil.rmtree(outputFolderPath_sdf) shutil.rmtree(outputFolderPath_active) shutil.rmtree(outputFolderPath_linker) elif outputSelection == 2: # chop and remove redundancy, but remove temp files, left 3 folders: log rigid, linker shutil.rmtree(outputFolderPath_chop) shutil.rmtree(outputFolderPath_sdf) shutil.rmtree(outputFolderPath_chop_comb) else: print('Error Code: 1131. Invalid output selection.') return if outputFormat == 1: # traditional format, each file only contain one molecule pass elif outputFormat == 0: # default output format, only one rigid file and only one linker file if outputSelection == 0: # 4 output files, (rigid, linker)*(before remove, after remove) try: AdjustSub0(outputPathList) except: print('Error Code: 1134.') return elif outputSelection == 1: # 2 output files, (rigid, linker)*(before remove) try: AdjustSub1(outputPathList) except: print('Error Code: 1135.') return elif outputSelection == 2: # 2 output files, (rigid, linker)*(after remove) try: AdjustSub2(outputPathList) except: print('Error Code: 1136.') return else: print('Error Code: 1133.') return else: print('Error Code: 1132. Invalid output format.') return def AdjustSub0(outputPathList): try: [outputDir, outputFolderPath_log, outputFolderPath_chop, outputFolderPath_active, outputFolderPath_linker, outputFolderPath_sdf, outputFolderPath_chop_comb] = outputPathList except: print('Error Code: 1140. Failed to parse output path list.') return try: [combFilePath, combFileName] = GetFileList(outputFolderPath_chop_comb) except: print('Error Code: 1141.') return try: tempRigidContent = [] tempLinkerContent = [] b4rmRigidPath = outputDir + 'RigidFull.sdf' b4rmLinkerPath = outputDir + 'LinkerFull.sdf' for i in range(len(combFilePath)): if combFileName[i][0] == 'r': with open(combFilePath[i], 'r') as inf: tempRigidContent = inf.readlines() with open(b4rmRigidPath, 'at') as outf: outf.writelines(tempRigidContent) outf.write('\n') tempRigidContent = [] elif combFileName[i][0] == 'l': with open(combFilePath[i], 'r') as inf: tempLinkerContent = inf.readlines() with open(b4rmLinkerPath, 'at') as outf: outf.writelines(tempLinkerContent) outf.write('\n') tempLinkerContent = [] else: pass except: print('Error Code: 1142.') try: [rigidFilePath, rigidFileName] = GetFileList(outputFolderPath_active) except: print('Error Code: 1143.') try: tempRigidContent = [] rmdRigidPath = outputDir + 'RigidUnique.sdf' for i in range(len(rigidFilePath)): if rigidFileName[i][0] == 'r': with open(rigidFilePath[i], 'r') as inf: tempRigidContent = inf.readlines() with open(rmdRigidPath, 'at') as outf: outf.writelines(tempRigidContent) outf.write('\n') tempRigidContent = [] except: print('Error Code: 1144.') try: [linkerFilePath, linkerFileName] = GetFileList(outputFolderPath_linker) except: print('Error Code: 1145.') try: tempLinkerContent = [] rmdLinkerPath = outputDir + 'LinkerUnique.sdf' for i in range(len(linkerFilePath)): if linkerFileName[i][0] == 'l': with open(linkerFilePath[i], 'r') as inf: tempLinkerContent = inf.readlines() with open(rmdLinkerPath, 'at') as outf: outf.writelines(tempLinkerContent) outf.write('\n') tempLinkerContent = [] except: print('Error Code: 1146.') try: shutil.rmtree(outputFolderPath_chop_comb) shutil.rmtree(outputFolderPath_active) shutil.rmtree(outputFolderPath_linker) except: print('Error Code: 1147. Failed to remove temp files.') def AdjustSub1(outputPathList): try: [outputDir, outputFolderPath_log, outputFolderPath_chop, outputFolderPath_active, outputFolderPath_linker, outputFolderPath_sdf, outputFolderPath_chop_comb] = outputPathList except: print('Error Code: 1150. Failed to parse output path list.') return try: [combFilePath, combFileName] = GetFileList(outputFolderPath_chop_comb) except: print('Error Code: 1151.') return try: tempRigidContent = [] tempLinkerContent = [] b4rmRigidPath = outputDir + 'RigidFull.sdf' b4rmLinkerPath = outputDir + 'LinkerFull.sdf' for i in range(len(combFilePath)): if combFileName[i][0] == 'r': with open(combFilePath[i], 'r') as inf: tempRigidContent = inf.readlines() with open(b4rmRigidPath, 'at') as outf: outf.writelines(tempRigidContent) outf.write('\n') tempRigidContent = [] elif combFileName[i][0] == 'l': with open(combFilePath[i], 'r') as inf: tempLinkerContent = inf.readlines() with open(b4rmLinkerPath, 'at') as outf: outf.writelines(tempLinkerContent) outf.write('\n') tempLinkerContent = [] else: pass except: print('Error Code: 1152.') try: shutil.rmtree(outputFolderPath_chop_comb) except: print('Error Code: 1157. Failed to remove temp files.') def AdjustSub2(outputPathList): try: [outputDir, outputFolderPath_log, outputFolderPath_chop, outputFolderPath_active, outputFolderPath_linker, outputFolderPath_sdf, outputFolderPath_chop_comb] = outputPathList except: print('Error Code: 1160. Failed to parse output path list.') return try: [rigidFilePath, rigidFileName] = GetFileList(outputFolderPath_active) except: print('Error Code: 1163.') try: tempRigidContent = [] rmdRigidPath = outputDir + 'RigidUnique.sdf' for i in range(len(rigidFilePath)): if rigidFileName[i][0] == 'r': with open(rigidFilePath[i], 'r') as inf: tempRigidContent = inf.readlines() with open(rmdRigidPath, 'at') as outf: outf.writelines(tempRigidContent) outf.write('\n') tempRigidContent = [] except: print('Error Code: 1164.') try: [linkerFilePath, linkerFileName] = GetFileList(outputFolderPath_linker) except: print('Error Code: 1165.') try: tempLinkerContent = [] rmdLinkerPath = outputDir + 'LinkerUnique.sdf' for i in range(len(linkerFilePath)): if linkerFileName[i][0] == 'l': with open(linkerFilePath[i], 'r') as inf: tempLinkerContent = inf.readlines() with open(rmdLinkerPath, 'at') as outf: outf.writelines(tempLinkerContent) outf.write('\n') tempLinkerContent = [] except: print('Error Code: 1166.') try: shutil.rmtree(outputFolderPath_active) shutil.rmtree(outputFolderPath_linker) except: print('Error Code: 1167. Failed to remove temp files.') def GetFileList(path): try: fileNameList = [] filePathList = [] try: for root, dirs, files in os.walk(path): for file in files: fileNameList.append(file) filePathList.append(path+file) return [filePathList, fileNameList] except: print('Error Code: 1171.') return except: print('Error Code: 1170.') return def GetInputList(inputFolderPath, outputFolderPath_log): #Step 1: Get a list of original *.mol2 files try: fileNameList=[] infilePathList=[] outfilePathList=[] try: for root, dirs, files in os.walk(inputFolderPath): for file in files: fileNameList.append(file) infilePathList.append(inputFolderPath+file+'\n') except: print('Error Code: 1081.') return try: with open(outputFolderPath_log+'InputList','at') as outList: outList.writelines(infilePathList) except: print('Error Code: 1082.') return except: print('Error Code: 1080. Failed to get input file list.') return def Chop(outputPathList, pool): try: [outputDir, outputFolderPath_log, outputFolderPath_chop, outputFolderPath_active, outputFolderPath_linker, outputFolderPath_sdf, outputFolderPath_chop_comb] = outputPathList except: print('Error Code: 1130. Failed to parse output path list.') return try: from chopRDKit02 import ChopWithRDKit except: print('Error Code: 1090-01.') return #Step 2: chop and generate list # Log try: path = outputFolderPath_log+'Process.log' msg = ' Start Chop ' PrintLog(path, msg) except: print('Error Code: 1090. Failed to write log file.') return try: inputList=[] with open(outputFolderPath_log+'InputList','r') as inList: for lines in inList: inputList.append(lines.replace('\n','')) except: print('Error Code: 1091.') return try: partial_Chop=partial(ChopWithRDKit, outputDir) pool.map(partial_Chop,inputList) except: print('Error Code: 1092.') return try: # Log path = outputFolderPath_log+'Process.log' msg = ' End Chop ' PrintLog(path, msg) except: print('Error Code: 1093.') return def RmRigidRedundancy(outputPathList, pool): try: [outputDir, outputFolderPath_log, outputFolderPath_chop, outputFolderPath_active, outputFolderPath_linker, outputFolderPath_sdf, outputFolderPath_chop_comb] = outputPathList except: print('Error Code: 1130. Failed to parse output path list.') return try: from rmRedRigid01 import RmRigidRed except: print('Error Code: 1100-01') return # Rigid Part #Step 3: Form and group lists by atom numbers fileNameAndAtomNumList_R=[] try: with open(outputFolderPath_log+'RigidListAll.txt','r') as inList: fileNameAndAtomNumList_R=inList.readlines() except: print('Error Code: 1100.') return FNAANLList_R=[] #file name and atom number list list try: for FNAAN in fileNameAndAtomNumList_R: #FNAAN: file name and atom number FNAANList=FNAAN.split() #FNAANList: file name and atom number list FNAANLList_R.append([FNAANList[0],FNAANList[1:]]) except: print('Error Code: 1101.') return atomNumPro_R=[] try: for tempValue in FNAANLList_R: #tempValue: [[filename],['T','','C','','N','','O','']] if tempValue[1] not in atomNumPro_R: #tempValue[1]: ['T','','C','','N','','O',''],Group Property atomNumPro_R.append(tempValue[1]) except: print('Error Code: 1102.') return try: fileNameGroup_R=[[y[0] for y in FNAANLList_R if y[1]==x] for x in atomNumPro_R] except: print('Error Code: 1103.') return try: with open(outputFolderPath_log+'RigidGroupList.txt','w') as groupOut: for i in range(len(atomNumPro_R)): groupOut.write(' '.join(atomNumPro_R[i])+' - ') groupOut.write('File Num: ') groupOut.write(str(len(fileNameGroup_R[i]))) groupOut.write('\n') except: print('Error Code: 1104.') return try: # Log path = outputFolderPath_log+'Process.log' msg = ' Start Remove Rigid Redundancy ' PrintLog(path, msg) except: print('Error Code: 1105.') return #Step 4: Generate similarity data and etc. try: fileNameGroup_Rs=sorted(fileNameGroup_R,key=lambda x:len(x),reverse=True) #process long list first except: print('Error Code: 1106.') return try: partial_RmRigid=partial(RmRigidRed, outputDir) pool.map(partial_RmRigid,fileNameGroup_Rs) except: print('Error Code: 1107.') return try: # Log path = outputFolderPath_log+'Process.log' msg = ' End Remove Rigid Redundancy ' PrintLog(path, msg) except: print('Error Code: 1108.') return def RmLinkerRedundancy(outputPathList, pool): try: [outputDir, outputFolderPath_log, outputFolderPath_chop, outputFolderPath_active, outputFolderPath_linker, outputFolderPath_sdf, outputFolderPath_chop_comb] = outputPathList except: print('Error Code: 1130. Failed to parse output path list.') return try: from combineLinkers01 import combineLinkers from rmRedLinker03 import RmLinkerRed except: print('Error Code: 1110-01') return # Linker Part #Step 3: Form and group lists by atom numbers fileNameAndAtomNumList_L=[] try: with open(outputFolderPath_log+'LinkerListAll.txt','r') as inList: fileNameAndAtomNumList_L=inList.readlines() except: print('Error Code: 1110.') return FNAANLList_L=[] #file name and atom number list list try: for FNAAN in fileNameAndAtomNumList_L: #FNAAN: file name and atom number FNAANList=FNAAN.split() #FNAANList: file name and atom number list FNAANLList_L.append([FNAANList[0],FNAANList[1:]]) except: print('Error Code: 1111.') return atomNumPro_L=[] try: for tempValue in FNAANLList_L: if tempValue[1] not in atomNumPro_L: atomNumPro_L.append(tempValue[1]) except: print('Error Code: 1112.') return try: fileNameGroup_L=[[y[0] for y in FNAANLList_L if y[1]==x] for x in atomNumPro_L] except: print('Error Code: 1113.') return try: with open(outputFolderPath_log+'LinkerGroupList.txt','w') as groupOut: for i in range(len(atomNumPro_L)): groupOut.write(' '.join(atomNumPro_L[i])+' - ') groupOut.write('File Num: ') groupOut.write(str(len(fileNameGroup_L[i]))) groupOut.write('\n') except: print('Error Code: 1114.') return try: # Log path = outputFolderPath_log+'Process.log' msg = ' Start Remove Linker Redundancy ' PrintLog(path, msg) except: print('Error Code: 1115.') return #Step 4: Generate similarity data and etc. try: partial_RmLinker=partial(RmLinkerRed, outputDir) except: print('Error Code: 1116.') return inputL=[] try: for i in range(len(fileNameGroup_L)): inputL.append([fileNameGroup_L[i],atomNumPro_L[i]]) except: print('Error Code: 1117.') return try: inputLs=sorted(inputL,key=lambda x:len(x[0]),reverse=True) except: print('1118.') return try: pool.map(partial_RmLinker,inputLs) except: print('1119.') return try: # Log path = outputFolderPath_log+'Process.log' msg = ' End Remove Linker Redundancy ' PrintLog(path, msg) except: print('Error Code: 1120.') return def PrintLog(path, msg): # write log with open(path, 'at') as outLog: outLog.write(time.asctime( time.localtime(time.time()) )) outLog.write(msg) outLog.write('\n') def main(): try: try: [mainEntryPath, inputFolderPath, outputDir, processNum, outputSelection, outputFormat] = ParseArgs() except: print('Error Code: 1001. Failed to parse input commands.') return try: [outputPathList, pool] = PrepareEnv(outputDir, mainEntryPath, processNum) except: print('Error Code: 1002. Failed to prepare running evnironment.') return try: ProcessData(inputFolderPath, outputPathList, outputSelection, outputFormat, pool) except: print('Error Code: 1003. Failed to process data.') return try: AdjustOutput(outputPathList, outputSelection, outputFormat) except: print('Error Code: 1004. Failed to adjust output format.') return except: print('Error Code: 1000') return if __name__ == "__main__": main()
gpl-3.0
8,407,459,200,154,259,000
32.59676
181
0.550313
false
4.062473
false
false
false
getpatchwork/patchwork
patchwork/migrations/0043_merge_patch_submission.py
1
11421
from django.conf import settings from django.db import connection, migrations, models import django.db.models.deletion import patchwork.fields def migrate_data(apps, schema_editor): if connection.vendor == 'postgresql': schema_editor.execute( """ UPDATE patchwork_submission SET archived = patchwork_patch.archived2, commit_ref = patchwork_patch.commit_ref2, delegate_id = patchwork_patch.delegate2_id, diff = patchwork_patch.diff2, hash = patchwork_patch.hash2, number = patchwork_patch.number2, pull_url = patchwork_patch.pull_url2, related_id = patchwork_patch.related2_id, series_id = patchwork_patch.series2_id, state_id = patchwork_patch.state2_id FROM patchwork_patch WHERE patchwork_submission.id = patchwork_patch.submission_ptr_id """ ) elif connection.vendor == 'mysql': schema_editor.execute( """ UPDATE patchwork_submission, patchwork_patch SET patchwork_submission.archived = patchwork_patch.archived2, patchwork_submission.commit_ref = patchwork_patch.commit_ref2, patchwork_submission.delegate_id = patchwork_patch.delegate2_id, patchwork_submission.diff = patchwork_patch.diff2, patchwork_submission.hash = patchwork_patch.hash2, patchwork_submission.number = patchwork_patch.number2, patchwork_submission.pull_url = patchwork_patch.pull_url2, patchwork_submission.related_id = patchwork_patch.related2_id, patchwork_submission.series_id = patchwork_patch.series2_id, patchwork_submission.state_id = patchwork_patch.state2_id WHERE patchwork_submission.id = patchwork_patch.submission_ptr_id """ # noqa ) else: schema_editor.execute( """ UPDATE patchwork_submission SET ( archived, commit_ref, delegate_id, diff, hash, number, pull_url, related_id, series_id, state_id ) = ( SELECT patchwork_patch.archived2, patchwork_patch.commit_ref2, patchwork_patch.delegate2_id, patchwork_patch.diff2, patchwork_patch.hash2, patchwork_patch.number2, patchwork_patch.pull_url2, patchwork_patch.related2_id, patchwork_patch.series2_id, patchwork_patch.state2_id FROM patchwork_patch WHERE patchwork_patch.submission_ptr_id = patchwork_submission.id ) WHERE EXISTS ( SELECT * FROM patchwork_patch WHERE patchwork_patch.submission_ptr_id = patchwork_submission.id ) """ # noqa ) class Migration(migrations.Migration): atomic = False dependencies = [ ('patchwork', '0042_add_cover_model'), ] operations = [ # move the 'PatchTag' model to point to 'Submission' migrations.RemoveField(model_name='patch', name='tags',), migrations.AddField( model_name='submission', name='tags', field=models.ManyToManyField( through='patchwork.PatchTag', to='patchwork.Tag' ), ), migrations.AlterField( model_name='patchtag', name='patch', field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='patchwork.Submission', ), ), # do the same for any other field that references 'Patch' migrations.AlterField( model_name='bundle', name='patches', field=models.ManyToManyField( through='patchwork.BundlePatch', to='patchwork.Submission' ), ), migrations.AlterField( model_name='bundlepatch', name='patch', field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='patchwork.Submission', ), ), migrations.AlterField( model_name='check', name='patch', field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='patchwork.Submission', ), ), migrations.AlterField( model_name='event', name='patch', field=models.ForeignKey( blank=True, help_text='The patch that this event was created for.', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='patchwork.Submission', ), ), migrations.AlterField( model_name='patchchangenotification', name='patch', field=models.OneToOneField( on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='patchwork.Submission', ), ), # rename all the fields on 'Patch' so we don't have duplicates when we # add them to 'Submission' migrations.RemoveIndex( model_name='patch', name='patch_list_covering_idx', ), migrations.AlterUniqueTogether(name='patch', unique_together=set([]),), migrations.RenameField( model_name='patch', old_name='archived', new_name='archived2', ), migrations.RenameField( model_name='patch', old_name='commit_ref', new_name='commit_ref2', ), migrations.RenameField( model_name='patch', old_name='delegate', new_name='delegate2', ), migrations.RenameField( model_name='patch', old_name='diff', new_name='diff2', ), migrations.RenameField( model_name='patch', old_name='hash', new_name='hash2', ), migrations.RenameField( model_name='patch', old_name='number', new_name='number2', ), migrations.RenameField( model_name='patch', old_name='pull_url', new_name='pull_url2', ), migrations.RenameField( model_name='patch', old_name='related', new_name='related2', ), migrations.RenameField( model_name='patch', old_name='series', new_name='series2', ), migrations.RenameField( model_name='patch', old_name='state', new_name='state2', ), # add the fields found on 'Patch' to 'Submission' migrations.AddField( model_name='submission', name='archived', field=models.BooleanField(default=False), ), migrations.AddField( model_name='submission', name='commit_ref', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AddField( model_name='submission', name='delegate', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, ), ), migrations.AddField( model_name='submission', name='diff', field=models.TextField(blank=True, null=True), ), migrations.AddField( model_name='submission', name='hash', field=patchwork.fields.HashField( blank=True, max_length=40, null=True ), ), migrations.AddField( model_name='submission', name='number', field=models.PositiveSmallIntegerField( default=None, help_text='The number assigned to this patch in the series', null=True, ), ), migrations.AddField( model_name='submission', name='pull_url', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AddField( model_name='submission', name='related', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='patches', related_query_name='patch', to='patchwork.PatchRelation', ), ), migrations.AddField( model_name='submission', name='series', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='patches', related_query_name='patch', to='patchwork.Series', ), ), migrations.AddField( model_name='submission', name='state', field=models.ForeignKey( null=True, on_delete=django.db.models.deletion.CASCADE, to='patchwork.State', ), ), # copy the data from 'Patch' to 'Submission' migrations.RunPython(migrate_data, None, atomic=False), # configure metadata for the 'Submission' model migrations.AlterModelOptions( name='submission', options={ 'base_manager_name': 'objects', 'ordering': ['date'], 'verbose_name_plural': 'Patches', }, ), migrations.AlterUniqueTogether( name='submission', unique_together=set([('series', 'number'), ('msgid', 'project')]), ), migrations.RemoveIndex( model_name='submission', name='submission_covering_idx', ), migrations.AddIndex( model_name='submission', index=models.Index( fields=[ 'archived', 'state', 'delegate', 'date', 'project', 'submitter', 'name', ], name='patch_covering_idx', ), ), # remove the foreign key fields from the 'Patch' model migrations.RemoveField(model_name='patch', name='delegate2',), migrations.RemoveField(model_name='patch', name='patch_project',), migrations.RemoveField(model_name='patch', name='related2',), migrations.RemoveField(model_name='patch', name='series2',), migrations.RemoveField(model_name='patch', name='state2',), migrations.RemoveField(model_name='patch', name='submission_ptr',), # drop the 'Patch' model and rename 'Submission' to 'Patch' migrations.DeleteModel(name='Patch',), migrations.RenameModel(old_name='Submission', new_name='Patch',), ]
gpl-2.0
-758,566,755,988,265,600
34.468944
82
0.523159
false
4.616411
false
false
false
iandees/all-the-places
locations/spiders/elpolloloco.py
1
2496
import scrapy import re from locations.items import GeojsonPointItem class ElPolloLocoSpider(scrapy.Spider): name = "elpolloloco" allowed_domains = ["www.elpolloloco.com"] start_urls = ( 'https://www.elpolloloco.com/locations/all-locations.html', ) def parse_stores(self, response): properties = { 'addr_full': response.xpath('normalize-space(//meta[@itemprop="streetAddress"]/@content)').extract_first(), 'phone': response.xpath('normalize-space(//div[@itemprop="telephone"]/text())').extract_first(), 'city': response.xpath('normalize-space(//meta[@itemprop="addressLocality"]/@content)').extract_first(), 'state': response.xpath('normalize-space(//meta[@itemprop="addressRegion"]/@content)').extract_first(), 'postcode':response.xpath('normalize-space(//meta[@itemprop="postalCode"]/@content)').extract_first(), 'ref': response.xpath('normalize-space(//div[@itemprop="branchCode"]/text())').extract_first(), 'website': response.url, 'lat': response.xpath('normalize-space(//meta[@itemprop="latitude"]/@content)').extract_first(), 'lon': response.xpath('normalize-space(//meta[@itemprop="longitude"]/@content)').extract_first(), 'opening_hours': self.parse_opening_hours(response.xpath('//div[@itemprop="openingHoursSpecification"]')), } yield GeojsonPointItem(**properties) def parse_opening_hours(self, opening_hours_div): result_array = [] for div in opening_hours_div: day_of_week_list = div.xpath('normalize-space(./meta[@itemprop="dayOfWeek"]/@href)').extract_first().rsplit("/",1) open_time = div.xpath('normalize-space(./meta[@itemprop="opens"]/@content)').extract_first().rsplit(":",1)[0] close_time = div.xpath('normalize-space(./meta[@itemprop="closes"]/@content)').extract_first().rsplit(":",1)[0] if (len(day_of_week_list) == 2): day_of_week = day_of_week_list[-1][:2] result_array.append("%s %s-%s" % (day_of_week, open_time, close_time)) return ';'.join(result_array) def parse(self, response): urls = response.xpath('//p[@class="locaFLstoreInfo" and ./a/span[@class ="locaSSComingSoon" and not(contains(./text(),"(Coming Soon)"))]]/a/@href').extract() for path in urls: yield scrapy.Request(response.urljoin(path), callback=self.parse_stores)
mit
-1,993,626,636,176,950,500
55.727273
165
0.623798
false
3.510549
false
false
false
daeilkim/refinery
refinery/refinery/data/models.py
1
10950
# models.py contains code for defining the user object and behavior which will be used throughout the site from refinery import db, app import datetime from refinery.webapp.pubsub import msgServer from collections import defaultdict import random,os,re,codecs from collections import defaultdict import pickle # Defines a User class that takes the database and returns a User object that contains id,nickname,email class User(db.Model): id = db.Column(db.Integer, primary_key = True) username = db.Column(db.String(64), index = True, unique = True) password = db.Column(db.String(64), index = True) email = db.Column(db.String(120), index = True, unique = True) image = db.Column(db.String(100)) #datasets = db.relationship('Dataset', backref = 'author', lazy = 'dynamic') def __init__(self, username, password, email): self.username = username self.password = password self.email = email self.image = None def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return unicode(self.id) def __repr__(self): return '<User %r>' % (self.username) def check_password(self, proposed_password): if self.password != proposed_password: return False else: return True class Experiment(db.Model): id = db.Column(db.Integer, primary_key = True) extype = db.Column(db.String(100)) # name of the model i.e topic_model status = db.Column(db.Text) # status (idle,start,inprogress,finish) def __init__(self, owner_id, extype): self.owner_id = owner_id self.extype = extype self.status = 'idle' def getExInfo(self): if(self.extype == "topicmodel"): return TopicModelEx.query.filter_by(ex_id=self.id).first() elif(self.extype == "summarize"): return SummarizeEx.query.filter_by(ex_id=self.id).first() else: return None class TopicModelEx(db.Model): id = db.Column(db.Integer, primary_key = True) ex_id = db.Column(db.Integer, db.ForeignKey('experiment.id')) viz_data = db.Column(db.PickleType) #the top words and topic proportions nTopics = db.Column(db.Integer) stopwords = db.Column(db.PickleType) def __init__(self, ex_id, nTopics): self.ex_id = ex_id self.viz_data = None self.nTopics = nTopics self.stopwords = [] class SummarizeEx(db.Model): id = db.Column(db.Integer, primary_key = True) ex_id = db.Column(db.Integer, db.ForeignKey('experiment.id')) current_summary = db.Column(db.PickleType) # a list of sentences in the current summary top_candidates = db.Column(db.PickleType) # a list of top ranked candidate sentences sents = db.Column(db.PickleType) running = db.Column(db.Integer) def __init__(self, ex_id): self.ex_id = ex_id self.current_summary = [] self.top_candidates = [] self.running = 0 class DataDoc(db.Model): id = db.Column(db.Integer, primary_key = True) data_id = db.Column(db.Integer, db.ForeignKey('dataset.id')) doc_id = db.Column(db.Integer, db.ForeignKey('document.id')) def __init__(self, dset, doc): self.data_id = dset self.doc_id = doc class Document(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(256)) #the name of this file path = db.Column(db.String(256)) #the path to the raw file data def __init__(self, name, path): self.name = name self.path = path self.sents = [] def getStaticURL(self): print "!!!!!!!","/" + os.path.relpath(self.path,"refinery") return "/" + os.path.relpath(self.path,"refinery") def getText(self): lines = [line for line in codecs.open(self.path,"r","utf-8")] return "\n".join(lines) def tokenize_sentence(text): ''' Returns list of words found in String. Matches A-Za-z and \'s ''' wordPattern = "[A-Za-z]+[']*[A-Za-z]*" wordlist = re.findall( wordPattern, text) return wordlist class Folder(db.Model): id = db.Column(db.Integer, primary_key = True) dataset_id = db.Column(db.Integer, db.ForeignKey('dataset.id')) # the dataset that was used docIDs = db.Column(db.PickleType) #hopefully, this can be a dictionary of included docIDs name = db.Column(db.String) tm_id = db.Column(db.Integer, db.ForeignKey('experiment.id')) sum_id = db.Column(db.Integer, db.ForeignKey('experiment.id')) vocabSize = db.Column(db.Integer) dirty = db.Column(db.String(20)) def __init__(self, dataset_id, name, docIDs): self.dataset_id = dataset_id self.docIDs = docIDs self.name = name self.tm_id = None self.sum_id = None self.dirty = "dirty" def numSents(self): s = Experiment.query.get(self.sum_id).getExInfo() if s.sents: return sum([len(s.sents[ss]) for ss in s.sents]) return 0 def numTopics(self): tm = Experiment.query.get(self.tm_id) return tm.getExInfo().nTopics def topicModelEx(self): return Experiment.query.get(self.tm_id) def sumModelEx(self): return Experiment.query.get(self.sum_id) def initialize(self): ex1 = Experiment(self.id, "topicmodel") db.session.add(ex1) db.session.commit() tm = TopicModelEx(ex1.id,10) db.session.add(tm) db.session.commit() self.tm_id = ex1.id ex2 = Experiment(self.id, "summarize") db.session.add(ex2) db.session.commit() ei = SummarizeEx(ex2.id) db.session.add(ei) db.session.commit() self.sum_id = ex2.id db.session.commit() def documents(self): # a generator for documents dataset = Dataset.query.get(self.dataset_id) for d in dataset.documents: if d.id in self.docIDs: yield d def N(self): dataset = Dataset.query.get(self.dataset_id) tot = len(list(self.documents())) return tot def all_docs(self): return sorted([Document.query.get(x.doc_id) for x in self.documents()],key=lambda x: x.id) def preprocTM(self, username, min_doc, max_doc_percent): #we need to add options, like to get rid of xml tags! STOPWORDFILEPATH = 'refinery/static/assets/misc/stopwords.txt' stopwords = set([x.strip() for x in open(STOPWORDFILEPATH)]) allD = self.all_docs() nDocs = len(allD) WC = defaultdict(int) DWC = defaultdict( lambda: defaultdict(int) ) def addWord(f,w): WC[w] += 1 DWC[f][w] += 1 c = 0.0 prev = 0 for d in allD: filE = d.path c += 1.0 pc = int(c / float(nDocs) * 100) if pc > prev: prev = pc s = 'pprog,Step 1,' + str(self.id) + "," + str(pc) msgServer.publish(username + 'Xmenus', "%s" % s) [[addWord(filE,word) for word in tokenize_sentence(line) if word.lower() not in stopwords] for line in open(filE)] # now remove words with bad appearace stats to_remove = [] c = 0.0 oldpc = -1 for w in WC: c += 1.0 pc = int(c/float(len(WC)) * 100) if not oldpc == pc: s = 'pprog,Step 2,' + str(self.id) + "," + str(pc) #print s msgServer.publish(username + 'Xmenus', "%s" % s) oldpc = pc has_w = [d for d,m in DWC.items() if w in m] n_has_w = len(has_w) doc_percent = float(n_has_w)/float(nDocs) #print w,doc_percent,n_has_w if n_has_w < min_doc or doc_percent > max_doc_percent: [DWC[d].pop(w,None) for d in has_w] to_remove.append(w) [WC.pop(w,None) for w in to_remove] vocab = [w for w in WC] print "N VOCAB",len(vocab) v_enum = defaultdict(int) for w in vocab: v_enum[w] = len(v_enum) d_enum = defaultdict(int) for f in allD: d_enum[f.path] = len(d_enum) outfile = open(self.wordcount_path(),'w') for d in allD: f = d.path m = DWC[f] fID = d_enum[f] for w, c in m.items(): wID = v_enum[w] outfile.write(str(fID) + ',' + str(wID) + ',' + str(c) + '\n') outfile.close() self.vocabSize = len(vocab) outfile = open(self.vocab_path(),'w') [outfile.write(x + "\n") for x in vocab] outfile.close() self.dirty = "clean" db.session.commit() def preproc_path(self): dataset = Dataset.query.get(self.dataset_id) return "refinery/static/users/" + User.query.get(dataset.owner_id).username + "/processed/" def wordcount_path(self): return self.preproc_path() + str(self.id) + "_word_count.txt" def vocab_path(self): return self.preproc_path() + str(self.id) + "_vocab.txt" def unigram(self): wcfile = self.wordcount_path() lines = [x.strip().split(",") for x in open(wcfile,'r')] unigram_dist = [0.0 for _ in xrange(self.vocabSize)] for l in lines: wID = int(l[1]) wC = int(l[2]) unigram_dist[wID] += wC tot = sum(unigram_dist) return [x / tot for x in unigram_dist] #return unigram_dist def get_vocab_list(self): vocabfile = self.vocab_path() return [x.strip() for x in open(vocabfile,'r')] class Dataset(db.Model): id = db.Column(db.Integer, primary_key = True) owner_id = db.Column(db.Integer, db.ForeignKey('user.id')) name = db.Column(db.String(100)) # name of the dataset summary = db.Column(db.Text) # summary of the dataset (optional) img = db.Column(db.String(100)) # path to dataset img owner = db.relationship('User', backref = 'datasets') folders = db.relationship('Folder', backref = 'dataset', lazy = 'dynamic') documents = db.relationship('DataDoc', backref = 'docdataset', lazy = 'dynamic') def get_folders(self): return self.folders.order_by(Folder.id) def __init__(self, owner, name, summary, img=None): self.owner_id = owner self.name = name self.summary = summary if img is None: random_img = random.choice(os.listdir(app.config['RANDOM_IMG_DIRECTORY'])) self.img = os.path.join("assets/images/random", random_img) else: self.img = img
mit
-3,804,350,228,446,922,000
30.285714
127
0.572603
false
3.444479
false
false
false
cloudartisan/jarvis
streams.py
1
3192
#!/usr/bin/env python import time import StringIO from threading import Thread from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from SocketServer import ThreadingMixIn import cv2 import numpy from PIL import Image class DummyStream: def __init__(self): self.stopped = False self._frame = None @property def frame(self): return self._frame @frame.setter def frame(self, frame): self._frame = frame def read(self): return self.frame def start(self): return self def stop(self): self.stopped = True class WebcamVideoStream: def __init__(self, device=0, should_mirror=False): self.should_mirror = should_mirror self.stopped = False self.grabbed = False self._frame = None self._stream = cv2.VideoCapture(device) def read(self): if self.should_mirror and self._frame is not None: return numpy.fliplr(self._frame).copy() else: return self._frame def start(self): t = Thread(target=self.update, args=()) t.daemon = True t.start() return self def update(self): while not self.stopped: self.grabbed, self._frame = self._stream.read() def stop(self): self.stopped = True class WebRequestHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path.endswith('.mjpg'): self.send_response(200) self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary') self.end_headers() while not self.server.stopped: frame = self.server.camera_feed.read() if frame is None: continue image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(image) s = StringIO.StringIO() image.save(s, 'JPEG') self.wfile.write('--jpgboundary') self.send_header('Content-type', 'image/jpeg') self.send_header('Content-length', str(s.len)) self.end_headers() image.save(self.wfile, 'JPEG') else: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('<html><head></head><body>') self.wfile.write('<img src="/stream.mjpg"/>') self.wfile.write('</body></html>') class ThreadedWebStream(Thread): def __init__(self, camera_feed, ip='127.0.0.1', port=8000): class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): pass super(ThreadedWebStream, self).__init__() self.ip = ip self.port = port self.server = ThreadedHTTPServer((ip, port), WebRequestHandler) self.server.camera_feed = camera_feed self.server.stopped = True def run(self): self.server.stopped = False self.server.serve_forever() def stop(self): self.server.stopped = True self.server.shutdown() def __str__(self): return "{}:{}".format(self.ip, self.port)
apache-2.0
-5,632,914,860,883,558,000
27.247788
96
0.579887
false
4.035398
false
false
false
pmillerchip/firejail
contrib/fjclip.py
1
1239
#!/usr/bin/env python import re import sys import subprocess import fjdisplay usage = """fjclip.py src dest. src or dest can be named firejails or - for stdin or stdout. firemon --x11 to see available running x11 firejails. firejail names can be shortened to least ambiguous. for example 'work-libreoffice' can be shortened to 'work' if no other firejails name starts with 'work'. warning: browsers are dangerous. clipboards from browsers are dangerous. see https://github.com/dxa4481/Pastejacking fjclip.py strips whitespace from both ends, but does nothing else to protect you. use a simple gui text editor like gedit if you want to see what your pasting.""" if len(sys.argv) != 3 or sys.argv == '-h' or sys.argv == '--help': print(usage) exit(1) if sys.argv[1] == '-': clipin_raw = sys.stdin.read() else: display = fjdisplay.getdisplay(sys.argv[1]) clipin_raw = subprocess.check_output(['xsel', '-b', '--display', display]) clipin = clipin_raw.strip() if sys.argv[2] == '-': print(clipin) else: display = fjdisplay.getdisplay(sys.argv[2]) clipout = subprocess.Popen(['xsel', '-b', '-i', '--display', display], stdin=subprocess.PIPE) clipout.communicate(clipin)
gpl-2.0
1,670,571,682,513,023,000
33.416667
91
0.688458
false
3.277778
false
false
false
tiggerntatie/ggame-tutorials
tutorial3.py
1
1622
""" tutorial3.py by E. Dennison """ from ggame import App, RectangleAsset, ImageAsset, SoundAsset from ggame import LineStyle, Color, Sprite, Sound myapp = App() # define colors and line style green = Color(0x00ff00, 1) black = Color(0, 1) noline = LineStyle(0, black) # a rectangle asset and sprite to use as background bg_asset = RectangleAsset(myapp.width, myapp.height, noline, green) bg = Sprite(bg_asset, (0,0)) # A ball! This is already in the ggame-tutorials repository ball_asset = ImageAsset("images/orb-150545_640.png") ball = Sprite(ball_asset, (0, 0)) # Original image is too big. Scale it to 1/10 its original size ball.scale = 0.1 # custom attributes ball.direction = 1 ball.go = True # Sounds pew1_asset = SoundAsset("sounds/pew1.mp3") pew1 = Sound(pew1_asset) pop_asset = SoundAsset("sounds/reappear.mp3") pop = Sound(pop_asset) # reverse - change the ball direction def reverse(b): pop.play() b.direction *= -1 # Set up function for handling screen refresh def step(): if ball.go: ball.x += ball.direction if ball.x + ball.width > myapp.width or ball.x < 0: ball.x -= ball.direction reverse(ball) # Handle the space key def spaceKey(event): ball.go = not ball.go # Handle the "reverse" key def reverseKey(event): reverse(ball) # Handle the mouse click def mouseClick(event): pew1.play() ball.x = event.x ball.y = event.y # Set up event handlers for the app myapp.listenKeyEvent('keydown', 'space', spaceKey) myapp.listenKeyEvent('keydown', 'r', reverseKey) myapp.listenMouseEvent('click', mouseClick) myapp.run(step)
mit
71,991,645,884,679,840
25.177419
67
0.695438
false
2.917266
false
false
false
kalikaneko/bitmask-dev
src/leap/bitmask/bonafide/_srp.py
1
4517
# -*- coding: utf-8 -*- # _srp.py # Copyright (C) 2015 LEAP # # 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/>. """ SRP Authentication. """ import binascii import json import srp class SRPAuthMechanism(object): """ Implement a protocol-agnostic SRP Authentication mechanism. """ def __init__(self, username, password): self.username = username self.srp_user = srp.User(username, password, srp.SHA256, srp.NG_1024) _, A = self.srp_user.start_authentication() self.A = A self.M = None self.M2 = None def get_handshake_params(self): return {'login': bytes(self.username), 'A': binascii.hexlify(self.A)} def process_handshake(self, handshake_response): challenge = json.loads(handshake_response) self._check_for_errors(challenge) salt = challenge.get('salt', None) B = challenge.get('B', None) unhex_salt, unhex_B = self._unhex_salt_B(salt, B) self.M = self.srp_user.process_challenge(unhex_salt, unhex_B) def get_authentication_params(self): # It looks A is not used server side return {'client_auth': binascii.hexlify(self.M), 'A': binascii.hexlify(self.A)} def process_authentication(self, authentication_response): auth = json.loads(authentication_response) self._check_for_errors(auth) uuid = auth.get('id', None) token = auth.get('token', None) self.M2 = auth.get('M2', None) self._check_auth_params(uuid, token, self.M2) return uuid, token def verify_authentication(self): unhex_M2 = _safe_unhexlify(self.M2) self.srp_user.verify_session(unhex_M2) assert self.srp_user.authenticated() def _check_for_errors(self, response): if 'errors' in response: msg = response['errors']['base'] raise SRPAuthError(unicode(msg).encode('utf-8')) def _unhex_salt_B(self, salt, B): if salt is None: raise SRPAuthNoSalt() if B is None: raise SRPAuthNoB() try: unhex_salt = _safe_unhexlify(salt) unhex_B = _safe_unhexlify(B) except (TypeError, ValueError) as e: raise SRPAuthBadDataFromServer(str(e)) return unhex_salt, unhex_B def _check_auth_params(self, uuid, token, M2): if not all((uuid, token, M2)): msg = '%s' % str((M2, uuid, token)) raise SRPAuthBadDataFromServer(msg) class SRPSignupMechanism(object): """ Implement a protocol-agnostic SRP Registration mechanism. """ def get_signup_params(self, username, password): salt, verifier = srp.create_salted_verification_key( bytes(username), bytes(password), srp.SHA256, srp.NG_1024) user_data = { 'user[login]': username, 'user[password_salt]': binascii.hexlify(salt), 'user[password_verifier]': binascii.hexlify(verifier)} return user_data def process_signup(self, signup_response): signup = json.loads(signup_response) errors = signup.get('errors') if errors: msg = 'username ' + errors.get('login')[0] raise SRPRegistrationError(msg) else: username = signup.get('login') return username def _safe_unhexlify(val): return binascii.unhexlify(val) \ if (len(val) % 2 == 0) else binascii.unhexlify('0' + val) class SRPAuthError(Exception): """ Base exception for srp authentication errors """ class SRPAuthNoSalt(SRPAuthError): message = 'The server didn\'t send the salt parameter' class SRPAuthNoB(SRPAuthError): message = 'The server didn\'t send the B parameter' class SRPAuthBadDataFromServer(SRPAuthError): pass class SRPRegistrationError(Exception): pass
gpl-3.0
-6,066,140,394,348,291,000
29.52027
71
0.625858
false
3.726898
false
false
false
MarkusHackspacher/unknown-horizons
horizons/ai/aiplayer/internationaltrademanager.py
1
7150
# ################################################### # Copyright (C) 2008-2017 The Unknown Horizons Team # team@unknown-horizons.org # This file is part of Unknown Horizons. # # Unknown Horizons 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 St, Fifth Floor, Boston, MA 02110-1301 USA # ################################################### import logging from collections import defaultdict from horizons.component.storagecomponent import StorageComponent from horizons.component.tradepostcomponent import TradePostComponent from horizons.constants import RES, TRADER from .mission.internationaltrade import InternationalTrade class InternationalTradeManager: """ An object of this class manages the international trade routes of one AI player. The current implementation is limited to one active route between each pair of our settlement and another player's settlement where each route can have at most one bought and one sold resource. The routes are automatically removed when they have been used once or when the ship gets destroyed. """ log = logging.getLogger("ai.aiplayer.internationaltrade") def __init__(self, owner): super().__init__() self.owner = owner self.world = owner.world self.session = owner.session self.personality = owner.personality_manager.get('InternationalTradeManager') def _trade_mission_exists(self, settlement, settlement_manager): """Return a boolean showing whether there is a trade route between the settlements.""" for mission in self.owner.missions: if not isinstance(mission, InternationalTrade): continue if mission.settlement is settlement and mission.settlement_manager is settlement_manager: return True return False def _add_route(self): """Add a new international trade route if possible.""" ship = None for possible_ship, state in self.owner.ships.items(): if state is self.owner.shipStates.idle: ship = possible_ship break if not ship: #self.log.info('%s international trade: no available ships', self) return # find all possible legal trade route options options = defaultdict(list) # {(settlement, settlement_manager): (total value, amount, resource id, bool(selling)), ...} for settlement in self.world.settlements: if settlement.owner is self.owner: continue # don't allow routes of this type between the player's own settlements for settlement_manager in self.owner.settlement_managers: if self._trade_mission_exists(settlement, settlement_manager): continue # allow only one international trade route between a pair of settlements my_inventory = settlement_manager.settlement.get_component(StorageComponent).inventory resource_manager = settlement_manager.resource_manager # add the options where we sell to the other player for resource_id, limit in settlement.get_component(TradePostComponent).buy_list.items(): if resource_id not in resource_manager.resource_requirements: continue # not a well-known resource: ignore it if limit <= settlement.get_component(StorageComponent).inventory[resource_id]: continue # they aren't actually buying the resource if my_inventory[resource_id] <= resource_manager.resource_requirements[resource_id]: continue # my settlement is unable to sell the resource price = int(self.session.db.get_res_value(resource_id) * TRADER.PRICE_MODIFIER_SELL) tradable_amount = min(my_inventory[resource_id] - resource_manager.resource_requirements[resource_id], limit - settlement.get_component(StorageComponent).inventory[resource_id], ship.get_component(StorageComponent).inventory.get_limit(), settlement.owner.get_component(StorageComponent).inventory[RES.GOLD] // price) options[(settlement, settlement_manager)].append((tradable_amount * price, tradable_amount, resource_id, True)) # add the options where we buy from the other player for resource_id, limit in settlement.get_component(TradePostComponent).sell_list.items(): if resource_id not in resource_manager.resource_requirements: continue # not a well-known resource: ignore it if limit >= settlement.get_component(StorageComponent).inventory[resource_id]: continue # they aren't actually selling the resource if my_inventory[resource_id] >= resource_manager.resource_requirements[resource_id]: continue # my settlement doesn't want to buy the resource price = int(self.session.db.get_res_value(resource_id) * TRADER.PRICE_MODIFIER_BUY) tradable_amount = min(resource_manager.resource_requirements[resource_id] - my_inventory[resource_id], settlement.get_component(StorageComponent).inventory[resource_id] - limit, ship.get_component(StorageComponent).inventory.get_limit(), self.owner.get_component(StorageComponent).inventory[RES.GOLD] // price) options[(settlement, settlement_manager)].append((tradable_amount * price, tradable_amount, resource_id, False)) if not options: #self.log.info('%s international trade: no interesting options', self) return # make up final options where a route is limited to at most one resource bought and one resource sold final_options = [] # [(value, bought resource id or None, sold resource id or None, settlement, settlement_manager), ...] for (settlement, settlement_manager), option in sorted(options.items()): best_buy = None # largest amount of resources best_sale = None # most expensive sale for total_price, tradable_amount, resource_id, selling in option: if selling: if best_sale is None or best_sale[0] < total_price: best_sale = (total_price, tradable_amount, resource_id) else: if best_buy is None or best_buy[1] < tradable_amount: best_buy = (total_price, tradable_amount, resource_id) buy_coefficient = self.personality.buy_coefficient_rich if self.owner.get_component(StorageComponent).inventory[RES.GOLD] > self.personality.little_money else self.personality.buy_coefficient_poor total_value = (best_sale[0] if best_sale else 0) + (best_buy[1] if best_buy else 0) * buy_coefficient final_options.append((total_value, best_buy[2] if best_buy else None, best_sale[2] if best_sale else None, settlement, settlement_manager)) bought_resource, sold_resource, settlement, settlement_manager = sorted(final_options, reverse=True, key=lambda x: x[0])[0][1:] self.owner.start_mission(InternationalTrade(settlement_manager, settlement, ship, bought_resource, sold_resource, self.owner.report_success, self.owner.report_failure)) def tick(self): self._add_route()
gpl-2.0
-3,247,088,160,504,770,000
53.580153
219
0.744336
false
3.725899
false
false
false
fermat618/pida
tests/core/test_languages_extern.py
1
4614
import os #from pida.core.doctype import DocType #from pida.core.testing import test, assert_equal, assert_notequal from pida.utils.languages import OutlineItem, ValidationError, Definition, \ Suggestion, Documentation from pida.core.languages import (Validator, Outliner, External, JobServer, ExternalProxy, Documentator, Definer, Completer, LanguageService) from pida.core.document import Document from .test_services import MockBoss class TestExternalValidator(Validator): def run(self): yield os.getpid() for i in xrange(50): yield ValidationError(message="error %s" % i) class TestExternalOutliner(Outliner): def run(self): yield os.getpid() for i in xrange(50): yield OutlineItem(name="run %s" % i, line=i) class TestDocumentator(Documentator): def run(self, buffer, offset): yield os.getpid() yield buffer yield offset for i in xrange(50): yield Documentation(path="run %s" % i, short="short %s" % i, long=buffer[i:i + 5]) class TestCompleter(Completer): def run(self, base, buffer, offset): yield os.getpid() yield base yield buffer yield offset for i in xrange(30): yield Suggestion("run %s" % i) class TestDefiner(Definer): def run(self, buffer, offset, *k): yield os.getpid() yield buffer yield offset for i in xrange(30): yield Definition(line="run %s" % i, offset=i) class MyExternal(External): validator = TestExternalValidator outliner = TestExternalOutliner documentator = TestDocumentator completer = TestCompleter definer = TestDefiner class MYService(LanguageService): # only test if it gets overridden outliner_factory = TestExternalOutliner validator_factory = TestExternalValidator external = MyExternal def __init__(self, boss): LanguageService.__init__(self, boss) self.something = False self.started = False def pytest_funcarg__svc(request): boss = MockBoss() svc = MYService(boss) svc.create_all() return svc def pytest_funcarg__doc(request): svc = request.getfuncargvalue('svc') doc = Document(svc.boss, __file__) mkp = request.getfuncargvalue('monkeypatch') mkp.setattr(Document, 'project', None) doc.project = None return doc def test_service_override(svc): assert isinstance(svc.jobserver, JobServer) assert issubclass(svc.validator_factory, ExternalProxy) assert issubclass(svc.outliner_factory, ExternalProxy) def test_outliner(svc, doc): # test iterators outliner = svc.outliner_factory(svc, doc) for i, v in enumerate(outliner.run()): if i == 0: assert os.getpid() != v else: assert isinstance(v, OutlineItem) assert "run %s" % (i - 1) == v.name def test_validator(svc, doc): validator = svc.validator_factory(svc, doc) for i, v in enumerate(validator.run()): if i == 0: assert os.getpid() != v else: assert isinstance(v, ValidationError) assert "error %s" % (i - 1) == v.message def test_completer(svc, doc): completer = svc.completer_factory(svc, doc) for i, v in enumerate(completer.run('base', 'some text', 3)): if i == 0: assert os.getpid() != v elif i == 1: assert v == 'base' elif i == 2: assert v == 'some text' elif i == 3: assert v == 3 else: assert isinstance(v, Suggestion) assert "run %s" % (i - 4) == v def test_documenter(svc, doc): documentator = svc.documentator_factory(svc, doc) for i, v in enumerate(documentator.run('base', 'some text')): if i == 0: assert v != os.getpid() elif i == 1: assert 'base' == v elif i == 2: assert 'some text' == v else: assert isinstance(v, Documentation) assert "short %s" % (i - 3) == v.short assert "run %s" % (i - 3) == v.path def test_definer(svc, doc): definer = svc.definer_factory(svc, doc) for i, v in enumerate(definer.run('some text', 4)): if i == 0: assert os.getpid() != v elif i == 1: assert 'some text' == v elif i == 2: assert v == 4 else: assert isinstance(v, Definition) assert i - 3 == v.offset assert "run %s" % (i - 3) == v.line
gpl-2.0
6,641,927,541,506,754,000
26.628743
76
0.58886
false
3.760391
true
false
false
dokipen/trac
trac/mimeview/patch.py
1
12980
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2009 Edgewall Software # Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de> # Copyright (C) 2006 Christian Boos <cboos@neuf.fr> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. # # Author: Christopher Lenz <cmlenz@gmx.de> # Ludvig Strigeus import os.path from trac.core import * from trac.mimeview.api import content_to_unicode, IHTMLPreviewRenderer, \ Mimeview from trac.util.html import escape, Markup from trac.util.text import expandtabs from trac.util.translation import _ from trac.web.chrome import Chrome, add_script, add_stylesheet __all__ = ['PatchRenderer'] class PatchRenderer(Component): """HTML renderer for patches in unified diff format. This uses the same layout as in the wiki diff view or the changeset view. """ implements(IHTMLPreviewRenderer) # IHTMLPreviewRenderer methods def get_quality_ratio(self, mimetype): if mimetype == 'text/x-diff': return 8 return 0 def render(self, context, mimetype, content, filename=None, rev=None): req = context.req content = content_to_unicode(self.env, content, mimetype) changes = self._diff_to_hdf(content.splitlines(), Mimeview(self.env).tab_width) if not changes: raise TracError(_('Invalid unified diff content')) data = {'diff': {'style': 'inline'}, 'no_id': True, 'changes': changes, 'longcol': 'File', 'shortcol': ''} add_script(req, 'common/js/diff.js') add_stylesheet(req, 'common/css/diff.css') return Chrome(self.env).render_template(req, 'diff_div.html', data, fragment=True) # Internal methods # FIXME: This function should probably share more code with the # trac.versioncontrol.diff module def _diff_to_hdf(self, difflines, tabwidth): """ Translate a diff file into something suitable for inclusion in HDF. The result is [(filename, revname_old, revname_new, changes)], where changes has the same format as the result of `trac.versioncontrol.diff.hdf_diff`. If the diff cannot be parsed, this method returns None. """ def _markup_intraline_change(fromlines, tolines): from trac.versioncontrol.diff import _get_change_extent for i in xrange(len(fromlines)): fr, to = fromlines[i], tolines[i] (start, end) = _get_change_extent(fr, to) if start != 0 or end != 0: last = end+len(fr) fromlines[i] = fr[:start] + '\0' + fr[start:last] + \ '\1' + fr[last:] last = end+len(to) tolines[i] = to[:start] + '\0' + to[start:last] + \ '\1' + to[last:] import re space_re = re.compile(' ( +)|^ ') def htmlify(match): div, mod = divmod(len(match.group(0)), 2) return div * '&nbsp; ' + mod * '&nbsp;' comments = [] changes = [] lines = iter(difflines) try: line = lines.next() while True: oldpath = oldrev = newpath = newrev = '' oldinfo = newinfo = [] binary = False # consume preample, storing free lines in comments # (also detect the special case of git binary patches) if not line.startswith('--- '): if not line.startswith('Index: ') and line != '='*67: comments.append(line) if line == "GIT binary patch": binary = True line = lines.next() while line and line != '': line = lines.next() comments.append(line) diffcmd_line = comments[0] # diff --git a/... b/,,, oldpath, newpath = diffcmd_line.split()[-2:] index_line = comments[1] # index 8f****78..1e****5c oldrev, newrev = index_line.split()[-1].split('..') oldinfo = ['', oldpath, oldrev] newinfo = ['', newpath, newrev] else: line = lines.next() continue if not oldinfo and not newinfo: # Base filename/version from '--- <file> [rev]' oldinfo = line.split(None, 2) if len(oldinfo) > 1: oldpath = oldinfo[1] if len(oldinfo) > 2: oldrev = oldinfo[2] # Changed filename/version from '+++ <file> [rev]' line = lines.next() if not line.startswith('+++ '): self.log.debug('expected +++ after ---, got '+line) return None newinfo = line.split(None, 2) if len(newinfo) > 1: newpath = newinfo[1] if len(newinfo) > 2: newrev = newinfo[2] shortrev = ('old', 'new') if oldpath or newpath: sep = re.compile(r'([/.~\\])') commonprefix = ''.join(os.path.commonprefix( [sep.split(newpath), sep.split(oldpath)])) commonsuffix = ''.join(os.path.commonprefix( [sep.split(newpath)[::-1], sep.split(oldpath)[::-1]])[::-1]) if len(commonprefix) > len(commonsuffix): common = commonprefix elif commonsuffix: common = commonsuffix.lstrip('/') a = oldpath[:-len(commonsuffix)] b = newpath[:-len(commonsuffix)] if len(a) < 4 and len(b) < 4: shortrev = (a, b) elif oldpath == '/dev/null': common = _("new file %(new)s", new=newpath.lstrip('b/')) shortrev = ('-', '+') elif newpath == '/dev/null': common = _("deleted file %(deleted)s", deleted=oldpath.lstrip('a/')) shortrev = ('+', '-') else: common = '(a) %s vs. (b) %s' % (oldpath, newpath) shortrev = ('a', 'b') else: common = '' groups = [] groups_title = [] changes.append({'change': 'edit', 'props': [], 'comments': '\n'.join(comments), 'binary': binary, 'diffs': groups, 'diffs_title': groups_title, 'old': {'path': common, 'rev': ' '.join(oldinfo[1:]), 'shortrev': shortrev[0]}, 'new': {'path': common, 'rev': ' '.join(newinfo[1:]), 'shortrev': shortrev[1]}}) comments = [] line = lines.next() while line: # "@@ -333,10 +329,8 @@" or "@@ -1 +1 @@ [... title ...]" r = re.match(r'@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@' '(.*)', line) if not r: break blocks = [] groups.append(blocks) fromline, fromend, toline, toend = \ [int(x or 1) for x in r.groups()[:4]] groups_title.append(r.group(5)) last_type = extra = None fromend += fromline toend += toline line = lines.next() while fromline < fromend or toline < toend or extra: # First character is the command command = ' ' if line: command, line = line[0], line[1:] # Make a new block? if (command == ' ') != last_type: last_type = command == ' ' kind = last_type and 'unmod' or 'mod' block = {'type': kind, 'base': {'offset': fromline - 1, 'lines': []}, 'changed': {'offset': toline - 1, 'lines': []}} blocks.append(block) else: block = blocks[-1] if command == ' ': sides = ['base', 'changed'] elif command == '+': last_side = 'changed' sides = [last_side] elif command == '-': last_side = 'base' sides = [last_side] elif command == '\\' and last_side: meta = block[last_side].setdefault('meta', {}) meta[len(block[last_side]['lines'])] = True sides = [last_side] elif command == '@': # ill-formed patch groups_title[-1] = "%s (%s)" % ( groups_title[-1], _("this hunk was shorter than expected")) line = '@'+line break else: self.log.debug('expected +, - or \\, got '+command) return None for side in sides: if side == 'base': fromline += 1 else: toline += 1 block[side]['lines'].append(line) line = lines.next() extra = line and line[0] == '\\' except StopIteration: pass # Go through all groups/blocks and mark up intraline changes, and # convert to html for o in changes: for group in o['diffs']: for b in group: base, changed = b['base'], b['changed'] f, t = base['lines'], changed['lines'] if b['type'] == 'mod': if len(f) == 0: b['type'] = 'add' elif len(t) == 0: b['type'] = 'rem' elif len(f) == len(t): _markup_intraline_change(f, t) for i in xrange(len(f)): line = expandtabs(f[i], tabwidth, '\0\1') line = escape(line, quotes=False) line = '<del>'.join([space_re.sub(htmlify, seg) for seg in line.split('\0')]) line = line.replace('\1', '</del>') f[i] = Markup(line) if 'meta' in base and i in base['meta']: f[i] = Markup('<em>%s</em>') % f[i] for i in xrange(len(t)): line = expandtabs(t[i], tabwidth, '\0\1') line = escape(line, quotes=False) line = '<ins>'.join([space_re.sub(htmlify, seg) for seg in line.split('\0')]) line = line.replace('\1', '</ins>') t[i] = Markup(line) if 'meta' in changed and i in changed['meta']: t[i] = Markup('<em>%s</em>') % t[i] return changes
bsd-3-clause
-9,055,686,318,459,183,000
44.069444
79
0.4047
false
4.754579
false
false
false
pycontw/pycontw2016
src/users/admin.py
1
1812
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import gettext_lazy as _ from .models import User, CocRecord from .forms import AdminUserChangeForm, UserCreationForm @admin.register(User) class UserAdmin(UserAdmin): fieldsets = ( ( None, {'fields': ('email', 'password')} ), ( _('Personal info'), { 'fields': ( 'speaker_name', 'bio', 'photo', 'twitter_id', 'github_id', 'facebook_profile_url', ), }, ), ( _('Permissions'), { 'fields': ( 'verified', 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions', ), }, ), ( _('Important dates'), {'fields': ('last_login', 'date_joined')}, ), ) add_fieldsets = ( ( None, { 'classes': ('wide',), 'fields': ( 'email', 'password1', 'password2', 'speaker_name', 'bio', 'verified', ), }, ), ) form = AdminUserChangeForm add_form = UserCreationForm list_display = ('email', 'is_staff', 'as_hash') list_filter = ( 'verified', 'is_active', 'is_staff', 'is_superuser', 'groups', ) search_fields = ('email',) ordering = ('email',) filter_horizontal = ('groups', 'user_permissions',) @admin.register(CocRecord) class CocRecordAdmin(admin.ModelAdmin): list_display = ('user', 'coc_version', 'agreed_at', ) list_filter = ('coc_version', ) raw_id_fields = ('user', )
mit
3,297,041,993,475,273,000
25.26087
72
0.46468
false
4.213953
false
false
false
DedMemez/ODS-August-2017
safezone/GameTutorials.py
1
15275
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.safezone.GameTutorials from panda3d.core import Vec4 from direct.gui.DirectGui import * from direct.fsm import FSM from direct.directnotify import DirectNotifyGlobal from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer from direct.interval.IntervalGlobal import * class ChineseTutorial(DirectFrame, FSM.FSM): def __init__(self, doneFunction, doneEvent = None, callback = None): FSM.FSM.__init__(self, 'ChineseTutorial') self.doneFunction = doneFunction base.localAvatar.startSleepWatch(self.handleQuit) self.doneEvent = doneEvent self.callback = callback self.setStateArray(['Page1', 'Page2', 'Quit']) base.localAvatar.startSleepWatch(self.handleQuit) DirectFrame.__init__(self, pos=(-0.7, 0.0, 0.0), image_color=ToontownGlobals.GlobalDialogColor, image_scale=(1.0, 1.5, 1.0), text='', text_scale=0.06) self.accept('stoppedAsleep', self.handleQuit) self['image'] = DGG.getDefaultDialogGeom() self.title = DirectLabel(self, relief=None, text='', text_pos=(0.0, 0.4), text_fg=(1, 0, 0, 1), text_scale=0.13, text_font=ToontownGlobals.getSignFont()) images = loader.loadModel('phase_6/models/golf/checker_tutorial') images.setTransparency(1) self.iPage1 = images.find('**/tutorialPage1*') self.iPage1.reparentTo(aspect2d) self.iPage1.setPos(0.43, -0.1, 0.0) self.iPage1.setScale(13.95) self.iPage1.setTransparency(1) self.iPage1.hide() self.iPage1.getChildren()[1].hide() self.iPage2 = images.find('**/tutorialPage3*') self.iPage2.reparentTo(aspect2d) self.iPage2.setPos(0.43, -0.1, 0.5) self.iPage2.setScale(13.95) self.iPage2.setTransparency(1) self.iPage2.hide() self.iPage3 = images.find('**/tutorialPage2*') self.iPage3.reparentTo(aspect2d) self.iPage3.setPos(0.43, -0.1, -0.5) self.iPage3.setScale(13.95) self.iPage3.setTransparency(1) self.iPage3.hide() buttons = loader.loadModel('phase_3/models/gui/dialog_box_buttons_gui') gui = loader.loadModel('phase_3.5/models/gui/friendslist_gui') self.bNext = DirectButton(self, image=(gui.find('**/Horiz_Arrow_UP'), gui.find('**/Horiz_Arrow_DN'), gui.find('**/Horiz_Arrow_Rllvr'), gui.find('**/Horiz_Arrow_UP')), image3_color=Vec4(1, 1, 1, 0.5), relief=None, text=TTLocalizer.ChineseTutorialNext, text3_fg=Vec4(0, 0, 0, 0.5), text_scale=0.05, text_pos=(0.0, -0.1), pos=(0.35, -0.3, -0.33), command=self.requestNext) self.bPrev = DirectButton(self, image=(gui.find('**/Horiz_Arrow_UP'), gui.find('**/Horiz_Arrow_DN'), gui.find('**/Horiz_Arrow_Rllvr'), gui.find('**/Horiz_Arrow_UP')), image3_color=Vec4(1, 1, 1, 0.5), image_scale=(-1.0, 1.0, 1.0), relief=None, text=TTLocalizer.ChineseTutorialPrev, text3_fg=Vec4(0, 0, 0, 0.5), text_scale=0.05, text_pos=(0.0, -0.1), pos=(-0.35, -0.3, -0.33), command=self.requestPrev) self.bQuit = DirectButton(self, image=(buttons.find('**/ChtBx_OKBtn_UP'), buttons.find('**/ChtBx_OKBtn_DN'), buttons.find('**/ChtBx_OKBtn_Rllvr')), relief=None, text=TTLocalizer.ChineseTutorialDone, text_scale=0.05, text_pos=(0.0, -0.1), pos=(0.0, -0.3, -0.33), command=self.handleQuit) self.bQuit.hide() buttons.removeNode() gui.removeNode() self.request('Page1') return def __del__(self): self.cleanup() def enterPage1(self, *args): self.bNext.show() self.title['text'] = (TTLocalizer.ChineseTutorialTitle1,) self['text'] = TTLocalizer.ChinesePage1 self['text_pos'] = (0.0, 0.23) self['text_wordwrap'] = 13.5 self.bPrev['state'] = DGG.DISABLED self.bPrev.hide() self.bNext['state'] = DGG.NORMAL self.iPage1.show() self.blinker = Sequence() obj = self.iPage1.getChildren()[1] self.iPage1.getChildren()[1].show() self.blinker.append(LerpColorInterval(obj, 0.5, Vec4(0.5, 0.5, 0, 0.0), Vec4(0.2, 0.2, 0.2, 1))) self.blinker.append(LerpColorInterval(obj, 0.5, Vec4(0.2, 0.2, 0.2, 1), Vec4(0.5, 0.5, 0, 0.0))) self.blinker.loop() def exitPage1(self, *args): self.bPrev['state'] = DGG.NORMAL self.iPage1.hide() self.iPage1.getChildren()[1].hide() self.blinker.finish() def enterPage2(self, *args): self.bPrev.show() self.title['text'] = (TTLocalizer.ChineseTutorialTitle2,) self['text'] = TTLocalizer.ChinesePage2 self['text_pos'] = (0.0, 0.28) self['text_wordwrap'] = 12.5 self.bNext['state'] = DGG.DISABLED self.bNext.hide() self.iPage2.show() self.iPage3.show() self.bQuit.show() def exitPage2(self, *args): self.iPage2.hide() self.bQuit.hide() self.iPage3.hide() def enterQuit(self, *args): self.iPage1.removeNode() self.iPage2.removeNode() self.iPage3.removeNode() self.bNext.destroy() self.bPrev.destroy() self.bQuit.destroy() DirectFrame.destroy(self) def exitQuit(self, *args): pass def handleQuit(self, task = None): base.cr.playGame.getPlace().setState('walk') self.forceTransition('Quit') self.doneFunction() if task != None: task.done return class CheckersTutorial(DirectFrame, FSM.FSM): def __init__(self, doneFunction, doneEvent = None, callback = None): FSM.FSM.__init__(self, 'CheckersTutorial') self.doneFunction = doneFunction base.localAvatar.startSleepWatch(self.handleQuit) self.doneEvent = doneEvent self.callback = callback self.setStateArray(['Page1', 'Page2', 'Page3', 'Quit']) DirectFrame.__init__(self, pos=(-0.7, 0.0, 0.0), image_color=ToontownGlobals.GlobalDialogColor, image_scale=(1.0, 1.5, 1.0), text='', text_scale=0.06) self.accept('stoppedAsleep', self.handleQuit) self['image'] = DGG.getDefaultDialogGeom() self.title = DirectLabel(self, relief=None, text='', text_pos=(0.0, 0.4), text_fg=(1, 0, 0, 1), text_scale=0.13, text_font=ToontownGlobals.getSignFont()) images = loader.loadModel('phase_6/models/golf/regularchecker_tutorial') images.setTransparency(1) self.iPage1 = images.find('**/tutorialPage1*') self.iPage1.reparentTo(aspect2d) self.iPage1.setPos(0.43, -0.1, 0.0) self.iPage1.setScale(0.4) self.iPage1.setTransparency(1) self.iPage1.hide() self.iPage2 = images.find('**/tutorialPage2*') self.iPage2.reparentTo(aspect2d) self.iPage2.setPos(0.43, -0.1, 0.0) self.iPage2.setScale(0.4) self.iPage2.setTransparency(1) self.iPage2.hide() self.iPage3 = images.find('**/tutorialPage3*') self.iPage3.reparentTo(aspect2d) self.iPage3.setPos(0.6, -0.1, 0.5) self.iPage3.setScale(0.4) self.iPage3.setTransparency(1) self.obj = self.iPage3.find('**/king*') self.iPage3.hide() self.iPage4 = images.find('**/tutorialPage4*') self.iPage4.reparentTo(aspect2d) self.iPage4.setPos(0.6, -0.1, -0.5) self.iPage4.setScale(0.4) self.iPage4.setTransparency(1) self.iPage4.hide() buttons = loader.loadModel('phase_3/models/gui/dialog_box_buttons_gui') gui = loader.loadModel('phase_3.5/models/gui/friendslist_gui') self.bNext = DirectButton(self, image=(gui.find('**/Horiz_Arrow_UP'), gui.find('**/Horiz_Arrow_DN'), gui.find('**/Horiz_Arrow_Rllvr'), gui.find('**/Horiz_Arrow_UP')), image3_color=Vec4(1, 1, 1, 0.5), relief=None, text=TTLocalizer.ChineseTutorialNext, text3_fg=Vec4(0, 0, 0, 0.5), text_scale=0.05, text_pos=(0.0, -0.08), pos=(0.35, -0.3, -0.38), command=self.requestNext) self.bPrev = DirectButton(self, image=(gui.find('**/Horiz_Arrow_UP'), gui.find('**/Horiz_Arrow_DN'), gui.find('**/Horiz_Arrow_Rllvr'), gui.find('**/Horiz_Arrow_UP')), image3_color=Vec4(1, 1, 1, 0.5), image_scale=(-1.0, 1.0, 1.0), relief=None, text=TTLocalizer.ChineseTutorialPrev, text3_fg=Vec4(0, 0, 0, 0.5), text_scale=0.05, text_pos=(0.0, -0.08), pos=(-0.35, -0.3, -0.38), command=self.requestPrev) self.bQuit = DirectButton(self, image=(buttons.find('**/ChtBx_OKBtn_UP'), buttons.find('**/ChtBx_OKBtn_DN'), buttons.find('**/ChtBx_OKBtn_Rllvr')), relief=None, text=TTLocalizer.ChineseTutorialDone, text_scale=0.05, text_pos=(0.0, -0.1), pos=(0.0, -0.3, -0.38), command=self.handleQuit) self.bQuit.hide() buttons.removeNode() gui.removeNode() self.request('Page1') return def __del__(self): self.cleanup() def enterPage1(self, *args): self.bNext.show() self.title['text'] = (TTLocalizer.ChineseTutorialTitle1,) self['text'] = TTLocalizer.CheckersPage1 self['text_pos'] = (0.0, 0.23) self['text_wordwrap'] = 13.5 self['text_scale'] = 0.06 self.bPrev['state'] = DGG.DISABLED self.bPrev.hide() self.bNext['state'] = DGG.NORMAL self.iPage1.show() def exitPage1(self, *args): self.bPrev['state'] = DGG.NORMAL self.iPage1.hide() def enterPage2(self, *args): self.bPrev.show() self.bNext.show() self.title['text'] = (TTLocalizer.ChineseTutorialTitle2,) self['text'] = TTLocalizer.CheckersPage2 self['text_pos'] = (0.0, 0.28) self['text_wordwrap'] = 12.5 self['text_scale'] = 0.06 self.bNext['state'] = DGG.NORMAL self.iPage2.show() def exitPage2(self, *args): self.iPage2.hide() def enterPage3(self, *args): self.bPrev.show() self.title['text'] = (TTLocalizer.ChineseTutorialTitle2,) self['text'] = TTLocalizer.CheckersPage3 + '\n\n' + TTLocalizer.CheckersPage4 self['text_pos'] = (0.0, 0.32) self['text_wordwrap'] = 19 self['text_scale'] = 0.05 self.bNext['state'] = DGG.DISABLED self.blinker = Sequence() self.blinker.append(LerpColorInterval(self.obj, 0.5, Vec4(0.5, 0.5, 0, 0.0), Vec4(0.9, 0.9, 0, 1))) self.blinker.append(LerpColorInterval(self.obj, 0.5, Vec4(0.9, 0.9, 0, 1), Vec4(0.5, 0.5, 0, 0.0))) self.blinker.loop() self.bNext.hide() self.iPage3.show() self.iPage4.show() self.bQuit.show() def exitPage3(self, *args): self.blinker.finish() self.iPage3.hide() self.bQuit.hide() self.iPage4.hide() def enterQuit(self, *args): self.iPage1.removeNode() self.iPage2.removeNode() self.iPage3.removeNode() self.bNext.destroy() self.bPrev.destroy() self.bQuit.destroy() DirectFrame.destroy(self) def exitQuit(self, *args): pass def handleQuit(self, task = None): self.forceTransition('Quit') base.cr.playGame.getPlace().setState('walk') self.doneFunction() if task != None: task.done return class FindFourTutorial(DirectFrame, FSM.FSM): def __init__(self, doneFunction, doneEvent = None, callback = None): FSM.FSM.__init__(self, 'FindFourTutorial') self.doneFunction = doneFunction base.localAvatar.startSleepWatch(self.handleQuit) self.doneEvent = doneEvent self.callback = callback self.setStateArray(['Page1', 'Page2', 'Quit']) base.localAvatar.startSleepWatch(self.handleQuit) DirectFrame.__init__(self, pos=(-0.7, 0.0, 0.0), image_color=ToontownGlobals.GlobalDialogColor, image_scale=(1.0, 1.5, 1.0), text='', text_scale=0.06) self.accept('stoppedAsleep', self.handleQuit) self['image'] = DGG.getDefaultDialogGeom() self.title = DirectLabel(self, relief=None, text='', text_pos=(0.0, 0.4), text_fg=(1, 0, 0, 1), text_scale=0.13, text_font=ToontownGlobals.getSignFont()) buttons = loader.loadModel('phase_3/models/gui/dialog_box_buttons_gui') gui = loader.loadModel('phase_3.5/models/gui/friendslist_gui') self.bNext = DirectButton(self, image=(gui.find('**/Horiz_Arrow_UP'), gui.find('**/Horiz_Arrow_DN'), gui.find('**/Horiz_Arrow_Rllvr'), gui.find('**/Horiz_Arrow_UP')), image3_color=Vec4(1, 1, 1, 0.5), relief=None, text=TTLocalizer.ChineseTutorialNext, text3_fg=Vec4(0, 0, 0, 0.5), text_scale=0.05, text_pos=(0.0, -0.1), pos=(0.35, -0.3, -0.33), command=self.requestNext) self.bPrev = DirectButton(self, image=(gui.find('**/Horiz_Arrow_UP'), gui.find('**/Horiz_Arrow_DN'), gui.find('**/Horiz_Arrow_Rllvr'), gui.find('**/Horiz_Arrow_UP')), image3_color=Vec4(1, 1, 1, 0.5), image_scale=(-1.0, 1.0, 1.0), relief=None, text=TTLocalizer.ChineseTutorialPrev, text3_fg=Vec4(0, 0, 0, 0.5), text_scale=0.05, text_pos=(0.0, -0.1), pos=(-0.35, -0.3, -0.33), command=self.requestPrev) self.bQuit = DirectButton(self, image=(buttons.find('**/ChtBx_OKBtn_UP'), buttons.find('**/ChtBx_OKBtn_DN'), buttons.find('**/ChtBx_OKBtn_Rllvr')), relief=None, text=TTLocalizer.ChineseTutorialDone, text_scale=0.05, text_pos=(0.0, -0.1), pos=(0.0, -0.3, -0.33), command=self.handleQuit) self.bQuit.hide() buttons.removeNode() gui.removeNode() self.request('Page1') return def __del__(self): self.cleanup() def enterPage1(self, *args): self.bNext.show() self.title['text'] = (TTLocalizer.ChineseTutorialTitle1,) self['text'] = TTLocalizer.FindFourPage1 self['text_pos'] = (0.0, 0.23) self['text_wordwrap'] = 13.5 self.bPrev['state'] = DGG.DISABLED self.bPrev.hide() self.bNext['state'] = DGG.NORMAL def exitPage1(self, *args): self.bPrev['state'] = DGG.NORMAL def enterPage2(self, *args): self.bPrev.show() self.title['text'] = (TTLocalizer.ChineseTutorialTitle2,) self['text'] = TTLocalizer.FindFourPage2 self['text_pos'] = (0.0, 0.28) self['text_wordwrap'] = 12.5 self.bNext['state'] = DGG.DISABLED self.bNext.hide() self.bQuit.show() def exitPage2(self, *args): self.bQuit.hide() def enterQuit(self, *args): self.bNext.destroy() self.bPrev.destroy() self.bQuit.destroy() DirectFrame.destroy(self) def exitQuit(self, *args): pass def handleQuit(self, task = None): base.cr.playGame.getPlace().setState('walk') self.forceTransition('Quit') self.doneFunction() if task != None: task.done return
apache-2.0
-6,883,993,430,927,133,000
43.198225
294
0.594697
false
3.00689
false
false
false
a1ezzz/wasp-general
wasp_general/cli/curses_commands.py
1
2162
# -*- coding: utf-8 -*- # wasp_general/cli/curses_commands.py # # Copyright (C) 2016 the wasp-general authors and contributors # <see AUTHORS file> # # This file is part of wasp-general. # # Wasp-general 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. # # Wasp-general 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 wasp-general. If not, see <http://www.gnu.org/licenses/>. # TODO: document the code # TODO: write tests for the code # noinspection PyUnresolvedReferences from wasp_general.version import __author__, __version__, __credits__, __license__, __copyright__, __email__ # noinspection PyUnresolvedReferences from wasp_general.version import __status__ from wasp_general.verify import verify_type from wasp_general.command.command import WCommand from wasp_general.command.result import WPlainCommandResult from wasp_general.cli.curses import WCursesConsole class WExitCommand(WCommand): @verify_type(console=WCursesConsole) def __init__(self, console): WCommand.__init__(self) self.__console = console def console(self): return self.__console @verify_type('paranoid', command_tokens=str) def match(self, *command_tokens, **command_env): return command_tokens == ('exit',) or command_tokens == ('quit',) @verify_type('paranoid', command_tokens=str) def _exec(self, *command_tokens, **command_env): self.__console.stop() return WPlainCommandResult('Exiting...') class WEmptyCommand(WCommand): @verify_type('paranoid', command_tokens=str) def match(self, *command_tokens, **command_env): return len(command_tokens) == 0 @verify_type('paranoid', command_tokens=str) def _exec(self, *command_tokens, **command_env): return WPlainCommandResult('')
lgpl-3.0
1,186,058,328,410,375,000
32.78125
108
0.740981
false
3.515447
false
false
false
srcLurker/home-assistant
tests/test_core.py
1
23404
"""Test to verify that Home Assistant core works.""" # pylint: disable=protected-access import asyncio import unittest from unittest.mock import patch, MagicMock from datetime import datetime, timedelta import pytz import homeassistant.core as ha from homeassistant.exceptions import InvalidEntityFormatError from homeassistant.util.async import ( run_callback_threadsafe, run_coroutine_threadsafe) import homeassistant.util.dt as dt_util from homeassistant.util.unit_system import (METRIC_SYSTEM) from homeassistant.const import ( __version__, EVENT_STATE_CHANGED, ATTR_FRIENDLY_NAME, CONF_UNIT_SYSTEM) from tests.common import get_test_home_assistant PST = pytz.timezone('America/Los_Angeles') def test_split_entity_id(): """Test split_entity_id.""" assert ha.split_entity_id('domain.object_id') == ['domain', 'object_id'] def test_async_add_job_schedule_callback(): """Test that we schedule coroutines and add jobs to the job pool.""" hass = MagicMock() job = MagicMock() ha.HomeAssistant.async_add_job(hass, ha.callback(job)) assert len(hass.loop.call_soon.mock_calls) == 1 assert len(hass.loop.create_task.mock_calls) == 0 assert len(hass.add_job.mock_calls) == 0 @patch('asyncio.iscoroutinefunction', return_value=True) def test_async_add_job_schedule_coroutinefunction(mock_iscoro): """Test that we schedule coroutines and add jobs to the job pool.""" hass = MagicMock() job = MagicMock() ha.HomeAssistant.async_add_job(hass, job) assert len(hass.loop.call_soon.mock_calls) == 0 assert len(hass.loop.create_task.mock_calls) == 1 assert len(hass.add_job.mock_calls) == 0 @patch('asyncio.iscoroutinefunction', return_value=False) def test_async_add_job_add_threaded_job_to_pool(mock_iscoro): """Test that we schedule coroutines and add jobs to the job pool.""" hass = MagicMock() job = MagicMock() ha.HomeAssistant.async_add_job(hass, job) assert len(hass.loop.call_soon.mock_calls) == 0 assert len(hass.loop.create_task.mock_calls) == 0 assert len(hass.loop.run_in_executor.mock_calls) == 1 def test_async_run_job_calls_callback(): """Test that the callback annotation is respected.""" hass = MagicMock() calls = [] def job(): calls.append(1) ha.HomeAssistant.async_run_job(hass, ha.callback(job)) assert len(calls) == 1 assert len(hass.async_add_job.mock_calls) == 0 def test_async_run_job_delegates_non_async(): """Test that the callback annotation is respected.""" hass = MagicMock() calls = [] def job(): calls.append(1) ha.HomeAssistant.async_run_job(hass, job) assert len(calls) == 0 assert len(hass.async_add_job.mock_calls) == 1 class TestHomeAssistant(unittest.TestCase): """Test the Home Assistant core classes.""" # pylint: disable=invalid-name def setUp(self): """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() # pylint: disable=invalid-name def tearDown(self): """Stop everything that was started.""" self.hass.stop() # This test hangs on `loop.add_signal_handler` # def test_start_and_sigterm(self): # """Start the test.""" # calls = [] # self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, # lambda event: calls.append(1)) # self.hass.start() # self.assertEqual(1, len(calls)) # self.hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, # lambda event: calls.append(1)) # os.kill(os.getpid(), signal.SIGTERM) # self.hass.block_till_done() # self.assertEqual(1, len(calls)) def test_pending_sheduler(self): """Add a coro to pending tasks.""" call_count = [] @asyncio.coroutine def test_coro(): """Test Coro.""" call_count.append('call') for i in range(50): self.hass.add_job(test_coro()) run_coroutine_threadsafe( asyncio.wait(self.hass._pending_tasks, loop=self.hass.loop), loop=self.hass.loop ).result() with patch.object(self.hass.loop, 'call_later') as mock_later: run_callback_threadsafe( self.hass.loop, self.hass._async_tasks_cleanup).result() assert mock_later.called assert len(self.hass._pending_tasks) == 0 assert len(call_count) == 50 def test_async_add_job_pending_tasks_coro(self): """Add a coro to pending tasks.""" call_count = [] @asyncio.coroutine def test_coro(): """Test Coro.""" call_count.append('call') for i in range(50): self.hass.add_job(test_coro()) assert len(self.hass._pending_tasks) == 50 self.hass.block_till_done() assert len(call_count) == 50 def test_async_add_job_pending_tasks_executor(self): """Run a executor in pending tasks.""" call_count = [] def test_executor(): """Test executor.""" call_count.append('call') for i in range(40): self.hass.add_job(test_executor) assert len(self.hass._pending_tasks) == 40 self.hass.block_till_done() assert len(call_count) == 40 def test_async_add_job_pending_tasks_callback(self): """Run a callback in pending tasks.""" call_count = [] @ha.callback def test_callback(): """Test callback.""" call_count.append('call') for i in range(40): self.hass.add_job(test_callback) assert len(self.hass._pending_tasks) == 0 self.hass.block_till_done() assert len(call_count) == 40 class TestEvent(unittest.TestCase): """A Test Event class.""" def test_eq(self): """Test events.""" now = dt_util.utcnow() data = {'some': 'attr'} event1, event2 = [ ha.Event('some_type', data, time_fired=now) for _ in range(2) ] self.assertEqual(event1, event2) def test_repr(self): """Test that repr method works.""" self.assertEqual( "<Event TestEvent[L]>", str(ha.Event("TestEvent"))) self.assertEqual( "<Event TestEvent[R]: beer=nice>", str(ha.Event("TestEvent", {"beer": "nice"}, ha.EventOrigin.remote))) def test_as_dict(self): """Test as dictionary.""" event_type = 'some_type' now = dt_util.utcnow() data = {'some': 'attr'} event = ha.Event(event_type, data, ha.EventOrigin.local, now) expected = { 'event_type': event_type, 'data': data, 'origin': 'LOCAL', 'time_fired': now, } self.assertEqual(expected, event.as_dict()) class TestEventBus(unittest.TestCase): """Test EventBus methods.""" # pylint: disable=invalid-name def setUp(self): """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.bus = self.hass.bus # pylint: disable=invalid-name def tearDown(self): """Stop down stuff we started.""" self.hass.stop() def test_add_remove_listener(self): """Test remove_listener method.""" self.hass.allow_pool = False old_count = len(self.bus.listeners) def listener(_): pass unsub = self.bus.listen('test', listener) self.assertEqual(old_count + 1, len(self.bus.listeners)) # Remove listener unsub() self.assertEqual(old_count, len(self.bus.listeners)) # Should do nothing now unsub() def test_unsubscribe_listener(self): """Test unsubscribe listener from returned function.""" calls = [] @ha.callback def listener(event): """Mock listener.""" calls.append(event) unsub = self.bus.listen('test', listener) self.bus.fire('test') self.hass.block_till_done() assert len(calls) == 1 unsub() self.bus.fire('event') self.hass.block_till_done() assert len(calls) == 1 def test_listen_once_event_with_callback(self): """Test listen_once_event method.""" runs = [] @ha.callback def event_handler(event): runs.append(event) self.bus.listen_once('test_event', event_handler) self.bus.fire('test_event') # Second time it should not increase runs self.bus.fire('test_event') self.hass.block_till_done() self.assertEqual(1, len(runs)) def test_listen_once_event_with_coroutine(self): """Test listen_once_event method.""" runs = [] @asyncio.coroutine def event_handler(event): runs.append(event) self.bus.listen_once('test_event', event_handler) self.bus.fire('test_event') # Second time it should not increase runs self.bus.fire('test_event') self.hass.block_till_done() self.assertEqual(1, len(runs)) def test_listen_once_event_with_thread(self): """Test listen_once_event method.""" runs = [] def event_handler(event): runs.append(event) self.bus.listen_once('test_event', event_handler) self.bus.fire('test_event') # Second time it should not increase runs self.bus.fire('test_event') self.hass.block_till_done() self.assertEqual(1, len(runs)) def test_thread_event_listener(self): """Test a event listener listeners.""" thread_calls = [] def thread_listener(event): thread_calls.append(event) self.bus.listen('test_thread', thread_listener) self.bus.fire('test_thread') self.hass.block_till_done() assert len(thread_calls) == 1 def test_callback_event_listener(self): """Test a event listener listeners.""" callback_calls = [] @ha.callback def callback_listener(event): callback_calls.append(event) self.bus.listen('test_callback', callback_listener) self.bus.fire('test_callback') self.hass.block_till_done() assert len(callback_calls) == 1 def test_coroutine_event_listener(self): """Test a event listener listeners.""" coroutine_calls = [] @asyncio.coroutine def coroutine_listener(event): coroutine_calls.append(event) self.bus.listen('test_coroutine', coroutine_listener) self.bus.fire('test_coroutine') self.hass.block_till_done() assert len(coroutine_calls) == 1 class TestState(unittest.TestCase): """Test State methods.""" def test_init(self): """Test state.init.""" self.assertRaises( InvalidEntityFormatError, ha.State, 'invalid_entity_format', 'test_state') def test_domain(self): """Test domain.""" state = ha.State('some_domain.hello', 'world') self.assertEqual('some_domain', state.domain) def test_object_id(self): """Test object ID.""" state = ha.State('domain.hello', 'world') self.assertEqual('hello', state.object_id) def test_name_if_no_friendly_name_attr(self): """Test if there is no friendly name.""" state = ha.State('domain.hello_world', 'world') self.assertEqual('hello world', state.name) def test_name_if_friendly_name_attr(self): """Test if there is a friendly name.""" name = 'Some Unique Name' state = ha.State('domain.hello_world', 'world', {ATTR_FRIENDLY_NAME: name}) self.assertEqual(name, state.name) def test_dict_conversion(self): """Test conversion of dict.""" state = ha.State('domain.hello', 'world', {'some': 'attr'}) self.assertEqual(state, ha.State.from_dict(state.as_dict())) def test_dict_conversion_with_wrong_data(self): """Test conversion with wrong data.""" self.assertIsNone(ha.State.from_dict(None)) self.assertIsNone(ha.State.from_dict({'state': 'yes'})) self.assertIsNone(ha.State.from_dict({'entity_id': 'yes'})) def test_repr(self): """Test state.repr.""" self.assertEqual("<state happy.happy=on @ 1984-12-08T12:00:00+00:00>", str(ha.State( "happy.happy", "on", last_changed=datetime(1984, 12, 8, 12, 0, 0)))) self.assertEqual( "<state happy.happy=on; brightness=144 @ " "1984-12-08T12:00:00+00:00>", str(ha.State("happy.happy", "on", {"brightness": 144}, datetime(1984, 12, 8, 12, 0, 0)))) class TestStateMachine(unittest.TestCase): """Test State machine methods.""" # pylint: disable=invalid-name def setUp(self): """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.states = self.hass.states self.states.set("light.Bowl", "on") self.states.set("switch.AC", "off") # pylint: disable=invalid-name def tearDown(self): """Stop down stuff we started.""" self.hass.stop() def test_is_state(self): """Test is_state method.""" self.assertTrue(self.states.is_state('light.Bowl', 'on')) self.assertFalse(self.states.is_state('light.Bowl', 'off')) self.assertFalse(self.states.is_state('light.Non_existing', 'on')) def test_is_state_attr(self): """Test is_state_attr method.""" self.states.set("light.Bowl", "on", {"brightness": 100}) self.assertTrue( self.states.is_state_attr('light.Bowl', 'brightness', 100)) self.assertFalse( self.states.is_state_attr('light.Bowl', 'friendly_name', 200)) self.assertFalse( self.states.is_state_attr('light.Bowl', 'friendly_name', 'Bowl')) self.assertFalse( self.states.is_state_attr('light.Non_existing', 'brightness', 100)) def test_entity_ids(self): """Test get_entity_ids method.""" ent_ids = self.states.entity_ids() self.assertEqual(2, len(ent_ids)) self.assertTrue('light.bowl' in ent_ids) self.assertTrue('switch.ac' in ent_ids) ent_ids = self.states.entity_ids('light') self.assertEqual(1, len(ent_ids)) self.assertTrue('light.bowl' in ent_ids) def test_all(self): """Test everything.""" states = sorted(state.entity_id for state in self.states.all()) self.assertEqual(['light.bowl', 'switch.ac'], states) def test_remove(self): """Test remove method.""" events = [] @ha.callback def callback(event): events.append(event) self.hass.bus.listen(EVENT_STATE_CHANGED, callback) self.assertIn('light.bowl', self.states.entity_ids()) self.assertTrue(self.states.remove('light.bowl')) self.hass.block_till_done() self.assertNotIn('light.bowl', self.states.entity_ids()) self.assertEqual(1, len(events)) self.assertEqual('light.bowl', events[0].data.get('entity_id')) self.assertIsNotNone(events[0].data.get('old_state')) self.assertEqual('light.bowl', events[0].data['old_state'].entity_id) self.assertIsNone(events[0].data.get('new_state')) # If it does not exist, we should get False self.assertFalse(self.states.remove('light.Bowl')) self.hass.block_till_done() self.assertEqual(1, len(events)) def test_case_insensitivty(self): """Test insensitivty.""" runs = [] @ha.callback def callback(event): runs.append(event) self.hass.bus.listen(EVENT_STATE_CHANGED, callback) self.states.set('light.BOWL', 'off') self.hass.block_till_done() self.assertTrue(self.states.is_state('light.bowl', 'off')) self.assertEqual(1, len(runs)) def test_last_changed_not_updated_on_same_state(self): """Test to not update the existing, same state.""" state = self.states.get('light.Bowl') future = dt_util.utcnow() + timedelta(hours=10) with patch('homeassistant.util.dt.utcnow', return_value=future): self.states.set("light.Bowl", "on", {'attr': 'triggers_change'}) self.hass.block_till_done() state2 = self.states.get('light.Bowl') assert state2 is not None assert state.last_changed == state2.last_changed def test_force_update(self): """Test force update option.""" events = [] @ha.callback def callback(event): events.append(event) self.hass.bus.listen(EVENT_STATE_CHANGED, callback) self.states.set('light.bowl', 'on') self.hass.block_till_done() self.assertEqual(0, len(events)) self.states.set('light.bowl', 'on', None, True) self.hass.block_till_done() self.assertEqual(1, len(events)) class TestServiceCall(unittest.TestCase): """Test ServiceCall class.""" def test_repr(self): """Test repr method.""" self.assertEqual( "<ServiceCall homeassistant.start>", str(ha.ServiceCall('homeassistant', 'start'))) self.assertEqual( "<ServiceCall homeassistant.start: fast=yes>", str(ha.ServiceCall('homeassistant', 'start', {"fast": "yes"}))) class TestServiceRegistry(unittest.TestCase): """Test ServicerRegistry methods.""" # pylint: disable=invalid-name def setUp(self): """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.services = self.hass.services @ha.callback def mock_service(call): pass self.services.register("Test_Domain", "TEST_SERVICE", mock_service) # pylint: disable=invalid-name def tearDown(self): """Stop down stuff we started.""" self.hass.stop() def test_has_service(self): """Test has_service method.""" self.assertTrue( self.services.has_service("tesT_domaiN", "tesT_servicE")) self.assertFalse( self.services.has_service("test_domain", "non_existing")) self.assertFalse( self.services.has_service("non_existing", "test_service")) def test_services(self): """Test services.""" expected = { 'test_domain': {'test_service': {'description': '', 'fields': {}}} } self.assertEqual(expected, self.services.services) def test_call_with_blocking_done_in_time(self): """Test call with blocking.""" calls = [] @ha.callback def service_handler(call): """Service handler.""" calls.append(call) self.services.register("test_domain", "register_calls", service_handler) self.assertTrue( self.services.call('test_domain', 'REGISTER_CALLS', blocking=True)) self.assertEqual(1, len(calls)) def test_call_non_existing_with_blocking(self): """Test non-existing with blocking.""" prior = ha.SERVICE_CALL_LIMIT try: ha.SERVICE_CALL_LIMIT = 0.01 assert not self.services.call('test_domain', 'i_do_not_exist', blocking=True) finally: ha.SERVICE_CALL_LIMIT = prior def test_async_service(self): """Test registering and calling an async service.""" calls = [] @asyncio.coroutine def service_handler(call): """Service handler coroutine.""" calls.append(call) self.services.register('test_domain', 'register_calls', service_handler) self.assertTrue( self.services.call('test_domain', 'REGISTER_CALLS', blocking=True)) self.hass.block_till_done() self.assertEqual(1, len(calls)) def test_callback_service(self): """Test registering and calling an async service.""" calls = [] @ha.callback def service_handler(call): """Service handler coroutine.""" calls.append(call) self.services.register('test_domain', 'register_calls', service_handler) self.assertTrue( self.services.call('test_domain', 'REGISTER_CALLS', blocking=True)) self.hass.block_till_done() self.assertEqual(1, len(calls)) class TestConfig(unittest.TestCase): """Test configuration methods.""" # pylint: disable=invalid-name def setUp(self): """Setup things to be run when tests are started.""" self.config = ha.Config() self.assertIsNone(self.config.config_dir) def test_path_with_file(self): """Test get_config_path method.""" self.config.config_dir = '/tmp/ha-config' self.assertEqual("/tmp/ha-config/test.conf", self.config.path("test.conf")) def test_path_with_dir_and_file(self): """Test get_config_path method.""" self.config.config_dir = '/tmp/ha-config' self.assertEqual("/tmp/ha-config/dir/test.conf", self.config.path("dir", "test.conf")) def test_as_dict(self): """Test as dict.""" self.config.config_dir = '/tmp/ha-config' expected = { 'latitude': None, 'longitude': None, CONF_UNIT_SYSTEM: METRIC_SYSTEM.as_dict(), 'location_name': None, 'time_zone': 'UTC', 'components': [], 'config_dir': '/tmp/ha-config', 'version': __version__, } self.assertEqual(expected, self.config.as_dict()) class TestAsyncCreateTimer(object): """Test create timer.""" @patch('homeassistant.core.asyncio.Event') @patch('homeassistant.core.dt_util.utcnow') def test_create_timer(self, mock_utcnow, mock_event, event_loop): """Test create timer fires correctly.""" hass = MagicMock() now = mock_utcnow() event = mock_event() now.second = 1 mock_utcnow.reset_mock() ha._async_create_timer(hass) assert len(hass.bus.async_listen_once.mock_calls) == 2 start_timer = hass.bus.async_listen_once.mock_calls[1][1][1] event_loop.run_until_complete(start_timer(None)) assert hass.loop.create_task.called timer = hass.loop.create_task.mock_calls[0][1][0] event.is_set.side_effect = False, False, True event_loop.run_until_complete(timer) assert len(mock_utcnow.mock_calls) == 1 assert hass.loop.call_soon.called event_type, event_data = hass.loop.call_soon.mock_calls[0][1][1:] assert ha.EVENT_TIME_CHANGED == event_type assert {ha.ATTR_NOW: now} == event_data stop_timer = hass.bus.async_listen_once.mock_calls[0][1][1] stop_timer(None) assert event.set.called
mit
-2,077,596,494,842,952,200
30.499327
79
0.587079
false
3.802437
true
false
false
oshepherd/eforge
eforge/update/twitter/views.py
1
3164
# -*- coding: utf-8 -*- # EForge project management system, Copyright © 2010, Element43 # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # from eforge.models import Project from django.shortcuts import redirect, render_to_response from django.template import RequestContext from django.core.urlresolvers import reverse from django.conf import settings from django.contrib.sites.models import Site from eforge.decorators import project_page, has_project_perm from eforge.update.twitter.models import Token from twitter import Twitter, OAuth, TwitterHTTPError import urlparse consumer_key = settings.TWITTER_CONSUMER_KEY consumer_secret = settings.TWITTER_CONSUMER_SECRET authorize_url = 'https://api.twitter.com/oauth/authorize?oauth_token=%s' def abs_reverse(*args, **kwargs): domain = "http://%s" % Site.objects.get_current().domain return urlparse.urljoin(domain, reverse(*args, **kwargs)) @project_page @has_project_perm('eforge.manage') def setup(request, project): twitter = Twitter( auth=OAuth('', '', consumer_key, consumer_secret), format='', secure=True,) tokens = urlparse.parse_qs( twitter.oauth.request_token( oauth_callback=abs_reverse('twitter-callback', args=[project.slug]) )) print tokens request.session['oauth_secret'] = tokens['oauth_token_secret'][0] return redirect(authorize_url % tokens['oauth_token'][0]) @project_page @has_project_perm('eforge.manage') def callback(request, project): oauth_token = request.GET['oauth_token'] oauth_verifier = request.GET['oauth_verifier'] oauth_secret = request.session['oauth_secret'] print request.session.items() twitter = Twitter( auth=OAuth(oauth_token, oauth_secret, consumer_key, consumer_secret), format='', secure=True,) try: tokens = urlparse.parse_qs( twitter.oauth.access_token(oauth_verifier=oauth_verifier)) except TwitterHTTPError, e: print e raise try: token = Token.objects.get(project=project) except Token.DoesNotExist: token = Token(project=project) token.token = tokens['oauth_token'][0] token.token_secret = tokens['oauth_token_secret'][0] token.user = tokens['screen_name'][0] token.save() return render_to_response('twitter/done.html', { 'name': tokens['screen_name'][0] }, context_instance=RequestContext(request))
isc
3,334,641,479,672,096,000
35.790698
79
0.702498
false
4.024173
false
false
false
KhronosGroup/COLLADA-CTS
Core/Gui/Dialog/FBlessedViewerDialog.py
1
11440
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials, and to permit persons to whom the Materials are 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 Materials. # THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. import wx import os import os.path import shutil import Core.Common.FUtils as FUtils from Core.Common.FConstants import * from Core.Gui.Dialog.FImageSizer import * class FBlessedViewerDialog(wx.Dialog): def __init__(self, parent, dataSetPath): wx.Dialog.__init__(self, parent, wx.ID_ANY, "Blessed Viewer", size = wx.Size(540, 450), style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) sizer = wx.BoxSizer() self.SetSizer(sizer) window = wx.SplitterWindow(self) window.SetSashGravity(0.5) window.SetMinimumPaneSize(20) images = FBlessedImagesPanel(window, dataSetPath) names = FBlessedNamesPanel(window, dataSetPath, images) window.SplitVertically(names, images, 200) sizer.Add(window, 1, wx.EXPAND | wx.ALL, 0) class FBlessedNamesPanel(wx.Panel): def __init__(self, parent, dataSetPath, imagesPanel): wx.Panel.__init__(self, parent, style = wx.BORDER_SUNKEN) self.__dataSetPath = dataSetPath self.__imagesPanel = imagesPanel self.__imagesPanel.SetChangeCallback(self.__Update) self.__defaultBlessedImageFilename = "" sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) # UI: Add a label for the default blessed image filename. defaultBlessedLabel = wx.StaticText(self, wx.ID_ANY, " Default Blessed") sizer.Add(defaultBlessedLabel, 0, wx.ALIGN_LEFT | wx.ALL, 2) # UI: Add a text box with the default blessed image filename at the top. self.__defaultImageTextBox = wx.TextCtrl(self, wx.ID_ANY, style = wx.TE_READONLY) sizer.Add(self.__defaultImageTextBox, 0, wx.EXPAND | wx.ALL, 2) sizer.Add((1, 5), 0) # UI: Add a label for the blessed images list box. imageLabel = wx.StaticText(self, wx.ID_ANY, " Blessed Images/Animations") sizer.Add(imageLabel, 0, wx.ALIGN_LEFT | wx.ALL, 2) # UI: Add a list box containing all the bless image filenames. self.__imageListBox = wx.ListBox(self, style = wx.LB_SINGLE | wx.LB_HSCROLL) self.Bind(wx.EVT_LISTBOX, self.__ImageOnClick, self.__imageListBox) sizer.Add(self.__imageListBox, 1, wx.EXPAND | wx.ALL, 2) self.__Update(False) # returns [(imageName, imagePath),] def __GetImageList(self): blessedImages = [] blessedDir = os.path.join(self.__dataSetPath, BLESSED_DIR) if (os.path.isdir(blessedDir)): for ext in os.listdir(blessedDir): if (ext[0] == "."): continue # mostly for .svn folders if (ext == BLESSED_EXECUTIONS): continue extBlessedDir = os.path.join(blessedDir, ext) if (os.path.isdir(extBlessedDir)): for filename in os.listdir(extBlessedDir): fullFilename = os.path.join(extBlessedDir, filename) if (os.path.isfile(fullFilename)): blessedImages.append((filename, fullFilename)) return blessedImages # returns [(animationName, [imagePath1,]), ] def __GetAnimationList(self): blessedAnimations = [] blessedDir = os.path.join(self.__dataSetPath, BLESSED_DIR, BLESSED_ANIMATIONS) if (os.path.isdir(blessedDir)): for directory in os.listdir(blessedDir): if (directory[0] == "."): continue # mostly for .svn folders fullDirectory = os.path.join(blessedDir, directory) storedFilenames = [] for filename in os.listdir(fullDirectory): fullFilename = os.path.join(fullDirectory, filename) if (os.path.isfile(fullFilename)): storedFilenames.append(fullFilename) storedFilenames.sort() blessedAnimations.append((directory, storedFilenames)) return blessedAnimations def __Update(self, onlyDefaultBless): # Update the default blessed image filename. defaultContainerFilename = os.path.join(self.__dataSetPath, BLESSED_DIR, BLESSED_DEFAULT_FILE) if (os.path.isfile(defaultContainerFilename)): blessFile = open(defaultContainerFilename, "rb") filename = blessFile.readline().strip() blessFile.close() if (filename.find(BLESSED_ANIMATIONS) == -1): # Image? filename = os.path.basename(filename) else: filename = os.path.basename(os.path.dirname(filename)) self.__defaultImageTextBox.SetLabel(filename) else: self.__defaultImageTextBox.SetLabel("") if onlyDefaultBless: return # Update the image filenames list box. self.__imageListBox.Clear() for name, image in self.__GetImageList(): self.__imageListBox.Append("[I] " + name, [image]) for name, images in self.__GetAnimationList(): self.__imageListBox.Append("[A] " + name, images) # Restart the images panel if (self.__imageListBox.GetCount() > 0): self.__imageListBox.Select(0) self.__imagesPanel.SetImage(self.__imageListBox.GetClientData(0)) else: self.__imagesPanel.Clear() def __ImageOnClick(self, e): e.Skip() selection = self.__imageListBox.GetSelection() if (selection == -1): return self.__imagesPanel.SetImage(self.__imageListBox.GetClientData(selection)) class FBlessedImagesPanel(wx.Panel): def __init__(self, parent, dataSetPath): wx.Panel.__init__(self, parent, style = wx.BORDER_SUNKEN) self.__filenames = None self.__callback = None self.__animationSizer = None self.__dataSetPath = dataSetPath sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) self.Clear() sizer.Layout() def Clear(self): sizer = self.GetSizer() # for some reason Clear() does not destroy the static box if (self.__animationSizer != None): sizer.Detach(self.__animationSizer) self.__animationSizer.DeleteWindows() self.__animationSizer.GetStaticBox().Destroy() self.__animationSizer = None self.GetSizer().Clear(True) self.GetSizer().Layout() def SetImage(self, filenames): sizer = self.GetSizer() self.Clear() self.__filenames = filenames self.__animationSizer = FImageSizer(self, wx.EmptyString, filenames, None) sizer.Add(self.__animationSizer, 0, wx.ALIGN_CENTER | wx.ALL, 2) buttonSizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(buttonSizer, 0, wx.ALIGN_CENTER | wx.ALL, 2) button = wx.Button(self, wx.ID_ANY, "Delete") buttonSizer.Add(button, 0, wx.ALIGN_CENTER | wx.ALL, 2) self.Bind(wx.EVT_BUTTON, self.__OnUnbless, button) button = wx.Button(self, wx.ID_ANY, "Default Bless") buttonSizer.Add(button, 0, wx.ALIGN_CENTER | wx.ALL, 2) self.Bind(wx.EVT_BUTTON, self.__OnMakeDefault, button) buttonSizer.Layout() sizer.Layout() def SetChangeCallback(self, callback): self.__callback = callback def __OnUnbless(self, e): e.Skip() # Delete the blessed image files. for filename in self.__filenames: os.remove(filename) foundFile = False for element in os.listdir(os.path.dirname(filename)): if (element != ".svn"): foundFile = True break if (not foundFile): deleteDirectory = os.path.abspath(os.path.dirname(filename)) try: shutil.rmtree(deleteDirectory) except OSError, e: FUtils.ShowWarning(self, "Unable to delete " + deleteDirectory + ".\n" + "Error:\n" + str(e) + "\n Please delete directory manually.") # Verify whether this was the blessed images. In that case: clear the file. blessedDir = os.path.join(self.__dataSetPath, BLESSED_DIR) defaultContainerFilename = os.path.join(blessedDir, BLESSED_DEFAULT_FILE) if (os.path.isfile(defaultContainerFilename)): blessFile = open(defaultContainerFilename, "rb") defaultBlessedImageFilename = blessFile.readline().strip() blessFile.close() # Need to compare absolute filenames. if (len(defaultBlessedImageFilename) > 0): defaultBlessedImageFilename = os.path.join(blessedDir, defaultBlessedImageFilename) defaultBlessedImageFilename = os.path.abspath(defaultBlessedImageFilename) isDefault = False for filename in self.__filenames: filename = os.path.abspath(filename) if (filename == defaultBlessedImageFilename): isDefault = True break if (isDefault): blessFile = open(defaultContainerFilename, "w") blessFile.close() if (self.__callback != None): self.__callback(False) def __OnMakeDefault(self, e): e.Skip() # Rewrite the default blessed file to include these local filenames. blessedDir = os.path.join(self.__dataSetPath, BLESSED_DIR) defaultContainerFilename = os.path.join(blessedDir, BLESSED_DEFAULT_FILE) blessFile = open(defaultContainerFilename, "w") if (self.__filenames != None) and (len(self.__filenames) > 0): for filename in self.__filenames: relativeFilename = FUtils.GetRelativePath(filename, blessedDir) blessFile.write(relativeFilename) blessFile.write("\n") else: pass # Intentionally leave empty. Can we actually get here in the UI? blessFile.close() if (self.__callback != None): self.__callback(True)
mit
8,617,399,534,047,996,000
43.169884
466
0.603409
false
4.094488
false
false
false
dimonaks/siman
siman/impurity.py
1
35842
from __future__ import division, unicode_literals, absolute_import import ctypes from tabulate import tabulate #from ctypes import * from ctypes import cdll from ctypes import c_float, byref import numpy as np import traceback, os, sys, datetime, glob, copy from siman import header from siman.header import print_and_log, printlog, geo_folder, runBash from siman.classes import CalculationVasp, Structure from siman.set_functions import InputSet from siman.functions import return_atoms_to_cell, element_name_inv from siman.inout import write_xyz from siman.geo import local_surrounding, local_surrounding2, xcart2xred, xred2xcart lib = cdll.LoadLibrary(os.path.dirname(__file__)+'/libfindpores.so') def create_c_array(pylist, ctype): if ctype == float: c_array = (ctypes.c_float * len(pylist))(*pylist) return c_array def find_pores(st_in, r_matrix=1.4, r_impurity = 0.6, step_dec = 0.05, fine = 0.3, prec = 0.1, calctype = 'central', gbpos = 0, find_close_to = (), check_pore_vol = 0): """ st_in - input Structure() object r_impurity (A)- all pores smaller than this radius will be found r_matrix (A) - radius of matrix atoms disregarding to their type step_dec - scanning step of the cell in Angstroms fine - allows to change density of local points; local_step = step_dec/fine prec - precicion of pore center determination check_pore_vol - allows to estimate volume of pores; has problems for big cells 'find_close_to' - works in the cases of gb and grain_vol; allows to ignore all and find pore close to provided three reduced coordinates return - instance of Structure() class with coordinates of pores. Number and type of included pores depend on the argument of 'calctype'. """ xred = st_in.xred natom = len(xred) rprimd = st_in.rprimd name = st_in.name #print xred """Additional values""" # check_pore_vol = 1 #if calctype in ("pore_vol","gb","grain_vol","all_local" ): check_pore_vol = 1 #something wrong with this function, especially for big cells """----Conversions of types for C++""" r1 = create_c_array(rprimd[0], float) r2 = create_c_array(rprimd[1], float) r3 = create_c_array(rprimd[2], float) xred1 = (c_float * len(xred))(*[x[0] for x in xred]) xred2 = (c_float * len(xred))(*[x[1] for x in xred]) xred3 = (c_float * len(xred))(*[x[2] for x in xred]) max_npores = 10000; ntot = ctypes.c_int32(); npores = ctypes.c_int32() l_pxred1 = (c_float * max_npores)(0) #make static arrays fol local points l_pxred2 = (c_float * max_npores)(0) l_pxred3 = (c_float * max_npores)(0) l_npores = (ctypes.c_int32 * max_npores)(0) pxred1 = (c_float * max_npores)(0) #make static arrays natoms + npore pxred2 = (c_float * max_npores)(0) pxred3 = (c_float * max_npores)(0) """----Run C++ function""" print_and_log("Starting C++ function lib.findpores()...\n") # print(r_matrix, r_impurity, step_dec, fine, prec) lib.findpores ( check_pore_vol, \ max_npores, \ byref(ntot), l_pxred1, l_pxred2, l_pxred3, l_npores, \ byref(npores), pxred1, pxred2, pxred3, \ natom, xred1, xred2, xred3, \ c_float(r_matrix), c_float(r_impurity), c_float(step_dec), c_float(fine), c_float(prec), \ r1, r2, r3 ) print_and_log( "ntot is ", ntot.value) print_and_log( "l_npores[0] is ",l_npores[0]) v = np.zeros((3)) l_pxred = [] shift1 = 0; shift2 = 0 for i_por in range(npores.value): l_pxred.append( [] ) shift2+=l_npores[i_por] for i in range(shift1, shift2): v[0] = l_pxred1[i]; v[1] = l_pxred2[i]; v[2] = l_pxred3[i] l_pxred[i_por].append( v.copy() ) shift1 = shift2 if shift2 != ntot.value: print_and_log( "Error! final shift2 not equal to ntot") #print l_pxred[0] pxred = [] # only coordinates of pores #print pxred1[natom] for i in range(npores.value): v[0] = pxred1[i+natom]; v[1]= pxred2[i+natom]; v[2] = pxred3[i+natom] #with shift, because first natom elements are coordinates of atoms pxred.append( v.copy() ) #print pxred """----End of C++; result is two lists: lpxred - local geometry of all pores, pxred - coordinates of all pores""" """ Analyse of pores """ # st_result = Structure() st_result = st_in.new() st_result.rprimd = rprimd targetp = np.array((0.,0.,0.)) if find_close_to: targetp = np.asarray(find_close_to) #targer point print_and_log( "Target point is ",targetp) a = step_dec/fine #the side of little cube formed by the mesh which is used to find spheres inside the pore. aaa = a*a*a #find most central pore if calctype == 'central': #return coordinates of the most central pore st_result.name = "central_pore_from "+name center = np.array((0.5,0.5,0.5))#center of cell d_min = 100 for x in pxred: d = np.linalg.norm(x - center) #print x, x-center, d if d < d_min and x[0] <= 0.5 and x[1] <= 0.5 and x[2] <= 0.5: d_min = d x_min = x print_and_log( "The closest pore to the center has coordinates",x_min) st_result.xred.append( x_min ) elif calctype == 'gb': #add impurity at gb st_result.name = "gb_pore_from "+name d_min = 100; #d2_min = 100 dt_min =100 i_min = 0; x_min = np.zeros((3)) for i, x in enumerate(pxred): #print "l_npores ",l_npores[i] d = abs(x[0] - gbpos/rprimd[0][0]) # #print x[0], d if find_close_to: closer = (np.linalg.norm(targetp - x) < dt_min) else: closer = ( d < d_min ) # and x[1]>0.3 and x[2]>0.3: if closer: x_pre = x_min i_pre = i_min d_min = d dt_min = np.linalg.norm(targetp - x) x_min = x i_min = i #find and add impurity in bulk #d2 = abs( x[0] - (gbpos/rprimd[0][0] - 0.25) ) #if d2 < d2_min: # d2_min = d2 # x2_min = x # i2_min = i #print "rprimd[0][0]", rprimd[0][0] print_and_log( "Position of boundary is ",gbpos/rprimd[0][0]) #x_min[0] = gbpos/rprimd[0][0] if find_close_to: print_and_log( "The closest pore to the target point is [ %.2f %.2f %.2f ]"%(x_min[0], x_min[1], x_min[2])) else: print_and_log( "The closest pore to the gb has coordinates",x_min) st_result.xred.append( x_min ) #st_result.xred.append( x_pre ) #Calculate volume of the pore using local balls: print_and_log( "The number of pore is ",i_min," ; It has ",l_npores[i_min], "local balls") print_and_log( "Volume of pore is ", l_npores[i_min] * a*a*a, " A^3") #st_result.xred.extend( l_pxred[i_min] ) #st_result.xred.extend( l_pxred[i_pre] ) #print "The closest pore to the center of bulk has coordinates",x2_min #st_result.xred.append( x2_min ) #Calculate volume of the pore using local balls: #print "The number of bulk pore is ",i2_min," ; It has ",l_npores[i2_min], "local balls" #print "Volume of pore is ", l_npores[i2_min] * a*a*a, " A^3"; #st_result.xred.extend( l_pxred[i2_min] ) elif calctype == 'grain_vol': #add impurity to volume of grain st_result.name = "grain_volume_pore_from "+name d2_min = 100 dt_min = 100 i_min = 0; x_min = np.zeros((3)) for i, x in enumerate(pxred): #find and add impurity to the bulk d2 = abs( x[0] - (gbpos/rprimd[0][0] - 0.25) ) if find_close_to: closer = (np.linalg.norm(targetp - x) < dt_min) else: closer = ( d2 < d2_min ) # and x[1]>0.3 and x[2]>0.3: if closer: dt_min = np.linalg.norm(targetp - x) d2_min = d2 x2_min = x i2_min = i if find_close_to: print_and_log( "The closest pore to the target point is [ %.2f %.2f %.2f ]"%(x2_min[0], x2_min[1], x2_min[2])) else: print_and_log( "The closest pore to the center of bulk has coordinates",x2_min) st_result.xred.append( x2_min ) #Calculate volume of the pore using local balls: print_and_log( "The number of bulk pore is ",i2_min," ; It has ",l_npores[i2_min], "local balls") print_and_log( "Volume of pore is ", l_npores[i2_min] * a*a*a, " A^3") st_result.xred.extend( l_pxred[i2_min] ) elif calctype == 'all_local': st_result.name = "all_local_points_from "+name v_max = 0 i_max = 0 for i in range(npores.value): v_pore = l_npores[i] * aaa print_and_log( "Volume of pore is ", l_npores[i] * aaa, " A^3") if v_pore > v_max: v_max = v_pore; i_max = i print_and_log( "Pore number ", i_max,"has the largest volume ", v_max," A^3") # st_result.xred = l_pxred[i_max] # here coordinates of all local points to show geometry of pore with largerst volume st_result.xred = [x for group in l_pxred for x in group ] # all pores elif calctype == 'all_pores': st_result.name = "all_local_pores_from "+name st_result.xred = pxred st_result.rprimd = rprimd st_result.xred2xcart() st_result.typat = [1 for x in st_result.xred] st_result.ntypat = 1 st_result.natom = len(st_result.typat) st_result.znucl = [200] st_ntypat = 1 return st_result def add_impurity(it_new, impurity_type = None, addtype = 'central', calc = [], r_pore = 0.5, it_to = '', ise_to = '', verlist_to = [], copy_geo_from = "", find_close_to = (),add_to_version = 0, write_geo = True, only_version = None, fine = 4, put_exactly_to = None, check_pore_vol = 0, replace_atom = None, override = False): """ Add impurities in pores. Input: it_new - name of new structure with impurity impurity_type - name of impurity from Mendeley table, for example 'C' addtype - type of adding: ['central',]; 'central' means that impurity will be placed as close to the geometrical center of cell as possible. it_to , ise_to , verlist_to - completed calculations in which impurity will be added if 'verlist_to' is empty, function will try to find geometry files in 'geo_folder + struct_des[it_to].sfolder' folder; even if 'it_to' is empty it will try to find files in 'geo_folder + struct_des[it_new].sfolder+'/from' ' folder. 'ise_to' also can be empty if 'copy_geo_from' is not empty, then programm copy all files from folder 'copy_geo_from' to folder 'geo_folder + struct_des[it_to].sfolder+"/"+it_to' or 'geo_folder + struct_des[it_new].sfolder+"/from" ' 'find_close_to' is tuple of three reduced coordinates of point close to which you want to find impurity. If empty - ignored; 'add_to_version' is integer number added to each 'verlist_to' number to produce ver_new. 'only_version' - if == [v,], then instertion will be provided only for v. If None insertion will be made in all found versions If you want to add impurity to relaxed structure ... 'fine' - integer number; allows to reduce number of small steps for defining center Possible addtype's: 'central' - add one atom to the pore which is most close to the center of the cell but with reduced coordinates less than 0.5 0.5 0.5 'all_pore' - add atoms in every found pore 'all_local' - add atoms to every local point which allows to visualise topology of pores. 'gb' - uses self.gbpos and places atom close to this value assuming that it will be at gb 'grain_vol' - uses self.gbpos and assuming that cell contains two gb and two equal grains, places atom close to the centre of grain; y and z can be arbiratry put_exactly_to - will add impurity to this point find_close_to - will try to find closest void and insert pore here. check_pore_vol - allows to estimate volume of pores; has problems for big cells replace_atom - if not None, than the specified atom is substituted Side effects: creates new geometry folder with input structures; """ struct_des = header.struct_des def test_adding_of_impurities(added, init, v): """ Can be used only inside add_impurity() Replicates the structure and find again pores """ global natoms_v1 if added == None: return if v == 1: #TEST natoms_v1 = len(added.init.xcart) # for test st_rep_after = added.init.replic( (1,2,1) ) rep = copy.deepcopy(init) rep.init = rep.init.replic( (1,2,1) ); #print rep rep = add(znucl, "", rep, write_geo = False) #print rep #print "xcart of replic after adding ", st_rep_after.xcart #print "xcart of adding to replic ", rep.init.xcart if len(st_rep_after.xcart) != len(rep.init.xcart): raise RuntimeError p = 0 #for x2 in st_rep_after.xcart: # print x2 for x in rep.init.xcart: a = any( ( np.around(x2, p) == np.around(x, p) ).all() for x2 in st_rep_after.xcart ) #b = any( ( np.ceil(x2, p) == np.ceil(x, p) ).all() for x2 in st_rep_after.xcart ) #c = any( ( np.floor(x2, p) == np.floor(x, p) ).all() for x2 in st_rep_after.xcart ) #print a, b, c #np.concatenate(a, b, c): if not a: print_and_log( "Error! Can't find ", np.around(x,3), "in replic ") raise RuntimeError #assert all([ all( np.around(v1, 8) == np.around(v2, 8) ) for (v1, v2) in zip(st_rep_after.xcart, rep.init.xcart) ]) print_and_log( "add_impurity: test succesfully done") if natoms_v1 != len(added.init.xcart): print_and_log("You have different number of pores in different versions\n"); raise RuntimeError return def add(znucl, xyzpath = "", new = None, write_geo = True, put_exactly_to = None): "if put_exactly_to is True, then atom just added and nothing are searched" if write_geo and os.path.exists(new.path["input_geo"]) and not override: print_and_log("add: File '"+new.path["input_geo"]+"' already exists; continue\n", imp = 'Y'); return new #new.init = return_atoms_to_cell(new.init) if replace_atom: #atom substitution if znucl not in new.init.znucl: new.init.znucl.append(znucl) new.init.ntypat+=1 new.init.typat[replace_atom] = new.init.ntypat else: ind = new.init.znucl.index(znucl) new.init.typat[replace_atom] = ind + 1 new.init.nznucl = [] for typ in range(1, new.init.ntypat+1): new.init.nznucl.append(new.init.typat.count(typ) ) else: new_before = copy.deepcopy(new) # new.init.xcart[-2][0]-=0.9 #was made once manually for c1gCOi10.1 # new.init.xcart[-2][2]+=0.2 # new.init.xred = xcart2xred(new.init.xcart, new.init.rprimd) write_xyz(new.init) #step = 0.042 step = 0.06 #r_pore = 0.56 #fine = 0.3 # for visualisation of pores #fine = 4 #controls small steps; the steps are smaller for larger numbers #r_pore = 0.54 prec = 0.004 # precision of center Angs if new.hex_a == None: r_mat = 1.48 -step else: r_mat = new.hex_a / 2 - step if put_exactly_to: pores_xred = [np.array(put_exactly_to),] print_and_log( 'Inmpurity just put in ', pores_xred, imp = 'Y') else: pores = find_pores(new.init, r_mat, r_pore, step, fine, prec, addtype, new.gbpos, find_close_to, check_pore_vol) #octahedral pores_xred = pores.xred npores = len(pores_xred) st = new.init #delete last oxygen; was made once manually for c1gCOi10.1 # st.natom-=1 # del st.xred[-1] # del st.typat[-1] st.natom += npores st.xred.extend( pores_xred ) if znucl in st.znucl: print_and_log( "znucl of added impurity is already in cell") ind = st.znucl.index(znucl) typat = ind+1 st.nznucl[ind]+=npores else: st.ntypat +=1 typat = st.ntypat st.znucl.append( znucl ) st.nznucl.append( npores ) for i in range( npores ): st.typat.append( typat ) st.xred2xcart() new.init = st #print "Add impurity: len(xred ", len(new.init.xred) #print "natom", new.init.natom #For automatisation of fit try: #new.build if new.build.nadded == None: new.build.nadded=npores else: new.build.nadded+=npores if new.build.listadded == [None]: new.build.listadded = range(new.natom - npores, new.natom) #list of atoms which were added else: new.build.listadded.extend( range(new.natom - npores, new.natom) ) #print "Warning!!! Information about added impurities rewritten" except AttributeError: pass #new.init.znucl = new.znucl #new.init.typat = new.typat #write_xyz(replic(new.init, (2,1,2)) , xyzpath) #test_adding_of_impurities(new, new_before, v) print_and_log("Impurity with Z="+str(znucl)+" has been added to the found pore in "+new.name+"\n\n") if write_geo: write_xyz(new.init , xyzpath) new.write_geometry("init",new.des, override = override) print_and_log( "\n") return new """0.Begin----------------------------------------------------------------------------""" znucl = element_name_inv(impurity_type) if impurity_type != 'octa' and impurity_type not in it_new: print_and_log("add_impurity: Your name 'it_new' is incorrect!\n\n") raise RuntimeError #del header.history[-2] # #hstring = ("add_impurity('%s', '%s', '%s', calc, %.3f, '%s', '%s', %s, '%s') #at %s" % # (it_new, impurity_type, addtype, r_pore, # it_to, ise_to, verlist_to, copy_geo_from, # datetime.date.today() ) ) hstring = ("%s #on %s"% (traceback.extract_stack(None, 2)[0][3], datetime.date.today() ) ) if hstring != header.history[-1]: header.history.append( hstring ) #geo_exists = """1. The case of insertion to existing calculations--------------------------------------------------""" if verlist_to: for v in verlist_to: if only_version and v not in only_version: continue # only_version = None works for all versions id = (it_to, ise_to, v) new = copy.deepcopy(calc[id]) new.init = new.end #replace init structure by the end structure new.version = v+add_to_version new.name = it_new#+'.'+id[1]+'.'+str(id[2]) new.des = 'Obtained from '+str(id)+' by adding '+impurity_type+' impurity ' path_new_geo = struct_des[it_new].sfolder+"/"+it_new+"/"+it_new+'.imp.'+addtype+'.'+str(new.version)+'.'+'geo' new.init.name = it_new+".init."+str(new.version) xyzpath = struct_des[it_new].sfolder+"/"+it_new new.path["input_geo"] = geo_folder+path_new_geo print_and_log("File '"+new.path["input_geo"] +"' with impurity will be created\n"); #new.init.name = 'test_before_add_impurity' new = add(znucl, xyzpath, new, write_geo, put_exactly_to = put_exactly_to) """2. The case of insertion to geo files------------------------------------------------------------""" else: """ Please rewrite using new functions """ print_and_log("You does not set 'id' of relaxed calculation. I try to find geometry files in "+it_new+" folder\n") if it_to: geo_path = geo_folder + struct_des[it_to].sfolder + "/" + it_to else: geo_path = geo_folder + struct_des[it_new].sfolder + "/" + it_new+'/from' if copy_geo_from: print_and_log("You asked to copy geo files from "+copy_geo_from+" to " +geo_path+ " folder\n") #if not os.path.exists(os.path.dirname(geo_path)): runBash( "mkdir -p "+geo_path ) runBash( "cp "+copy_geo_from+"/* "+geo_path ) if os.path.exists(geo_path): print_and_log("Folder '"+geo_path +"' was found. Trying to add impurity\n"); else: print_and_log("Error! Folder "+geo_path+" does not exist\n"); raise RuntimeError #geofilelist = glob.glob(geo_path+'/*.geo*') #Find input_geofile #geofilelist = runBash('find '+geo_path+' -name "*grainA*.geo*" ').splitlines() #geofilelist = runBash('find '+geo_path+' -name "*.geo*" ').splitlines() geofilelist = glob.glob(geo_path+'/*.geo*') print_and_log( "There are several files here already: ", geofilelist, imp = 'y' ) #print 'find '+geo_path+' -name "*.geo*" ',geofilelist #return for input_geofile in geofilelist: v = int( runBash("grep version "+str(input_geofile) ).split()[1] ) if only_version and v not in only_version: continue # only_version = None works for all versions new = CalculationVasp() new.version = v new.name = input_geofile new.read_geometry(input_geofile) init = copy.deepcopy(new) igl = input_geofile.split("/") #new.name = igl[-3]+'/'+igl[-3] #+input_geofile new.name = struct_des[it_new].sfolder+"/"+it_new+"/"+it_new print_and_log( "New path and part of name of file is ", new.name, imp = 'Y') #return new.des = 'Obtained from '+input_geofile+' by adding '+impurity_type+' impurity ' #new.init.xred = new.xred #new.init.rprimd = new.rprimd #print new.rprimd new.init.name = new.name+'.imp.'+addtype+'.'+str(new.version) #new.path["input_geo"] = geo_folder+it_new+"/"+new.end.name+'.'+'geo' new.path["input_geo"] = geo_folder+"/"+new.init.name+'.'+'geo' #new.init.name = 'test_before_add_impurity' new = add(znucl, "", new, write_geo, put_exactly_to = put_exactly_to) return new.path["input_geo"] #return for last version def insert_cluster(insertion, i_center, matrix, m_center): """ Take care of orientation; typat should be consistent Input: insertion - object of class Structure(), which is supposed to be inserted in matrix in such a way that i_center will be combined with m_center. matrix - object of class Structure(). i_center, m_center - numpy arrays (3) cartesian coordinates """ ins = copy.deepcopy(insertion) mat = copy.deepcopy(matrix) r = mat.rprimd hproj = [ (r[0][i]+r[1][i]+r[2][i]) * 0.5 for i in (0,1,2) ] #projection of vectors on three axis if 1: for i, x in enumerate(ins.xcart): ins.xcart[i] = x - i_center for i, x in enumerate(mat.xcart): mat.xcart[i] = x - m_center max_dis = 1 for i_x, ix in enumerate(ins.xcart): dv_min = max_dis print_and_log( "Insertion atom ",ix,) if 1: for j, mx in enumerate(mat.xcart): dv = mx - ix for i in 0,1,2: if dv[i] > hproj[i]: dv = dv - mat.rprimd[i] #periodic boundary conditions - can be not correct (in the sense that closest image can lie not 100 % in the neighbourhood image cell ) for oblique cells and large absolute values of dv if dv[i] < -hproj[i]: dv = dv + mat.rprimd[i] len1 = np.linalg.norm(dv) len2, second_len2 = mat.image_distance(mx, ix, r, 1) #check len1 #print "Lengths calculated with two methods ", len1, len2 len1 = len2 #just use second method #assert np.around(len1,1) == np.around(len2,1) if len1 < dv_min: dv_min = len1; j_r = j # number of matrix atom to replace if 1: #Modify to replace overlapping atoms if dv_min == max_dis: print_and_log( " is more far away from any matrix atom than ",dv_min," A; I insert it") # mat.xcart.append( ix ) # print_and_log( 'type of added atom is ', ins.typat[i_x]) # mat.typat.append( ins.typat[i_x] ) mat = mat.add_atom(xc = ix, element = ins.get_elements()[i_x] ) else: print_and_log( "will replace martix atom", mat.xcart[j_r] ) mat.xcart[j_r] = ix.copy() mat.rprimd = r mat.xcart2xred() mat.natom = len(mat.xcart) mat.name = 'test_of_insert' st = mat # print(st.natom, len(st.xcart), len(st.typat), len(st.znucl), max(st.typat) ) # write_xyz(mat) mat = mat.return_atoms_to_cell() mat.write_poscar() return mat #write_xyz(mat) def make_interface(main_slab, m_xc, second_slab, s_xc): """ Make interfaces Both slabs should have close sizes along x and y and should be oriented correctly Input: main_slab (Structure) - slab second_slab (Structure) - slab, scaled to coincide with the main slab m_xc, s_xc (array(3)) - cartesian coordinates of pointis in main_slab and secondary slab to be combined Return Slab with interface and scaled second slab """ ins = copy.deepcopy(second_slab) mat = copy.deepcopy(main_slab) if 1: #scale insertion mr = mat.rprimd_len() ir = ins.rprimd_len() print('Matrix vlength', mr) print('Insert vlength', ir) x_scale = mr[0]/ ir[0] y_scale = mr[1]/ ir[1] print('Scaling factors', x_scale, y_scale) # print('i_center', i_center) ins.rprimd[0] = ins.rprimd[0]*x_scale ins.rprimd[1] = ins.rprimd[1]*y_scale ir = ins.rprimd_len() s_xred = xcart2xred([s_xc], ins.rprimd)[0] print('Insert vlength after scaling', ir) ins.update_xcart() # ins.xcart2xred() ins_sc = ins.copy() ins_sc.name+='_scaled' s_xc = xred2xcart([s_xred], ins.rprimd)[0] # print('i_center', i_center) if 1: for i, x in enumerate(ins.xcart): ins.xcart[i] = x - s_xc for i, x in enumerate(mat.xcart): mat.xcart[i] = x - m_xc for i_x, ix in enumerate(ins.xcart): mat = mat.add_atom(xc = ix, element = ins.get_elements()[i_x] ) mat.xcart2xred() mat.natom = len(mat.xcart) mat.name += 'inteface' mat = mat.return_atoms_to_cell() mat = mat.shift_atoms([0,0,0.5]) return mat, ins_sc def insert(it_ins, ise_ins, mat_path, it_new, calc, type_of_insertion = "xcart" ): """For insertion of atoms to cells with changed lateral sizes Input: 'type_of_insertion = xred' used to add xred coordinates mat_path - path to geo files which are supposed to be changed it_ins - already existed calculation; xred will be used from this calculation. it_new - new folder in geo folder for obtained structure This function finds version of calculation in folder mat_path and tries to use the same version of it_ins """ if not os.path.exists(mat_path): print_and_log("Error! Path "+mat_path+" does not exist\n\n") raise RuntimeError if it_ins not in mat_path and it_ins not in it_new: print_and_log('Cells are', it_ins, mat_path, it_new) print_and_log("Error! you are trying to insert coordinates from cell with different name\n\n") #raise RuntimeError hstring = ("%s #on %s"% (traceback.extract_stack(None, 2)[0][3], datetime.date.today() ) ) if hstring != header.history[-1]: header.history.append( hstring ) geofilelist = runBash('find '+mat_path+'/target -name "*.geo*" ').splitlines() if geofilelist == []: print_and_log("Warning! Target folder is empty. Trying to find in root folder ...") geofilelist = runBash('find '+mat_path+'/ -name "*.geo*" ').splitlines() ins = None for mat_geofile in geofilelist: mat = CalculationVasp() mat.name = mat_geofile mat.read_geometry(mat_geofile) #step = 0.27 #r_pore = 0.56 #r_mat = mat.hex_a / 2 - step #pores = find_pores(mat.init, r_mat, r_pore, step, 0.3, 'central') #octahedral #mat.xcart.append ( pores.xcart[0] ) #mat.typat.append(1) try: ins_working = ins ins = calc[(it_ins, ise_ins, mat.version)] except KeyError: print_and_log( "No key", (it_ins, ise_ins, mat.version), "I use previous working version !!!", imp = 'y' ) ins = ins_working #return #ins.end.znucl = ins.znucl #ins.end.nznucl = ins.nznucl #ins.end.ntypat = ins.ntypat #ins.end.typat = ins.typat #print ins.xcart[-1] mat_geopath = geo_folder+struct_des[it_new].sfolder + '/' if type_of_insertion == "xcart": #Please update here! mat_filename = '/'+it_new+"."+"inserted."+str(mat.version)+'.'+'geo' v = np.zeros(3) result = insert_cluster(ins.end, v, mat.init, v ) mat.end = result mat.init = result # mat.znucl = mat.end.znucl # mat.nznucl = mat.end.nznucl # mat.ntypat = mat.end.ntypat # mat.typat = mat.end.typat # mat.natom = len(mat.end.xred) #mat.version = ins.version des = ins.name+" was inserted to "+mat_geofile elif type_of_insertion == "xred": mat_filename = '/from/'+it_new+".xred."+str(mat.version)+'.'+'geo' #mat.end.rprimd = mat.rprimd #mat.init.xred = copy.deepcopy(ins.end.xred) #mat.init.typat = copy.deepcopy(ins.end.) #print ins.end.xcart rprimd = copy.deepcopy(mat.init.rprimd) #build = mat.build mat.init = copy.deepcopy(ins.end) #mat.build = build mat.init.rprimd = rprimd #return initial rprimd mat.init.xred2xcart() #calculate xcart with new rprimd des = "atoms with reduced coord. from "+ins.name+" was fully copied to "+mat_geofile mat.init.name = 'test_insert_xred'+str(mat.version) write_xyz(mat.init) mat.path["input_geo"] = mat_geopath + it_new + mat_filename if not mat.write_geometry("init",des): continue print_and_log("Xred from "+it_ins+" was inserted in "+mat_geofile+" and saved as "+mat_filename+" \n\n") return def determine_voids(st, r_impurity, fine = 1, step_dec = 0.05): if not r_impurity: printlog('add_neb(): Error!, Please provide *r_impurity* (1.6 A?)') sums = [] avds = [] printlog('Searching for voids', important = 'y') st_pores = find_pores(st, r_matrix = 0.5, r_impurity = r_impurity, step_dec = step_dec, fine = fine, calctype = 'all_pores') printlog('List of found voids:\n', np.array(st_pores.xcart) ) write_xyz(st.add_atoms(st_pores.xcart, 'H'), file_name = st.name+'_possible_positions') write_xyz(st.add_atoms(st_pores.xcart, 'H'), replications = (2,2,2), file_name = st.name+'_possible_positions_replicated') for x in st_pores.xcart: # summ = local_surrounding(x, st, n_neighbours = 6, control = 'sum', periodic = True) # avd = local_surrounding(x, st, n_neighbours = 6, control = 'av_dev', periodic = True) summ, avd = local_surrounding2(x, st, n_neighbours = 6, control = 'sum_av_dev', periodic = True) # print (summ, avd) sums.append(summ) avds.append(avd[0]) # print sums = np.array(sums) avds = np.array(avds).round(0) print_and_log('Sum of distances to 6 neighboring atoms for each void (A):\n', sums, imp ='y') print_and_log('Distortion of voids (0 - is symmetrical):\n', avds, imp ='y') return st_pores, sums, avds def determine_unique_voids(st_pores, sums, avds): crude_prec = 1 # number of signs after 0 sums_crude = np.unique(sums.round(crude_prec)) print_and_log('The unique voids based on the sums:', '\nwith 0.01 A prec:',np.unique(sums.round(2)), '\nwith 0.1 A prec:',sums_crude, imp ='y') print_and_log('Based on crude criteria only', len(sums_crude),'types of void are relevant', imp = 'y') insert_positions = [] start_table = [] for i, s in enumerate(sums_crude): index_of_first = np.where(sums.round(crude_prec)==s)[0][0] start_table.append([i, st_pores.xcart[index_of_first].round(2), index_of_first, avds[index_of_first], sums[index_of_first] ]) insert_positions.append( st_pores.xcart[index_of_first] ) print_and_log( tabulate(start_table, headers = ['void #', 'Cart.', 'Index', 'Dev.', 'Sum'], tablefmt='psql'), imp = 'Y' ) return insert_positions def insert_atom(st, el, i_void = None, i_void_list = None, r_imp = 1.6, ): """Simple Wrapper for inserting atoms i_void (int) has higher priority than i_void_list return st_new, i_add, sts_by_one st_new - all positions are filled i_add - the number of last inserted atom sts_by_one - list of structures with only one inserted atom in all found positions """ r_impurity = r_imp st_pores, sums, avds = determine_voids(st, r_impurity) insert_positions = determine_unique_voids(st_pores, sums, avds) printlog('To continue please choose *i_void* from the list above', imp = 'y') # st.name = st.name.split('+')[0] if i_void: i_void_list = [i_void] if i_void_list is None: i_void_list = list(range(len(insert_positions))) printlog('No i_void was provided, I insert all', imp = 'y') st_new = st.copy() sts_by_one = [] for i in i_void_list: xc = insert_positions[i] st_new, i_add = st_new.add_atoms([xc], el, return_ins = True) st_one, _ = st.add_atoms([xc], el, return_ins = True) st_one.name+='+'+el+str(i) sts_by_one.append(st_one) st_new.name+='+'+el+str(i) st_new.des+=';Atom '+el+' added to '+ str(xc) printlog(st.des, imp = 'y') st_new.write_poscar() st_new.magmom = [None] return st_new, i_add, sts_by_one
gpl-2.0
590,717,953,333,718,100
35.314083
252
0.560488
false
3.195044
false
false
false
psistrm12/rpiradio
buttonIO.py
1
2334
#!/usr/bin/env python # # Raspberry Pi input using buttons and rotary encoders # # Acknowledgement: This code is a variation oft the Rotary Switch Tutorial by Bob Rathbone. # See http://www.bobrathbone.com/raspberrypi_rotary.htm for further information! import RPi.GPIO as GPIO class PushButton: BUTTONDOWN = 1 BUTTONUP = 2 def __init__(self, pin, bouncetime, callback): self.pin = pin self.bouncetime = bouncetime self.callback = callback GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(self.pin, GPIO.BOTH, callback=self.button_event, bouncetime=self.bouncetime) return # Push button up event def button_event(self, b_event): if GPIO.input(b_event): event = self.BUTTONDOWN else: event = self.BUTTONUP self.callback(event) return # end class PushButton class RotaryEncoder: CLOCKWISE = 3 ANTICLOCKWISE = 4 rotary_a = 0 rotary_b = 0 rotary_c = 0 last_state = 0 direction = 0 # Initialise rotary encoder object def __init__(self,pinA,pinB,callback): self.pinA = pinA self.pinB = pinB #self.button = button self.callback = callback GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.pinA, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.pinB, GPIO.IN, pull_up_down=GPIO.PUD_UP) # add events GPIO.add_event_detect(self.pinA, GPIO.FALLING, callback=self.switch_event) GPIO.add_event_detect(self.pinB, GPIO.FALLING, callback=self.switch_event) return # Call back routine called by switch events def switch_event(self,switch): if GPIO.input(self.pinA): self.rotary_a = 1 else: self.rotary_a = 0 if GPIO.input(self.pinB): self.rotary_b = 1 else: self.rotary_b = 0 self.rotary_c = self.rotary_a ^ self.rotary_b new_state = self.rotary_a * 4 + self.rotary_b * 2 + self.rotary_c * 1 delta = (new_state - self.last_state) % 4 self.last_state = new_state event = 0 if delta == 1: if self.direction == self.CLOCKWISE: event = self.direction else: self.direction = self.CLOCKWISE elif delta == 3: if self.direction == self.ANTICLOCKWISE: event = self.direction else: self.direction = self.ANTICLOCKWISE if event > 0: self.callback(event) return # end class RotaryEncoder
gpl-2.0
-9,129,966,791,251,890,000
21.442308
100
0.693231
false
2.736225
false
false
false
spivachuk/sovrin-node
scripts/performance/perf_traffic.py
1
9901
""" Created on Feb 27, 2018 @author: nhan.nguyen This module contains class "TesterSimulateTraffic" that simulates the real time traffic. """ import threading import random import time import utils import os import asyncio import argparse import requests_sender import requests_builder import perf_add_requests from perf_tester import Tester class Option: def __init__(self): parser = argparse.ArgumentParser( description='Script to simulate the traffic which will send' 'request to ledger in several sets. Each set contains ' 'a specified number of requests and between two set, ' 'the system will be delayed for a random length of' ' time (from 1 to 10 seconds).\n\n', usage='To create 5 client to simulate the traffic in 50 seconds ' 'and you want each set contains 100 request.' '\nuse: python3.6 perf_traffic.py -c 5 -t 50 -n 100') parser.add_argument('-c', help='Specify the number of clients ' 'will be simulated. Default value will be 1.', action='store', type=int, default=1, dest='clients') parser.add_argument('-n', help='Number of transactions will be sent ' 'in a set. Default value will be 100.', action='store', type=int, default=100, dest='transactions_delay') parser.add_argument('--log', help='To see all log. If this flag does not exist,' 'program just only print fail message', action='store_true', default=False, dest='log') parser.add_argument('-to', help='Timeout of testing. ' 'Default value will be 100.', action='store', type=int, default=100, dest='time_out') parser.add_argument('--init', help='To build "GET" request, we need to ' 'send "ADD" request first. This argument is ' 'the number of "ADD" request will be sent ' 'to ledger to make sample for "GET" requests.' ' Default value will be 100', action='store', type=int, default=100, dest='number_of_request_samples') self.args = parser.parse_args() def catch_number_of_request_samples(): """ Parse number of sample of "GET" requests will be created. If the number is less than of equal with zero, default value (100) will be returned. :return: number of sample of "GET" requests. """ import sys result = 100 if "--init" in sys.argv: index = sys.argv.index("--init") if index < len(sys.argv) - 1: temp = -1 try: temp = int(sys.argv[index + 1]) except ValueError: pass if temp > 0: result = temp return result class TesterSimulateTraffic(Tester): __sample_req_info = {} __kinds_of_request = ["nym", "attribute", "schema", "claim", "get_nym", "get_attribute", "get_schema", "get_claim"] __number_of_request_samples = catch_number_of_request_samples() def __init__(self, number_of_clients: int = 2, transactions_delay: int = 100, time_out: int = 300, log=False, seed="000000000000000000000000Trustee1"): super().__init__(log=log, seed=seed) utils.run_async_method( None, TesterSimulateTraffic._prepare_samples_for_get_req, TesterSimulateTraffic.__number_of_request_samples) if time_out <= 0 or transactions_delay <= 0 or number_of_clients <= 0: return self.transactions_delay = transactions_delay self.time_out = time_out self.number_of_clients = number_of_clients self.current_total_txn = 0 self.__current_time = time.time() self.__lock = threading.Lock() self.__sender = requests_sender.RequestsSender() async def _test(self): """ Override from "Tester" class to implement testing steps. """ lst_threads = list() self.__current_time = time.time() for _ in range(self.number_of_clients): thread = threading.Thread(target=self.__simulate_client) thread.setDaemon(True) thread.start() lst_threads.append(thread) for thread in lst_threads: thread.join(self.time_out * 1.1) self.passed_req = self.__sender.passed_req self.failed_req = self.__sender.failed_req self.fastest_txn = self.__sender.fastest_txn self.lowest_txn = self.__sender.lowest_txn def __update(self): """ Synchronize within threads to update some necessary information. """ self.__lock.acquire() if self.start_time == 0 and self.finish_time != 0: self.start_time = self.finish_time if self.current_total_txn != 0 and \ self.current_total_txn % self.transactions_delay == 0: time.sleep(random.randint(1, 10)) self.current_total_txn += 1 self.__lock.release() def __simulate_client(self): """ Simulate a client to create real time traffic. """ loop = asyncio.new_event_loop() args = {"wallet_handle": self.wallet_handle, "pool_handle": self.pool_handle, "submitter_did": self.submitter_did} asyncio.set_event_loop(loop) while True: self.__update() if time.time() - self.__current_time >= self.time_out: break self.finish_time = utils.run_async_method( loop, TesterSimulateTraffic._build_and_send_request, self.__sender, args) loop.close() @staticmethod async def generate_sample_request_info(kind, sample_num: int = 100) -> list: """ Generate sample request information. :param kind: kind of request. :param sample_num: number of samples will be generated. :return: a list of samples request information. """ kinds = ["nym", "schema", "attribute", "claim"] if kind not in kinds or sample_num <= 0: return [] generator = perf_add_requests.PerformanceTesterForAddingRequest( request_num=sample_num, request_kind=kind) await generator.test() lst_info = list() with open(generator.info_file_path, "r") as info_file: for line in info_file: if len(line) > 2: lst_info.append(line) try: os.remove(generator.info_file_path) except IOError: pass return lst_info @staticmethod async def _prepare_samples_for_get_req(sample_num: int = 100): """ Init samples for "GET" requests. :param sample_num: create a number of samples request information for each kind of request (nym, attribute, claim, schema) """ if TesterSimulateTraffic.__sample_req_info: return keys = ["nym", "attribute", "schema", "claim"] if sample_num <= 0: return for key in keys: TesterSimulateTraffic.__sample_req_info[key] = \ await TesterSimulateTraffic.generate_sample_request_info( key, sample_num) @staticmethod def _random_req_kind(): """ Random choice a request kind. :return: request kind. """ return random.choice(TesterSimulateTraffic.__kinds_of_request) @staticmethod def _random_sample_for_get_request(kind: str): """ Choice randomly a sample of request info base on kind of request. :param kind: kind of request (get_nym, get_attribute, get_claim, get_schema). :return: a random sample of request info. """ if kind.startswith("get_"): return random.choice( TesterSimulateTraffic.__sample_req_info[kind.replace( "get_", "")]) return "" @staticmethod async def _build_and_send_request(sender, args): """ Build a request and send it onto ledger. :param sender: send the request. :param args: contains some arguments to send request to ledger (pool handle, wallet handle, submitter did) :return: response time. """ kind = TesterSimulateTraffic._random_req_kind() data = TesterSimulateTraffic._random_sample_for_get_request(kind) req = await requests_builder.RequestBuilder.build_request(args, kind, data) return await sender.send_request(args, kind, req) if __name__ == '__main__': opts = Option().args tester = TesterSimulateTraffic(number_of_clients=opts.clients, transactions_delay=opts.transactions_delay, time_out=opts.time_out, log=opts.log) utils.run_async_method(None, tester.test) elapsed_time = tester.finish_time - tester.start_time utils.print_client_result(tester.passed_req, tester.failed_req, elapsed_time)
apache-2.0
5,081,833,395,924,299,000
33.378472
79
0.54045
false
4.443896
true
false
false
SasView/sasmodels
sasmodels/models/fcc_paracrystal.py
1
6252
#fcc paracrystal model #note model title and parameter table are automatically inserted #note - calculation requires double precision r""" .. warning:: This model and this model description are under review following concerns raised by SasView users. If you need to use this model, please email help@sasview.org for the latest situation. *The SasView Developers. September 2018.* Definition ---------- Calculates the scattering from a **face-centered cubic lattice** with paracrystalline distortion. Thermal vibrations are considered to be negligible, and the size of the paracrystal is infinitely large. Paracrystalline distortion is assumed to be isotropic and characterized by a Gaussian distribution. The scattering intensity $I(q)$ is calculated as .. math:: I(q) = \frac{\text{scale}}{V_p} V_\text{lattice} P(q) Z(q) where *scale* is the volume fraction of spheres, $V_p$ is the volume of the primary particle, $V_\text{lattice}$ is a volume correction for the crystal structure, $P(q)$ is the form factor of the sphere (normalized), and $Z(q)$ is the paracrystalline structure factor for a face-centered cubic structure. Equation (1) of the 1990 reference\ [#Matsuoka1990]_ is used to calculate $Z(q)$, using equations (23)-(25) from the 1987 paper\ [#Matsuoka1987]_ for $Z1$, $Z2$, and $Z3$. The lattice correction (the occupied volume of the lattice) for a face-centered cubic structure of particles of radius $R$ and nearest neighbor separation $D$ is .. math:: V_\text{lattice} = \frac{16\pi}{3}\frac{R^3}{\left(D\sqrt{2}\right)^3} The distortion factor (one standard deviation) of the paracrystal is included in the calculation of $Z(q)$ .. math:: \Delta a = gD where $g$ is a fractional distortion based on the nearest neighbor distance. .. figure:: img/fcc_geometry.jpg Face-centered cubic lattice. For a crystal, diffraction peaks appear at reduced q-values given by .. math:: \frac{qD}{2\pi} = \sqrt{h^2 + k^2 + l^2} where for a face-centered cubic lattice $h, k , l$ all odd or all even are allowed and reflections where $h, k, l$ are mixed odd/even are forbidden. Thus the peak positions correspond to (just the first 5) .. math:: \begin{array}{cccccc} q/q_0 & 1 & \sqrt{4/3} & \sqrt{8/3} & \sqrt{11/3} & \sqrt{4} \\ \text{Indices} & (111) & (200) & (220) & (311) & (222) \end{array} .. note:: The calculation of $Z(q)$ is a double numerical integral that must be carried out with a high density of points to properly capture the sharp peaks of the paracrystalline scattering. So be warned that the calculation is slow. Fitting of any experimental data must be resolution smeared for any meaningful fit. This makes a triple integral which may be very slow. The 2D (Anisotropic model) is based on the reference below where $I(q)$ is approximated for 1d scattering. Thus the scattering pattern for 2D may not be accurate particularly at low $q$. For general details of the calculation and angular dispersions for oriented particles see :ref:`orientation`. Note that we are not responsible for any incorrectness of the 2D model computation. .. figure:: img/parallelepiped_angle_definition.png Orientation of the crystal with respect to the scattering plane, when $\theta = \phi = 0$ the $c$ axis is along the beam direction (the $z$ axis). References ---------- .. [#Matsuoka1987] Hideki Matsuoka et. al. *Physical Review B*, 36 (1987) 1754-1765 (Original Paper) .. [#Matsuoka1990] Hideki Matsuoka et. al. *Physical Review B*, 41 (1990) 3854-3856 (Corrections to FCC and BCC lattice structure calculation) Authorship and Verification --------------------------- * **Author:** NIST IGOR/DANSE **Date:** pre 2010 * **Last Modified by:** Paul Butler **Date:** September 29, 2016 * **Last Reviewed by:** Richard Heenan **Date:** March 21, 2016 """ import numpy as np from numpy import inf, pi name = "fcc_paracrystal" title = "Face-centred cubic lattic with paracrystalline distortion" description = """ Calculates the scattering from a **face-centered cubic lattice** with paracrystalline distortion. Thermal vibrations are considered to be negligible, and the size of the paracrystal is infinitely large. Paracrystalline distortion is assumed to be isotropic and characterized by a Gaussian distribution. """ category = "shape:paracrystal" single = False # pylint: disable=bad-whitespace, line-too-long # ["name", "units", default, [lower, upper], "type","description"], parameters = [["dnn", "Ang", 220, [-inf, inf], "", "Nearest neighbour distance"], ["d_factor", "", 0.06, [-inf, inf], "", "Paracrystal distortion factor"], ["radius", "Ang", 40, [0, inf], "volume", "Particle radius"], ["sld", "1e-6/Ang^2", 4, [-inf, inf], "sld", "Particle scattering length density"], ["sld_solvent", "1e-6/Ang^2", 1, [-inf, inf], "sld", "Solvent scattering length density"], ["theta", "degrees", 60, [-360, 360], "orientation", "c axis to beam angle"], ["phi", "degrees", 60, [-360, 360], "orientation", "rotation about beam"], ["psi", "degrees", 60, [-360, 360], "orientation", "rotation about c axis"] ] # pylint: enable=bad-whitespace, line-too-long source = ["lib/sas_3j1x_x.c", "lib/gauss150.c", "lib/sphere_form.c", "fcc_paracrystal.c"] def random(): """Return a random parameter set for the model.""" # copied from bcc_paracrystal radius = 10**np.random.uniform(1.3, 4) d_factor = 10**np.random.uniform(-2, -0.7) # sigma_d in 0.01-0.7 dnn_fraction = np.random.beta(a=10, b=1) dnn = radius*4/np.sqrt(2)/dnn_fraction pars = dict( #sld=1, sld_solvent=0, scale=1, background=1e-32, dnn=dnn, d_factor=d_factor, radius=radius, ) return pars # april 10 2017, rkh add unit tests, NOT compared with any other calc method, assume correct! # TODO: fix the 2d tests q = 4.*pi/220. tests = [ [{}, [0.001, q, 0.215268], [0.275164706668, 5.7776842567, 0.00958167119232]], #[{}, (-0.047, -0.007), 238.103096286], #[{}, (0.053, 0.063), 0.863609587796], ]
bsd-3-clause
-7,846,327,260,319,252,000
37.832298
104
0.671465
false
3.207799
false
false
false
motherjones/mirrors
mirrors/tests/test_auth.py
1
1445
from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase class ComponentAuthenticationTest(APITestCase): fixtures = ['users.json', 'component_data.json'] def test_noauthed_rejects(self): url = reverse('component-detail', kwargs={ 'slug': 'component-with-svg-data' }) res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) def test_authed_as_user_accepts(self): url = reverse('component-detail', kwargs={ 'slug': 'component-with-svg-data' }) self.client.login(username='test_user', password='password1') res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_authed_as_staff_accepts(self): url = reverse('component-detail', kwargs={ 'slug': 'component-with-svg-data' }) self.client.login(username='test_staff', password='password1') res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_authed_as_admin_accepts(self): url = reverse('component-detail', kwargs={ 'slug': 'component-with-svg-data' }) self.client.login(username='test_admin', password='password1') res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK)
mit
7,669,851,948,419,885,000
32.604651
71
0.640138
false
3.695652
true
false
false
yasserglez/pytiger2c
packages/pytiger2c/ast/andoperatornode.py
1
2345
# -*- coding: utf-8 -*- """ Clase C{AndOperatorNode} del árbol de sintáxis abstracta. """ from pytiger2c.ast.binarylogicaloperatornode import BinaryLogicalOperatorNode from pytiger2c.types.integertype import IntegerType class AndOperatorNode(BinaryLogicalOperatorNode): """ Clase C{AndOperatorNode} del árbol de sintáxis abstracta. Representa la operación lógica C{AND}, representada con el operador C{&} en Tiger, entre dos números enteros. Este operador retornará 1 en caso de que el resultado de evaluar la expresión sea verdadero, 0 en otro caso. """ def __init__(self, left, right): """ Inicializa la clase C{AndOperatorNode}. Para obtener información acerca de los parámetros recibidos por este método consulte la documentación del método C{__init__} en la clase C{BinaryOperatorNode}. """ super(AndOperatorNode, self).__init__(left, right) def generate_code(self, generator): """ Genera el código C correspondiente a la estructura del lenguaje Tiger representada por el nodo. @type generator: C{CodeGenerator} @param generator: Clase auxiliar utilizada en la generación del código C correspondiente a un programa Tiger. @raise CodeGenerationError: Esta excepción se lanzará cuando se produzca algún error durante la generación del código correspondiente al nodo. La excepción contendrá información acerca del error. """ self.scope.generate_code(generator) result_var = generator.define_local(IntegerType().code_type) self.left.generate_code(generator) generator.add_statement('if (!{left}) {{'.format(left=self.left.code_name)) generator.add_statement('{result} = 0; }}'.format(result=result_var)) generator.add_statement('else {') self.right.generate_code(generator) generator.add_statement('if ({right}) {{'.format(right=self.right.code_name)) generator.add_statement('{result} = 1; }}'.format(result=result_var)) generator.add_statement('else {') generator.add_statement('{result} = 0; }}'.format(result=result_var)) generator.add_statement('}') self._code_name = result_var
mit
-9,185,024,468,901,850,000
41.181818
85
0.663362
false
3.531202
false
false
false
rubik/pyg
pyg/log.py
1
8604
import os import sys import logging __all__ = ['logger'] try: from colorama import init, Fore, Style init(autoreset=False) colors = { 'good' : Fore.GREEN, 'bad' : Fore.RED, 'vgood' : Fore.GREEN + Style.BRIGHT, 'vbad' : Fore.RED + Style.BRIGHT, 'std' : '', # Do not color "standard" text 'warn' : Fore.YELLOW + Style.BRIGHT, 'reset' : Style.RESET_ALL, } except ImportError: colors = { 'good' : '', 'bad' : '', 'vgood' : '', 'vbad' : '', 'std' : '', 'warn' : '', 'reset' : '', } def get_console_width(): """ Return width of available window area. Autodetection works for Windows and POSIX platforms. Returns 80 for others Code from http://bitbucket.org/techtonik/python-wget """ if os.name == 'nt': STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 # get console handle from ctypes import windll, Structure, byref try: from ctypes.wintypes import SHORT, WORD, DWORD except ImportError: # workaround for missing types in Python 2.5 from ctypes import ( c_short as SHORT, c_ushort as WORD, c_ulong as DWORD) console_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) # CONSOLE_SCREEN_BUFFER_INFO Structure class COORD(Structure): _fields_ = [("X", SHORT), ("Y", SHORT)] class SMALL_RECT(Structure): _fields_ = [("Left", SHORT), ("Top", SHORT), ("Right", SHORT), ("Bottom", SHORT)] class CONSOLE_SCREEN_BUFFER_INFO(Structure): _fields_ = [("dwSize", COORD), ("dwCursorPosition", COORD), ("wAttributes", WORD), ("srWindow", SMALL_RECT), ("dwMaximumWindowSize", DWORD)] sbi = CONSOLE_SCREEN_BUFFER_INFO() ret = windll.kernel32.GetConsoleScreenBufferInfo(console_handle, byref(sbi)) if ret == 0: return 0 return sbi.srWindow.Right+1 elif os.name == 'posix': from fcntl import ioctl from termios import TIOCGWINSZ from array import array winsize = array("H", [0] * 4) try: ioctl(sys.stdout.fileno(), TIOCGWINSZ, winsize) except IOError: pass return (winsize[1], winsize[0])[0] return 80 class Logger(object): VERBOSE = logging.DEBUG - 1 DEBUG = logging.DEBUG INFO = logging.INFO WARN = logging.WARNING ERROR = logging.ERROR FATAL = logging.FATAL ## This attribute is set to True when the user does not want colors ## by __init__.py _NO_COLORS = False def __init__(self,level=None): self.indent = 0 self.level = level or Logger.INFO self._stack = [''] self.enabled = True def disable_colors(self): self._NO_COLORS = True for k in colors.keys(): colors[k] = '' def newline(self): '''Print a newline character (\n) on Standard Output.''' sys.stdout.write('\n') def raise_last(self, exc): raise exc(self.last_msg) @property def last_msg(self): return self._stack[-1] def ask(self, message=None, bool=None, choices=None, dont_ask=False): if bool is not None: if bool in (True, False) or (isinstance(bool, (list, tuple)) and len(bool) == 1): if bool == False: txt = "Cancel" elif bool == True: txt = "OK" else: txt = bool[0] self.log(self.info, 'std', "%s, %s..."%(message, txt), addn=False) if not dont_ask: raw_input() return else: if dont_ask: self.log(self.info, 'std', '%s ? Yes'%message) return True while True: self.log(self.info, 'std', "yes: "+bool[0]) self.log(self.info, 'std', "no: "+bool[1]) try: self.log(self.info, 'std', '%s ? (y/[n]) '%message, addn=False) ans = raw_input() except Exception: continue # default choice : no if not ans.strip(): return False if ans not in 'yYnN': continue return ans in 'yY' if choices: if isinstance(choices, dict): _data = choices choices = choices.keys() else: _data = None self.log(self.info, 'std', message) for n, choice in enumerate(choices): self.log(self.info, 'std', "%2d - %s"%(n+1, choice)) while True: try: ans = input('Your choice ? ') except Exception: self.log(self.info, 'std', "Please enter selected option's number.") continue if ans < 0 or ans > len(choices): continue break idx = choices[ans-1] return (_data[idx] if _data else idx) def verbose(self, msg, *a, **kw): self.log(self.VERBOSE, 'std', msg, *a, **kw) def debug(self, msg, *a, **kw): self.log(self.DEBUG, 'std', msg, *a, **kw) def info(self, msg, *a, **kw): self.log(self.INFO, 'std', msg, *a, **kw) def success(self, msg, *a, **kw): self.log(self.INFO, 'good', msg, *a, **kw) def warn(self, msg, *a, **kw): self.log(self.WARN, 'warn', msg, *a, **kw) def error(self, msg, *a, **kw): self.log(self.ERROR, 'bad', msg, *a, **kw) exc = kw.get('exc', None) if exc is not None: raise exc(self.last_msg) def fatal(self, msg, *a, **kw): self.log(self.FATAL, 'vbad', msg, *a, **kw) exc = kw.get('exc', None) if exc is not None: raise exc(self.last_msg) def exit(self, msg=None, status=1): if msg != None: self.log(self.FATAL, 'vbad', msg) sys.exit(status) def log(self, level, col, msg, *a, **kw): ''' This is the base function that logs all messages. This function prints a newline character too, unless you specify ``addn=False``. When the message starts with a return character (\r) it automatically cleans the line. ''' if level >= self.level and self.enabled: std = sys.stdout if level >= self.ERROR: std = sys.stderr ## We can pass to logger.log any object: it must have at least ## a __repr__ or a __str__ method. msg = str(msg) if msg.startswith('\r') or self.last_msg.startswith('\r'): ## We have to clear the line in case this message is longer than ## the previous std.write('\r' + ' ' * get_console_width()) msg = '\r' + ' ' * self.indent + msg.lstrip('\r').format(*a) else: try: msg = ' ' * self.indent + msg.format(*a) except KeyError: msg = ' ' * self.indent + msg col, col_reset = colors[col], colors['reset'] if self._NO_COLORS: col, col_reset = '', '' std.write(col + msg + col_reset) ## Automatically adds a newline character if kw.get('addn', True): self.newline() ## flush() makes the log immediately readable std.flush() self._stack.append(msg) logger = Logger() if __name__ == '__main__': print logger.ask("Beware, you enter a secret place", bool=True) print logger.ask("Sorry, can't install this package", bool=False) print logger.ask("Sorry, can't install this package", bool=['Press any key to continue']) print logger.ask('Proceed', bool=('remove files', 'cancel')) print logger.ask('Do you want to upgrade', bool=('upgrade version', 'keep working version')) print logger.ask('Installation method', choices=('Egg based', 'Flat directory')) print logger.ask('some dict', choices={'choice a': 'a', 'choice b': 'b', 'choice c': 'c'})
mit
6,918,560,899,047,315,000
30.866667
112
0.496165
false
3.979648
false
false
false
3DGenomes/tadbit
_pytadbit/mapping/analyze.py
1
67679
""" 18 Nov 2014 """ from warnings import warn from collections import OrderedDict from pysam import AlignmentFile from scipy.stats import norm as sc_norm, skew, kurtosis from scipy.stats import pearsonr, spearmanr, linregress from scipy.sparse.linalg import eigsh from numpy.linalg import eigh import numpy as np try: from matplotlib import rcParams from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from matplotlib.colors import LinearSegmentedColormap except ImportError: warn('matplotlib not found\n') from pytadbit import HiC_data from pytadbit.utils.extraviews import tadbit_savefig, setup_plot from pytadbit.utils.tadmaths import nozero_log_matrix as nozero_log from pytadbit.utils.tadmaths import right_double_mad as mad from pytadbit.parsers.hic_parser import load_hic_data_from_reads from pytadbit.utils.extraviews import nicer from pytadbit.utils.file_handling import mkdir def hic_map(data, resolution=None, normalized=False, masked=None, by_chrom=False, savefig=None, show=False, savedata=None, focus=None, clim=None, perc_clim=None, cmap='jet', pdf=False, decay=True, perc=20, name=None, decay_resolution=None, **kwargs): """ function to retrieve data from HiC-data object. Data can be stored as a square matrix, or drawn using matplotlib :param data: can be either a path to a file with pre-processed reads (filtered or not), or a Hi-C-data object :param None resolution: at which to bin the data (try having a dense matrix with < 10% of cells with zero interaction counts). Note: not necessary if a hic_data object is passed as 'data'. :param False normalized: used normalized data, based on precalculated biases :param masked: a list of columns to be removed. Usually because to few interactions :param False by_chrom: data can be stored in a partitioned way. This parameter can take the values of: * 'intra': one output per each chromosome will be created * 'inter': one output per each possible pair of chromosome will be created * 'all' : both of the above outputs :param None savefig: path where to store the output images. Note that, if the by_chrom option is used, then savefig will be the name of the directory containing the output files. :param None savedata: path where to store the output matrices. Note that, if the by_chrom option is used, then savefig will be the name of the directory containing the output files. :param None focus: can be either two number (i.e.: (1, 100)) specifying the start and end position of the sub-matrix to display (start and end, along the diagonal of the original matrix); or directly a chromosome name; or two chromosome names (i.e.: focus=('chr2, chrX')), in order to store the data corresponding to inter chromosomal interactions between these two chromosomes :param True decay: plot the correlation between genomic distance and interactions (usually a decay). :param False force_image: force to generate an image even if resolution is crazy... :param None clim: cutoff for the upper and lower bound in the coloring scale of the heatmap. (perc_clim should be set to None) :param None perc_clim: cutoff for the upper and lower bound in the coloring scale of the heatmap; in percentile. (clim should be set to None) :param False pdf: when using the bny_chrom option, to specify the format of the stored images :param jet cmap: color map to be used for the heatmap; "tadbit" color map is also implemented and will use percentiles of the distribution of interactions to defines intensities of red. :param None decay_resolution: chromatin fragment size to consider when calculating decay of the number of interactions with genomic distance. Default is equal to resolution of the matrix. """ if isinstance(data, str): data = load_hic_data_from_reads(data, resolution=resolution, **kwargs) if not kwargs.get('get_sections', True) and decay: warn('WARNING: not decay not available when get_sections is off.') decay = False if clim and perc_clim: raise Exception('ERROR: only one of clim or perc_clim should be set\n') hic_data = data resolution = data.resolution if not decay_resolution: decay_resolution = resolution if hic_data.bads and not masked: masked = hic_data.bads # save and draw the data if by_chrom: if focus: raise Exception('Incompatible options focus and by_chrom\n') if savedata: mkdir(savedata) if savefig: mkdir(savefig) for i, crm1 in enumerate(hic_data.chromosomes): for crm2 in hic_data.chromosomes.keys()[i:]: if by_chrom == 'intra' and crm1 != crm2: continue if by_chrom == 'inter' and crm1 == crm2: continue try: subdata = hic_data.get_matrix(focus=(crm1, crm2), normalized=normalized) start1, _ = hic_data.section_pos[crm1] start2, _ = hic_data.section_pos[crm2] masked1 = {} masked2 = {} if focus and hic_data.bads: # rescale masked masked1 = dict([(m - start1, hic_data.bads[m]) for m in hic_data.bads]) masked2 = dict([(m - start2, hic_data.bads[m]) for m in hic_data.bads]) if masked1 or masked2: for i in xrange(len(subdata)): if i in masked1: subdata[i] = [float('nan') for j in xrange(len(subdata))] for j in xrange(len(subdata)): if j in masked2: subdata[i][j] = float('nan') if savedata: hic_data.write_matrix('%s/%s.mat' % ( savedata, '_'.join(set((crm1, crm2)))), focus=(crm1, crm2), normalized=normalized) if show or savefig: if (len(subdata) > 10000 and not kwargs.get('force_image', False)): warn('WARNING: Matrix image not created, more than ' '10000 rows, use a lower resolution to create images') continue draw_map(subdata, OrderedDict([(k, hic_data.chromosomes[k]) for k in hic_data.chromosomes.keys() if k in [crm1, crm2]]), hic_data.section_pos, '%s/%s.%s' % (savefig, '_'.join(set((crm1, crm2))), 'pdf' if pdf else 'png'), show, one=True, clim=clim, perc_clim=perc_clim, cmap=cmap, decay_resolution=decay_resolution, perc=perc, name=name, cistrans=float('NaN')) except ValueError, e: print 'Value ERROR: problem with chromosome %s' % crm1 print str(e) except IndexError, e: print 'Index ERROR: problem with chromosome %s' % crm1 print str(e) else: if savedata: hic_data.write_matrix(savedata, focus=focus, normalized=normalized) if show or savefig: subdata = hic_data.get_matrix(focus=focus, normalized=normalized) if (len(subdata) > 10000 and not kwargs.get('force_image', False)): warn('WARNING: Matrix image not created, more than ' '10000 rows, use a lower resolution to create images') return start1 = hic_data._focus_coords(focus)[0] if focus and masked: # rescale masked masked = dict([(m - start1, masked[m]) for m in masked]) if masked: for i in xrange(len(subdata)): if i in masked: subdata[i] = [float('nan') for j in xrange(len(subdata))] for j in xrange(len(subdata)): if j in masked: subdata[i][j] = float('nan') draw_map(subdata, {} if focus else hic_data.chromosomes, hic_data.section_pos, savefig, show, one = True if focus else False, decay=decay, clim=clim, perc_clim=perc_clim, cmap=cmap, decay_resolution=decay_resolution, perc=perc, normalized=normalized, max_diff=kwargs.get('max_diff', None), name=name, cistrans=float('NaN') if focus else hic_data.cis_trans_ratio(normalized, kwargs.get('exclude', None), kwargs.get('diagonal', True), kwargs.get('equals', None))) def draw_map(data, genome_seq, cumcs, savefig, show, one=False, clim=None, perc_clim=None, cmap='jet', decay=False, perc=20, name=None, cistrans=None, decay_resolution=10000, normalized=False, max_diff=None): _ = plt.figure(figsize=(15.,12.5)) if not max_diff: max_diff = len(data) ax1 = plt.axes([0.34, 0.08, 0.6, 0.7205]) ax2 = plt.axes([0.07, 0.65, 0.21, 0.15]) if decay: ax3 = plt.axes([0.07, 0.42, 0.21, 0.15]) plot_distance_vs_interactions(data, genome_seq=genome_seq, axe=ax3, resolution=decay_resolution, max_diff=max_diff, normalized=normalized) ax4 = plt.axes([0.34, 0.805, 0.6, 0.04], sharex=ax1) ax5 = plt.axes([0.34, 0.845, 0.6, 0.04], sharex=ax1) ax6 = plt.axes([0.34, 0.885, 0.6, 0.04], sharex=ax1) try: minoridata = np.nanmin(data) maxoridata = np.nanmax(data) except AttributeError: vals = [i for d in data for i in d if not np.isnan(i)] minoridata = np.min(vals) maxoridata = np.max(vals) totaloridata = np.nansum([data[i][j] for i in xrange(len(data)) for j in xrange(i, len(data[i]))]) # may not be square data = nozero_log(data, np.log2) vals = np.array([i for d in data for i in d]) vals = vals[np.isfinite(vals)] if perc_clim: try: clim = np.percentile(vals, perc_clim[0]), np.percentile(vals, perc_clim[1]) except ValueError: clim = None mindata = np.nanmin(vals) maxdata = np.nanmax(vals) diff = maxdata - mindata norm = lambda x: (x - mindata) / diff posI = 0.01 if not clim else norm(clim[0]) if clim[0] != None else 0.01 posF = 1.0 if not clim else norm(clim[1]) if clim[1] != None else 1.0 if cmap == 'tadbit': cuts = perc cdict = {'red' : [(0.0, 1.0, 1.0)], 'green': [(0.0, 1.0, 1.0)], 'blue' : [(0.0, 1.0, 1.0)]} for i in np.linspace(posI, posF, cuts, endpoint=False): prc = (i / (posF - posI)) / 1.75 pos = norm(np.percentile(vals, i * 100.)) # print '%7.4f %7.4f %7.4f %7.4f' % (prc, pos, np.percentile(vals, i * 100.), i) cdict['red' ].append([pos, 1 , 1 ]) cdict['green'].append([pos, 1 - prc, 1 - prc]) cdict['blue' ].append([pos, 1 - prc, 1 - prc]) cdict['red' ].append([1.0, 1, 1]) cdict['green'].append([1.0, 0, 0]) cdict['blue' ].append([1.0, 0, 0]) cmap = LinearSegmentedColormap(cmap, cdict) clim = None else: cmap = plt.get_cmap(cmap) cmap.set_bad('darkgrey', 1) ax1.imshow(data, interpolation='none', cmap=cmap, vmin=clim[0] if clim else None, vmax=clim[1] if clim else None) size1 = len(data) size2 = len(data[0]) if size1 == size2: for i in xrange(size1): for j in xrange(i, size2): if np.isnan(data[i][j]): data[i][j] = 0 data[j][i] = 0 else: for i in xrange(size1): for j in xrange(size2): if np.isnan(data[i][j]): data[i][j] = 0 #data[j][i] = data[i][j] try: evals, evect = eigh(data) sort_perm = evals.argsort() evect = evect[sort_perm] except: evals, evect = None, None data = [i for d in data for i in d if np.isfinite(i)] gradient = np.linspace(np.nanmin(data), np.nanmax(data), max(size1, size2)) gradient = np.vstack((gradient, gradient)) try: h = ax2.hist(data, color='darkgrey', linewidth=2, bins=20, histtype='step', density=True) except AttributeError: h = ax2.hist(data, color='darkgrey', linewidth=2, bins=20, histtype='step', normed=True) _ = ax2.imshow(gradient, aspect='auto', cmap=cmap, vmin=clim[0] if clim else None, vmax=clim[1] if clim else None, extent=(np.nanmin(data), np.nanmax(data) , 0, max(h[0]))) if genome_seq: for crm in genome_seq: ax1.vlines([cumcs[crm][0]-.5, cumcs[crm][1]-.5], cumcs[crm][0]-.5, cumcs[crm][1]-.5, color='w', linestyle='-', linewidth=1, alpha=1) ax1.hlines([cumcs[crm][1]-.5, cumcs[crm][0]-.5], cumcs[crm][0]-.5, cumcs[crm][1]-.5, color='w', linestyle='-', linewidth=1, alpha=1) ax1.vlines([cumcs[crm][0]-.5, cumcs[crm][1]-.5], cumcs[crm][0]-.5, cumcs[crm][1]-.5, color='k', linestyle='--') ax1.hlines([cumcs[crm][1]-.5, cumcs[crm][0]-.5], cumcs[crm][0]-.5, cumcs[crm][1]-.5, color='k', linestyle='--') if not one: vals = [0] keys = [''] for crm in genome_seq: vals.append(cumcs[crm][0]) keys.append(crm) vals.append(cumcs[crm][1]) ax1.set_yticks(vals) ax1.set_yticklabels('') ax1.set_yticks([float(vals[i]+vals[i+1])/2 for i in xrange(len(vals) - 1)], minor=True) ax1.set_yticklabels(keys, minor=True) for t in ax1.yaxis.get_minor_ticks(): t.tick1On = False t.tick2On = False # totaloridata = ''.join([j + ('' if (i+1)%3 else ',') for i, j in enumerate(str(totaloridata)[::-1])])[::-1].strip(',') # minoridata = ''.join([j + ('' if (i+1)%3 else ',') for i, j in enumerate(str(minoridata)[::-1])])[::-1].strip(',') # maxoridata = ''.join([j + ('' if (i+1)%3 else ',') for i, j in enumerate(str(maxoridata)[::-1])])[::-1].strip(',') plt.figtext(0.05,0.25, ''.join([ (name + '\n') if name else '', 'Number of interactions: %s\n' % str(totaloridata), ('' if np.isnan(cistrans) else ('Percentage of cis interactions: %.0f%%\n' % (cistrans*100))), 'Min interactions: %s\n' % (minoridata), 'Max interactions: %s\n' % (maxoridata)])) ax2.set_xlim((np.nanmin(data), np.nanmax(data))) ax2.set_ylim((0, max(h[0]))) ax1.set_xlim ((-0.5, size1 - .5)) ax1.set_ylim ((-0.5, size2 - .5)) ax2.set_xlabel('log interaction count') # we reduce the number of dots displayed.... we just want to see the shape subdata = np.array(list(set([float(int(d*100))/100 for d in data]))) try: normfit = sc_norm.pdf(subdata, np.nanmean(data), np.nanstd(data)) except AttributeError: normfit = sc_norm.pdf(subdata, np.mean(data), np.std(data)) ax2.plot(subdata, normfit, 'w.', markersize=2.5, alpha=.4) ax2.plot(subdata, normfit, 'k.', markersize=1.5, alpha=1) ax2.set_title('skew: %.3f, kurtosis: %.3f' % (skew(data), kurtosis(data))) try: ax4.vlines(range(size1), 0, evect[:,-1], color='k') except (TypeError, IndexError): pass ax4.hlines(0, 0, size2, color='red') ax4.set_ylabel('E1') ax4.set_yticklabels([]) try: ax5.vlines(range(size1), 0, evect[:,-2], color='k') except (TypeError, IndexError): pass ax5.hlines(0, 0, size2, color='red') ax5.set_ylabel('E2') ax5.set_yticklabels([]) try: ax6.vlines(range(size1), 0, evect[:,-3], color='k') except (TypeError, IndexError): pass ax6.hlines(0, 0, size2, color='red') ax6.set_ylabel('E3') ax6.set_yticklabels([]) xticklabels = ax4.get_xticklabels() + ax5.get_xticklabels() + ax6.get_xticklabels() plt.setp(xticklabels, visible=False) if savefig: tadbit_savefig(savefig) elif show: plt.show() plt.close('all') def plot_distance_vs_interactions(data, min_diff=1, max_diff=1000, show=False, genome_seq=None, resolution=None, axe=None, savefig=None, normalized=False, plot_each_cell=False): """ Plot the number of interactions observed versus the genomic distance between the mapped ends of the read. The slope is expected to be around -1, in logarithmic scale and between 700 kb and 10 Mb (according to the prediction of the fractal globule model). :param data: input file name (either tsv or TADbit generated BAM), or HiC_data object or list of lists :param 10 min_diff: lower limit (in number of bins) :param 1000 max_diff: upper limit (in number of bins) to look for :param 100 resolution: group reads that are closer than this resolution parameter :param_hash False plot_each_cell: if false, only the mean distances by bin will be represented, otherwise each pair of interactions will be plotted. :param None axe: a matplotlib.axes.Axes object to define the plot appearance :param None savefig: path to a file where to save the image generated; if None, the image will be shown using matplotlib GUI (the extension of the file name will determine the desired format). :returns: slope, intercept and R square of each of the 3 correlations """ if isinstance(data, basestring): resolution = resolution or 1 dist_intr = dict([(i, {}) for i in xrange(min_diff, max_diff)]) fhandler = open(data) line = fhandler.next() while line.startswith('#'): line = fhandler.next() try: while True: _, cr1, ps1, _, _, _, _, cr2, ps2, _ = line.split('\t', 9) if cr1 != cr2: line = fhandler.next() continue diff = abs(int(ps1) / resolution - int(ps2) / resolution) if max_diff > diff >= min_diff: try: dist_intr[diff][int(ps1) / resolution] += 1. except KeyError: dist_intr[diff][int(ps1) / resolution] = 1. line = fhandler.next() except StopIteration: pass fhandler.close() for diff in dist_intr: dist_intr[diff] = [dist_intr[diff].get(k, 0) for k in xrange(max(dist_intr[diff]) - diff)] elif isinstance(data, HiC_data): resolution = resolution or data.resolution dist_intr = dict([(i, []) for i in xrange(min_diff, max_diff)]) if normalized: get_data = lambda x, y: data[x, y] / data.bias[x] / data.bias[y] else: get_data = lambda x, y: data[x, y] max_diff = min(len(data), max_diff) if data.section_pos: for crm in data.section_pos: for diff in xrange(min_diff, min( (max_diff, 1 + data.chromosomes[crm]))): for i in xrange(data.section_pos[crm][0], data.section_pos[crm][1] - diff): dist_intr[diff].append(get_data(i, i + diff)) else: for diff in xrange(min_diff, max_diff): for i in xrange(len(data) - diff): if not np.isnan(data[i, i + diff]): dist_intr[diff].append(get_data(i, diff)) elif isinstance(data, dict): # if we pass decay/expected dictionary, computes weighted mean dist_intr = {} for i in range(min_diff, max_diff): val = [data[c][i] for c in data if i in data[c] and data[c][i] != data[c].get(i-1, 0)] if val: dist_intr[i] = [sum(val) / float(len(val))] else: dist_intr[i] = [0] else: dist_intr = dict([(i, []) for i in xrange(min_diff, max_diff)]) if genome_seq: max_diff = min(max(genome_seq.values()), max_diff) cnt = 0 for crm in genome_seq: for diff in xrange(min_diff, min( (max_diff, genome_seq[crm]))): for i in xrange(cnt, cnt + genome_seq[crm] - diff): if not np.isnan(data[i][i + diff]): dist_intr[diff].append(data[i][i + diff]) cnt += genome_seq[crm] else: max_diff = min(len(data), max_diff) for diff in xrange(min_diff, max_diff): for i in xrange(len(data) - diff): if not np.isnan(data[i][i + diff]): dist_intr[diff].append(data[i][i + diff]) resolution = resolution or 1 if not axe: fig=plt.figure() axe = fig.add_subplot(111) # remove last part of the plot in case no interaction is count... reduce max_dist for diff in xrange(max_diff - 1, min_diff, -1): try: if not dist_intr[diff]: del(dist_intr[diff]) max_diff -=1 continue except KeyError: max_diff -=1 continue break # get_cmap the mean values perc bins mean_intr = dict([(i, float(sum(dist_intr[i])) / len(dist_intr[i])) for i in dist_intr if len(dist_intr[i])]) if plot_each_cell: xp, yp = [], [] for x, y in sorted(dist_intr.items(), key=lambda x:x[0]): xp.extend([x] * len(y)) yp.extend(y) x = [] y = [] for k in xrange(len(xp)): if yp[k]: x.append(xp[k]) y.append(yp[k]) axe.plot(x, y, color='grey', marker='.', alpha=0.1, ms=1, linestyle='None') xp, yp = zip(*sorted(mean_intr.items(), key=lambda x:x[0])) x = [] y = [] for k in xrange(len(xp)): if yp[k]: x.append(xp[k]) y.append(yp[k]) axe.plot(x, y, 'k.', alpha=0.4) best = (float('-inf'), 0, 0, 0, 0, 0, 0, 0, 0, 0) logx = np.log(x) logy = np.log(y) ntries = 100 # set k for better fit # for k in xrange(1, ntries/5, ntries/5/5): if resolution == 1: k = 1 for i in xrange(3, ntries-2-k): v1 = i * len(x) / ntries try: a1, b1, r21, _, _ = linregress(logx[ :v1], logy[ :v1]) except ValueError: a1 = b1 = r21 = 0 r21 *= r21 for j in xrange(i + 1 + k, ntries - 2 - k): v2 = j * len(x) / ntries try: a2, b2, r22, _, _ = linregress(logx[v1+k:v2], logy[v1+k:v2]) a3, b3, r23, _, _ = linregress(logx[v2+k: ], logy[v2+k: ]) except ValueError: a2 = b2 = r22 = 0 a3 = b3 = r23 = 0 r2 = r21 + r22**2 + r23**2 if r2 > best[0]: best = (r2, v1, v2, a1, a2, a3, b1, b2, b3, k) # plot line of best fit (v1, v2, a1, a2, a3, b1, b2, b3, k) = best[1:] yfit1 = lambda xx: np.exp(b1 + a1*np.array (np.log(xx))) yfit2 = lambda xx: np.exp(b2 + a2*np.array (np.log(xx))) yfit3 = lambda xx: np.exp(b3 + a3*np.array (np.log(xx))) axe.plot(x[ :v1], yfit1(x[ :v1] ), color= 'yellow', lw=2, label = r'$\alpha_{%s}=%.2f$' % ( '0-0.7 \mathrm{ Mb}' if resolution != 1 else '1', a1)) #label = r'$\alpha_1=%.2f$ (0-%d)' % (a1, x[v1])) axe.plot(x[v1+k:v2], yfit2(x[v1+k:v2]), color= 'orange', lw=2, label = r'$\alpha_{%s}=%.2f$' % ( '0.7-10 \mathrm{ Mb}' if resolution != 1 else '2', a2)) # label = r'$\alpha_2=%.2f$ (%d-%d)' % (a2, x[v1], x[v2])) axe.plot(x[v2+k: ], yfit3(x[v2+k: ] ), color= 'red' , lw=2, label = r'$\alpha_{%s}=%.2f$' % ( '10 \mathrm{ Mb}-\infty' if resolution != 1 else '3', a3)) # label = r'$\alpha_3=%.2f$ (%d-$\infty$)' % (a3, x[v2+k])) else: # from 0.7 Mb v1 = 700000 / resolution # to 10 Mb v2 = 10000000 / resolution try: a1, b1, r21, _, _ = linregress(logx[ :v1], logy[ :v1]) except ValueError: a1, b1, r21 = 0, 0, 0 try: a2, b2, r22, _, _ = linregress(logx[v1:v2], logy[v1:v2]) except ValueError: a2, b2, r22 = 0, 0, 0 try: a3, b3, r23, _, _ = linregress(logx[v2: ], logy[v2: ]) except ValueError: a3, b3, r23 = 0, 0, 0 yfit1 = lambda xx: np.exp(b1 + a1*np.array (np.log(xx))) yfit2 = lambda xx: np.exp(b2 + a2*np.array (np.log(xx))) yfit3 = lambda xx: np.exp(b3 + a3*np.array (np.log(xx))) axe.plot(x[ :v1], yfit1(x[ :v1] ), color= 'yellow', lw=2, label = r'$\alpha_{%s}=%.2f$' % ( '0-0.7 \mathrm{ Mb}' if resolution != 1 else '1', a1)) #label = r'$\alpha_1=%.2f$ (0-%d)' % (a1, x[v1])) axe.plot(x[v1:v2], yfit2(x[v1:v2]), color= 'orange', lw=2, label = r'$\alpha_{%s}=%.2f$' % ( '0.7-10 \mathrm{ Mb}' if resolution != 1 else '2', a2)) # label = r'$\alpha_2=%.2f$ (%d-%d)' % (a2, x[v1], x[v2])) axe.plot(x[v2: ], yfit3(x[v2: ] ), color= 'red' , lw=2, label = r'$\alpha_{%s}=%.2f$' % ( '10 \mathrm{ Mb}-\infty' if resolution != 1 else '3', a3)) # label = r'$\alpha_3=%.2f$ (%d-$\infty$)' % (a3, x[v2+k])) axe.set_ylabel('Log interaction count') axe.set_xlabel('Log genomic distance (resolution: %s)' % nicer(resolution)) axe.legend(loc='lower left', frameon=False) axe.set_xscale('log') axe.set_yscale('log') axe.set_xlim((min_diff, max_diff)) try: axe.set_ylim((0, max(y))) except ValueError: pass if savefig: tadbit_savefig(savefig) plt.close('all') elif show: plt.show() plt.close('all') return (a1, b1, r21), (a2, b2, r22), (a3, b3, r23) def plot_iterative_mapping(fnam1, fnam2, total_reads=None, axe=None, savefig=None): """ Plots the number of reads mapped at each step of the mapping process (in the case of the iterative mapping, each step is mapping process with a given size of fragments). :param fnam: input file name :param total_reads: total number of reads in the initial FASTQ file :param None axe: a matplotlib.axes.Axes object to define the plot appearance :param None savefig: path to a file where to save the image generated; if None, the image will be shown using matplotlib GUI (the extension of the file name will determine the desired format). :returns: a dictionary with the number of reads per mapped length """ count_by_len = {} total_reads = total_reads or 1 if not axe: fig=plt.figure() _ = fig.add_subplot(111) colors = ['olive', 'darkcyan'] iteration = False for i, fnam in enumerate([fnam1, fnam2]): fhandler = open(fnam) line = fhandler.next() count_by_len[i] = {} while line.startswith('#'): if line.startswith('# MAPPED '): itr, num = line.split()[2:] count_by_len[i][int(itr)] = int(num) line = fhandler.next() if not count_by_len[i]: iteration = True try: while True: _, length, _, _ = line.rsplit('\t', 3) try: count_by_len[i][int(length)] += 1 except KeyError: count_by_len[i][int(length)] = 1 line = fhandler.next() except StopIteration: pass fhandler.close() lengths = sorted(count_by_len[i].keys()) for k in lengths[::-1]: count_by_len[i][k] += sum([count_by_len[i][j] for j in lengths if j < k]) plt.plot(lengths, [float(count_by_len[i][l]) / total_reads for l in lengths], label='read' + str(i + 1), linewidth=2, color=colors[i]) if iteration: plt.xlabel('read length (bp)') else: plt.xlabel('Iteration number') if total_reads != 1: plt.ylabel('Proportion of mapped reads') else: plt.ylabel('Number of mapped reads') plt.legend(loc=4) if savefig: tadbit_savefig(savefig) elif not axe: plt.show() plt.close('all') return count_by_len def fragment_size(fnam, savefig=None, nreads=None, max_size=99.9, axe=None, show=False, xlog=False, stats=('median', 'perc_max'), too_large=10000): """ Plots the distribution of dangling-ends lengths :param fnam: input file name :param None savefig: path where to store the output images. :param 99.9 max_size: top percentage of distances to consider, within the top 0.01% are usually found very long outliers. :param False xlog: represent x axis in logarithmic scale :param ('median', 'perc_max') stats: returns this set of values calculated from the distribution of insert/fragment sizes. Possible values are: - 'median' median of the distribution - 'mean' mean of the distribution - 'perc_max' percentil defined by the other parameter 'max_size' - 'first_deacay' starting from the median of the distribution to the first window where 10 consecutive insert sizes are counted less than a given value (this given value is equal to the sum of all sizes divided by 100 000) - 'MAD' Double Median Adjusted Deviation :param 10000 too_large: upper bound limit for fragment size to consider :param None nreads: number of reads to process (default: all reads) :returns: the median value and the percentile inputed as max_size. """ distr = {} genome_seq = OrderedDict() pos = 0 fhandler = open(fnam) for line in fhandler: if line.startswith('#'): if line.startswith('# CRM '): crm, clen = line[6:].split('\t') genome_seq[crm] = int(clen) else: break pos += len(line) fhandler.seek(pos) des = [] for line in fhandler: (crm1, pos1, dir1, _, re1, _, crm2, pos2, dir2, _, re2) = line.strip().split('\t')[1:12] if re1 == re2 and crm1 == crm2 and dir1 == '1' and dir2 == '0': pos1, pos2 = int(pos1), int(pos2) des.append(pos2 - pos1) if len(des) == nreads: break des = [i for i in des if i <= too_large] fhandler.close() if not des: raise Exception('ERROR: no dangling-ends found in %s' % (fnam)) max_perc = np.percentile(des, max_size) perc99 = np.percentile(des, 99) perc01 = np.percentile(des, 1) perc50 = np.percentile(des, 50) meanfr = np.mean(des) perc95 = np.percentile(des, 95) perc05 = np.percentile(des, 5) to_return = {'median': perc50} cutoff = len(des) / 100000. count = 0 for v in xrange(int(perc50), int(max(des))): if des.count(v) < cutoff: count += 1 else: count = 0 if count >= 10: to_return['first_decay'] = v - 10 break else: raise Exception('ERROR: not found') to_return['perc_max'] = max_perc to_return['MAD'] = mad(des) to_return['mean'] = meanfr if not savefig and not axe and not show: return [to_return[k] for k in stats] ax = setup_plot(axe, figsize=(10, 5.5)) desapan = ax.axvspan(perc95, perc99, facecolor='black', alpha=.2, label='1-99%% DEs\n(%.0f-%.0f nts)' % (perc01, perc99)) ax.axvspan(perc01, perc05, facecolor='black', alpha=.2) desapan = ax.axvspan(perc05, perc95, facecolor='black', alpha=.4, label='5-95%% DEs\n(%.0f-%.0f nts)' % (perc05, perc95)) deshist = ax.hist(des, bins=100, range=(0, max_perc), lw=2, alpha=.5, edgecolor='darkred', facecolor='darkred', label='Dangling-ends') ylims = ax.get_ylim() plots = [] ax.set_xlabel('Genomic distance between reads') ax.set_ylabel('Count') ax.set_title('Distribution of dangling-ends ' + 'lenghts\nmedian: %s (mean: %s), top %.1f%%: %0.f nts' % ( int(perc50), int(meanfr), max_size, int(max_perc))) if xlog: ax.set_xscale('log') ax.set_xlim((50, max_perc)) plt.subplots_adjust(left=0.1, right=0.75) ax.legend(bbox_to_anchor=(1.4, 1), frameon=False) if savefig: tadbit_savefig(savefig) elif show and not axe: plt.show() plt.close('all') return [to_return[k] for k in stats] def plot_genomic_distribution(fnam, first_read=None, resolution=10000, ylim=None, yscale=None, savefig=None, show=False, savedata=None, chr_names=None, nreads=None): """ Plot the number of reads in bins along the genome (or along a given chromosome). :param fnam: input file name :param True first_read: uses first read. :param 100 resolution: group reads that are closer than this resolution parameter :param None ylim: a tuple of lower and upper bound for the y axis :param None yscale: if set_bad to "log" values will be represented in log2 scale :param None savefig: path to a file where to save the image generated; if None, the image will be shown using matplotlib GUI (the extension of the file name will determine the desired format). :param None savedata: path where to store the output read counts per bin. :param None chr_names: can pass a list of chromosome names in case only some them the need to be plotted (this option may last even more than default) :param None nreads: number of reads to process (default: all reads) """ if first_read: warn('WARNING: first_read parameter should no loonger be used.') distr = {} genome_seq = OrderedDict() if chr_names: chr_names = set(chr_names) cond1 = lambda x: x not in chr_names else: cond1 = lambda x: False if nreads: cond2 = lambda x: x >= nreads else: cond2 = lambda x: False cond = lambda x, y: cond1(x) or cond2(y) count = 0 pos = 0 fhandler = open(fnam) for line in fhandler: if line.startswith('#'): if line.startswith('# CRM '): crm, clen = line[6:].split('\t') genome_seq[crm] = int(clen) else: break pos += len(line) fhandler.seek(pos) for line in fhandler: line = line.strip().split('\t') count += 1 for idx1, idx2 in ((1, 3), (7, 9)): crm, pos = line[idx1:idx2] if cond(crm, count): if cond2(count): break continue pos = int(pos) / resolution try: distr[crm][pos] += 1 except KeyError: try: distr[crm][pos] = 1 except KeyError: distr[crm] = {pos: 1} else: continue break fhandler.close() if savefig or show: _ = plt.figure(figsize=(15, 1 + 3 * len( chr_names if chr_names else distr.keys()))) max_y = max([max(distr[c].values()) for c in distr]) max_x = max([len(distr[c].values()) for c in distr]) ncrms = len(chr_names if chr_names else genome_seq if genome_seq else distr) data = {} for i, crm in enumerate(chr_names if chr_names else genome_seq if genome_seq else distr): try: # data[crm] = [distr[crm].get(j, 0) for j in xrange(max(distr[crm]))] # genome_seq[crm] data[crm] = [distr[crm].get(j, 0) for j in xrange(genome_seq[crm] / resolution + 1)] if savefig or show: plt.subplot(ncrms, 1, i + 1) plt.plot(range(genome_seq[crm] / resolution + 1), data[crm], color='red', lw=1.5, alpha=0.7) if yscale: plt.yscale(yscale) except KeyError: pass if savefig or show: if ylim: plt.vlines(genome_seq[crm] / resolution, ylim[0], ylim[1]) else: plt.vlines(genome_seq[crm] / resolution, 0, max_y) plt.xlim((0, max_x)) plt.ylim(ylim or (0, max_y)) plt.title(crm) if savefig: tadbit_savefig(savefig) if not show: plt.close('all') elif show: plt.show() if savedata: out = open(savedata, 'w') out.write('# CRM\tstart-end\tcount\n') out.write('\n'.join('%s\t%d-%d\t%d' % (c, (i * resolution) + 1, ((i + 1) * resolution), v) for c in data for i, v in enumerate(data[c]))) out.write('\n') out.close() def _unitize(vals): return np.argsort(vals) / float(len(vals)) def correlate_matrices(hic_data1, hic_data2, max_dist=10, intra=False, axe=None, savefig=None, show=False, savedata=None, min_dist=1, normalized=False, remove_bad_columns=True, **kwargs): """ Compare the interactions of two Hi-C matrices at a given distance, with Spearman rank correlation. Also computes the SCC reproducibility score as in HiCrep (see https://doi.org/10.1101/gr.220640.117). It's implementation is inspired by the version implemented in dryhic by Enrique Vidal (https://github.com/qenvio/dryhic). :param hic_data1: Hi-C-data object :param hic_data2: Hi-C-data object :param 1 resolution: to be used for scaling the plot :param 10 max_dist: maximum distance from diagonal (e.g. 10 mean we will not look further than 10 times the resolution) :param 1 min_dist: minimum distance from diagonal (set to 0 to reproduce result from HicRep) :param None savefig: path to save the plot :param False intra: only takes into account intra-chromosomal contacts :param False show: displays the plot :param False normalized: use normalized data :param True remove_bads: computes the union of bad columns between samples and exclude them from the comparison :returns: list of correlations, list of genomic distances, SCC and standard deviation of SCC """ spearmans = [] pearsons = [] dists = [] weigs = [] if normalized: get_the_guy1 = lambda i, j: (hic_data1[j, i] / hic_data1.bias[i] / hic_data1.bias[j]) get_the_guy2 = lambda i, j: (hic_data2[j, i] / hic_data2.bias[i] / hic_data2.bias[j]) else: get_the_guy1 = lambda i, j: hic_data1[j, i] get_the_guy2 = lambda i, j: hic_data2[j, i] if remove_bad_columns: # union of bad columns bads = hic_data1.bads.copy() bads.update(hic_data2.bads) if (intra and hic_data1.sections and hic_data2.sections and hic_data1.sections == hic_data2.sections): for dist in xrange(1, max_dist + 1): diag1 = [] diag2 = [] for crm in hic_data1.section_pos: for j in xrange(hic_data1.section_pos[crm][0], hic_data1.section_pos[crm][1] - dist): i = j + dist if j in bads or i in bads: continue diag1.append(get_the_guy1(i, j)) diag2.append(get_the_guy2(i, j)) spearmans.append(spearmanr(diag1, diag2)[0]) pearsons.append(spearmanr(diag1, diag2)[0]) r1 = _unitize(diag1) r2 = _unitize(diag2) weigs.append((np.var(r1, ddof=1) * np.var(r2, ddof=1))**0.5 * len(diag1)) dists.append(dist) else: if intra: warn('WARNING: hic_dta does not contain chromosome coordinates, ' + 'intra set to False') for dist in xrange(min_dist, max_dist + min_dist): diag1 = [] diag2 = [] for j in xrange(len(hic_data1) - dist): i = j + dist if j in bads or i in bads: continue diag1.append(get_the_guy1(i, j)) diag2.append(get_the_guy2(i, j)) spearmans.append(spearmanr(diag1, diag2)[0]) pearsons.append(pearsonr(diag1, diag2)[0]) r1 = _unitize(diag1) r2 = _unitize(diag2) weigs.append((np.var(r1, ddof=1) * np.var(r2, ddof=1))**0.5 * len(diag1)) dists.append(dist) # compute scc # print pearsons # print weigs tot_weigth = sum(weigs) scc = sum(pearsons[i] * weigs[i] / tot_weigth for i in xrange(len(pearsons))) var_corr = np.var(pearsons, ddof=1) std = (sum(weigs[i]**2 for i in xrange(len(pearsons))) * var_corr / sum(weigs)**2)**0.5 # plot if show or savefig or axe: if not axe: fig = plt.figure() axe = fig.add_subplot(111) given_axe = False else: given_axe = True axe.plot(dists, spearmans, color='orange', linewidth=3, alpha=.8) axe.set_xlabel('Genomic distance in bins') axe.set_ylabel('Spearman rank correlation') axe.set_xlim((0, dists[-1])) if savefig: tadbit_savefig(savefig) if show: plt.show() if not given_axe: plt.close('all') if savedata: out = open(savedata, 'w') out.write('# genomic distance\tSpearman rank correlation\n') for i in xrange(len(spearmans)): out.write('%s\t%s\n' % (dists[i], spearmans[i])) out.close() if kwargs.get('get_bads', False): return spearmans, dists, scc, std, bads return spearmans, dists, scc, std def _evec_dist(v1,v2): d1=np.dot(v1-v2,v1-v2) d2=np.dot(v1+v2,v1+v2) if d1<d2: d=d1 else: d=d2 return np.sqrt(d) def _get_Laplacian(M): S=M.sum(1) i_nz=np.where(S>0)[0] S=S[i_nz] M=(M[i_nz].T)[i_nz].T S=1/np.sqrt(S) M=S*M M=(S*M.T).T n=np.size(S) M=np.identity(n)-M M=(M+M.T)/2 return M def get_ipr(evec): ipr=1.0/(evec*evec*evec*evec).sum() return ipr def get_reproducibility(hic_data1, hic_data2, num_evec, verbose=True, normalized=False, remove_bad_columns=True): """ Compute reproducibility score similarly to HiC-spector (https://doi.org/10.1093/bioinformatics/btx152) :param hic_data1: Hi-C-data object :param hic_data2: Hi-C-data object :param 20 num_evec: number of eigenvectors to compare :returns: reproducibility score (bellow 0.5 ~ different cell types) """ M1 = hic_data1.get_matrix(normalized=normalized) M2 = hic_data2.get_matrix(normalized=normalized) if remove_bad_columns: # union of bad columns bads = hic_data1.bads.copy() bads.update(hic_data2.bads) # remove them form both matrices for bad in sorted(bads, reverse=True): del(M1[bad]) del(M2[bad]) for i in xrange(len(M1)): _ = M1[i].pop(bad) _ = M2[i].pop(bad) M1 = np.matrix(M1) M2 = np.matrix(M2) k1=np.sign(M1.A).sum(1) d1=np.diag(M1.A) kd1=~((k1==1)*(d1>0)) k2=np.sign(M2.A).sum(1) d2=np.diag(M2.A) kd2=~((k2==1)*(d2>0)) iz=np.nonzero((k1+k2>0)*(kd1>0)*(kd2>0))[0] M1b=(M1[iz].A.T)[iz].T M2b=(M2[iz].A.T)[iz].T i_nz1=np.where(M1b.sum(1)>0)[0] i_nz2=np.where(M2b.sum(1)>0)[0] i_z1=np.where(M1b.sum(1)==0)[0] i_z2=np.where(M2b.sum(1)==0)[0] M1b_L=_get_Laplacian(M1b) M2b_L=_get_Laplacian(M2b) a1, b1=eigsh(M1b_L,k=num_evec,which="SM") a2, b2=eigsh(M2b_L,k=num_evec,which="SM") b1_extend=np.zeros((np.size(M1b,0),num_evec)) b2_extend=np.zeros((np.size(M2b,0),num_evec)) for i in range(num_evec): b1_extend[i_nz1,i]=b1[:,i] b2_extend[i_nz2,i]=b2[:,i] ipr_cut=5 ipr1=np.zeros(num_evec) ipr2=np.zeros(num_evec) for i in range(num_evec): ipr1[i]=get_ipr(b1_extend[:,i]) ipr2[i]=get_ipr(b2_extend[:,i]) b1_extend_eff=b1_extend[:,ipr1>ipr_cut] b2_extend_eff=b2_extend[:,ipr2>ipr_cut] num_evec_eff=min(np.size(b1_extend_eff,1),np.size(b2_extend_eff,1)) evd=np.zeros(num_evec_eff) for i in range(num_evec_eff): evd[i]=_evec_dist(b1_extend_eff[:,i],b2_extend_eff[:,i]) Sd=evd.sum() l=np.sqrt(2) evs=abs(l-Sd/num_evec_eff)/l N = float(M1.shape[1]) if verbose: if (np.sum(ipr1>N/100)<=1)|(np.sum(ipr2>N/100)<=1): print("at least one of the maps does not look like typical Hi-C maps") else: print("size of maps: %d" %(np.size(M1,0))) print("reproducibility score: %6.3f " %(evs)) print("num_evec_eff: %d" %(num_evec_eff)) return evs def eig_correlate_matrices(hic_data1, hic_data2, nvect=6, normalized=False, savefig=None, show=False, savedata=None, remove_bad_columns=True, **kwargs): """ Compare the interactions of two Hi-C matrices using their 6 first eigenvectors, with Pearson correlation :param hic_data1: Hi-C-data object :param hic_data2: Hi-C-data object :param 6 nvect: number of eigenvectors to compare :param None savefig: path to save the plot :param False show: displays the plot :param False normalized: use normalized data :param True remove_bads: computes the union of bad columns between samples and exclude them from the comparison :param kwargs: any argument to pass to matplotlib imshow function :returns: matrix of correlations """ data1 = hic_data1.get_matrix(normalized=normalized) data2 = hic_data2.get_matrix(normalized=normalized) ## reduce matrices to remove bad columns if remove_bad_columns: # union of bad columns bads = hic_data1.bads.copy() bads.update(hic_data2.bads) # remove them form both matrices for bad in sorted(bads, reverse=True): del(data1[bad]) del(data2[bad]) for i in xrange(len(data1)): _ = data1[i].pop(bad) _ = data2[i].pop(bad) # get the log data1 = nozero_log(data1, np.log2) data2 = nozero_log(data2, np.log2) # get the eigenvectors ev1, evect1 = eigh(data1) ev2, evect2 = eigh(data2) corr = [[0 for _ in xrange(nvect)] for _ in xrange(nvect)] # sort eigenvectors according to their eigenvalues => first is last!! sort_perm = ev1.argsort() ev1.sort() evect1 = evect1[sort_perm] sort_perm = ev2.argsort() ev2.sort() evect2 = evect2[sort_perm] # calculate Pearson correlation for i in xrange(nvect): for j in xrange(nvect): corr[i][j] = abs(pearsonr(evect1[:,-i-1], evect2[:,-j-1])[0]) # plot axe = plt.axes([0.1, 0.1, 0.6, 0.8]) cbaxes = plt.axes([0.85, 0.1, 0.03, 0.8]) if show or savefig: im = axe.imshow(corr, interpolation="nearest",origin='lower', **kwargs) axe.set_xlabel('Eigen Vectors exp. 1') axe.set_ylabel('Eigen Vectors exp. 2') axe.set_xticks(range(nvect)) axe.set_yticks(range(nvect)) axe.set_xticklabels(range(1, nvect + 2)) axe.set_yticklabels(range(1, nvect + 2)) axe.xaxis.set_tick_params(length=0, width=0) axe.yaxis.set_tick_params(length=0, width=0) cbar = plt.colorbar(im, cax = cbaxes ) cbar.ax.set_ylabel('Pearson correlation', rotation=90*3, verticalalignment='bottom') axe2 = axe.twinx() axe2.set_yticks(range(nvect)) axe2.set_yticklabels(['%.1f' % (e) for e in ev2[-nvect:][::-1]]) axe2.set_ylabel('corresponding Eigen Values exp. 2', rotation=90*3, verticalalignment='bottom') axe2.set_ylim((-0.5, nvect - 0.5)) axe2.yaxis.set_tick_params(length=0, width=0) axe3 = axe.twiny() axe3.set_xticks(range(nvect)) axe3.set_xticklabels(['%.1f' % (e) for e in ev1[-nvect:][::-1]]) axe3.set_xlabel('corresponding Eigen Values exp. 1') axe3.set_xlim((-0.5, nvect - 0.5)) axe3.xaxis.set_tick_params(length=0, width=0) axe.set_ylim((-0.5, nvect - 0.5)) axe.set_xlim((-0.5, nvect - 0.5)) if savefig: tadbit_savefig(savefig) if show: plt.show() plt.close('all') if savedata: out = open(savedata, 'w') out.write('# ' + '\t'.join(['Eigen Vector %s'% i for i in xrange(nvect)]) + '\n') for i in xrange(nvect): out.write('\t'.join([str(corr[i][j]) for j in xrange(nvect)]) + '\n') out.close() if kwargs.get('get_bads', False): return corr, bads else: return corr def plot_rsite_reads_distribution(reads_file, outprefix, window=20, maxdist=1000): de_right={} de_left={} print "process reads" fl=open(reads_file) while True: line=fl.next() if not line.startswith('#'): break nreads=0 try: while True: nreads += 1 if nreads % 1000000 == 0: print nreads try: _, n1, sb1, sd1, l1, ru1, rd1, n2, sb2, sd2, l2, ru2, rd2\ = line.split() sb1, sd1, l1, ru1, rd1, sb2, sd2, l2, ru2, rd2 = \ map(int, [sb1, sd1, l1, ru1, rd1, sb2, sd2, l2, ru2, rd2]) except ValueError: print line raise ValueError("line is not the right format!") if n1 != n2: line=fl.next() continue #read1 ahead of read2 if sb1 > sb2: sb1, sd1, l1, ru1, rd1, sb2, sd2, l2, ru2, rd2 = \ sb2, sd2, l2, ru2, rd2, sb1, sd1, l1, ru1, rd1 #direction always -> <- if not (sd1 == 1 and sd2 == 0): line=fl.next() continue #close to the diagonal if sb2-sb1 > maxdist: line=fl.next() continue #close to RE 1 if abs(sb1-ru1) < abs(sb1-rd1): rc1=ru1 else: rc1=rd1 pos=sb1-rc1 if abs(pos)<=window: if not pos in de_right: de_right[pos]=0 de_right[pos]+=1 #close to RE 2 if abs(sb2-ru2) < abs(sb2-rd2): rc2=ru2 else: rc2=rd2 pos=sb2-rc2 if abs(pos)<=window: if not pos in de_left: de_left[pos]=0 de_left[pos]+=1 line=fl.next() except StopIteration: pass print " finished processing {} reads".format(nreads) #transform to arrays ind = range(-window,window+1) de_r = map(lambda x:de_right.get(x,0), ind) de_l = map(lambda x:de_left.get(x,0), ind) #write to files print "write to files" fl=open(outprefix+'_count.dat','w') fl.write('#dist\tX~~\t~~X\n') for i,j,k in zip(ind,de_r, de_l): fl.write('{}\t{}\t{}\n'.format(i, j, k)) #write plot rcParams.update({'font.size': 10}) pp = PdfPages(outprefix+'_plot.pdf') ind = np.array(ind) width = 1 pr = plt.bar(ind-0.5, de_r, width, color='r') pl = plt.bar(ind-0.5, de_l, width, bottom=de_r, color='b') plt.ylabel("Count") plt.title("Histogram of counts around cut site") plt.xticks(ind[::2], rotation="vertical") plt.legend((pl[0], pr[0]), ("~~X", "X~~")) plt.gca().set_xlim([-window-1,window+1]) pp.savefig() pp.close() def moving_average(a, n=3): ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n def plot_diagonal_distributions(reads_file, outprefix, ma_window=20, maxdist=800, de_left=[-2,3], de_right=[0,5]): rbreaks={} rejoined={} des={} print "process reads" fl=open(reads_file) while True: line=fl.next() if not line.startswith('#'): break nreads=0 try: while True: nreads += 1 if nreads % 1000000 == 0: print nreads try: _, n1, sb1, sd1, _, ru1, rd1, n2, sb2, sd2, _, ru2, rd2\ = line.split() sb1, sd1, ru1, rd1, sb2, sd2, ru2, rd2 = \ map(int, [sb1, sd1, ru1, rd1, sb2, sd2, ru2, rd2]) except ValueError: print line raise ValueError("line is not the right format!") if n1 != n2: line=fl.next() continue #read1 ahead of read2 if sb1 > sb2: sb1, sd1, ru1, rd1, sb2, sd2, ru2, rd2 = \ sb2, sd2, ru2, rd2, sb1, sd1, ru1, rd1 #direction always -> <- if not (sd1 == 1 and sd2 == 0): line=fl.next() continue mollen = sb2-sb1 if mollen > maxdist: line=fl.next() continue #DE1 if abs(sb1-ru1) < abs(sb1-rd1): rc1=ru1 else: rc1=rd1 pos=sb1-rc1 if pos in de_right: if not mollen in des: des[mollen]=0 des[mollen]+=1 line=fl.next() continue #DE2 if abs(sb2-ru2) < abs(sb2-rd2): rc2=ru2 else: rc2=rd2 pos=sb2-rc2 if pos in de_left: if not mollen in des: des[mollen]=0 des[mollen]+=1 line=fl.next() continue #random: map on same fragment if rd1 == rd2: if not mollen in rbreaks: rbreaks[mollen]=0 rbreaks[mollen]+=1 line=fl.next() continue #rejoined ends if not mollen in rejoined: rejoined[mollen]=0 rejoined[mollen]+=1 line=fl.next() except StopIteration: pass print " finished processing {} reads".format(nreads) #transform to arrays maxlen = max(max(rejoined),max(des),max(rbreaks)) ind = range(1,maxlen+1) des = map(lambda x:des.get(x,0), ind) rbreaks = map(lambda x:rbreaks.get(x,0), ind) rejoined = map(lambda x:rejoined.get(x,0), ind) #reweight corner for rejoined rejoined = map(lambda x: x**.5 * rejoined[x-1]/x, ind) #write to files print "write to files" fl=open(outprefix+'_count.dat','w') fl.write('#dist\trbreaks\tdes\trejoined\n') for i,j,k,l in zip(ind,rbreaks,des,rejoined): fl.write('{}\t{}\t{}\t{}\n'.format(i, j, k, l)) #transform data a bit more ind, des, rbreaks, rejoined = \ map(lambda x: moving_average(np.array(x), ma_window), [ind, des, rbreaks, rejoined]) des, rbreaks, rejoined = map(lambda x:x/float(x.sum()), [des, rbreaks, rejoined]) np.insert(ind,0,0) np.insert(des,0,0) np.insert(rbreaks,0,0) np.insert(rejoined,0,0) #write plot pp = PdfPages(outprefix+'_plot.pdf') rcParams.update({'font.size': 10}) pde = plt.fill_between(ind, des, 0, color='r', alpha=0.5) prb = plt.fill_between(ind, rbreaks, 0, color='b', alpha=0.5) prj = plt.fill_between(ind, rejoined, 0, color='y', alpha=0.5) plt.ylabel("Normalized count") plt.ylabel("Putative DNA molecule length") plt.title("Histogram of counts close to the diagonal") #plt.xticks(ind[::10], rotation="vertical") plt.legend((prb, pde, prj), ("Random breaks", "Dangling ends", "Rejoined")) plt.gca().set_xlim([0,maxlen]) pp.savefig() pp.close() def plot_strand_bias_by_distance(fnam, nreads=1000000, valid_pairs=True, half_step=20, half_len=2000, full_step=500, full_len=50000, savefig=None): """ Classify reads into four categories depending on the strand on which each of its end is mapped, and plots the proportion of each of these categories in function of the genomic distance between them. Only full mapped reads mapped on two diferent restriction fragments (still same chromosome) are considered. The four categories are: - Both read-ends mapped on the same strand (forward) - Both read-ends mapped on the same strand (reverse) - Both read-ends mapped on the different strand (facing), like extra-dangling-ends - Both read-ends mapped on the different strand (opposed), like extra-self-circles :params fnam: path to tsv file with intersection of mapped ends :params True valid_pairs: consider only read-ends mapped on different restriction fragments. If False, considers only read-ends mapped on the same restriction fragment. :params 1000000 nreads: number of reads used to plot (if None, all will be used) :params 20 half_step: binning for the first part of the plot :params 2000 half_len: maximum distance for the first part of the plot :params 500 full_step: binning for the second part of the plot :params 50000 full_len: maximum distance for the second part of the plot :params None savefig: path to save figure """ max_len = 100000 genome_seq = OrderedDict() pos = 0 fhandler = open(fnam) for line in fhandler: if line.startswith('#'): if line.startswith('# CRM '): crm, clen = line[6:].split('\t') genome_seq[crm] = int(clen) else: break pos += len(line) fhandler.seek(pos) names = ['<== <== both reverse', '<== ==> opposed (Extra-self-circles)', '==> <== facing (Extra-dangling-ends)', '==> ==> both forward'] dirs = [[0 for i in range(max_len)], [0 for i in range(max_len)], [0 for i in range(max_len)], [0 for i in range(max_len)]] iterator = (fhandler.next() for _ in xrange(nreads)) if nreads else fhandler if valid_pairs: comp_re = lambda x, y: x != y else: comp_re = lambda x, y: x == y for line in iterator: (crm1, pos1, dir1, len1, re1, _, crm2, pos2, dir2, len2, re2) = line.strip().split('\t')[1:12] pos1, pos2 = int(pos1), int(pos2) if pos2 < pos1: pos2, pos1 = pos1, pos2 dir2, dir1 = dir1, dir2 len2, len1 = len1, len2 dir1, dir2 = int(dir1), int(dir2) len1, len2 = int(len1), int(len2) if dir1 == 0: pos1 -= len1 if dir2 == 1: pos2 += len2 diff = pos2 - pos1 # only ligated; same chromsome; bellow max_dist; not multi-contact if comp_re(re1, re2) and crm1 == crm2 and diff < max_len and len1 == len2: dir1, dir2 = dir1 * 2, dir2 dirs[dir1 + dir2][diff] += 1 sum_dirs = [0 for i in range(max_len)] for i in range(max_len): sum_dir = float(sum(dirs[d][i] for d in range(4))) for d in range(4): try: dirs[d][i] = dirs[d][i] / sum_dir except ZeroDivisionError: dirs[d][i] = 0. sum_dirs[i] = sum_dir plt.figure(figsize=(14, 9)) if full_step: axLp = plt.subplot2grid((3, 2), (0, 0), rowspan=2) axLb = plt.subplot2grid((3, 2), (2, 0), sharex=axLp) axRp = plt.subplot2grid((3, 2), (0, 1), rowspan=2, sharey=axLp) axRb = plt.subplot2grid((3, 2), (2, 1), sharex=axRp, sharey=axLb) else: axLp = plt.subplot2grid((3, 1), (0, 0), rowspan=2) axLb = plt.subplot2grid((3, 1), (2, 0), sharex=axLp) for d in range(4): axLp.plot([sum(dirs[d][i:i + half_step]) / half_step for i in range(0, half_len - half_step, half_step)], alpha=0.7, label=names[d]) axLp.set_ylim(0, 1) axLp.set_yticks([0, 0.25, 0.5, 0.75, 1]) axLp.set_xlim(0, half_len / half_step) axLp.set_xticks(axLp.get_xticks()[:-1]) axLp.set_xticklabels([str(int(i)) for i in axLp.get_xticks() * half_step]) axLp.grid() if full_step: axLp.spines['right'].set_visible(False) plt.setp(axLp.get_xticklabels(), visible=False) axLb.spines['right'].set_visible(False) axLp.set_ylabel('Proportion of reads in each category') axLb.bar(range(0, half_len / half_step - 1), [sum(sum_dirs[i:i + half_step]) / half_step for i in range(0, half_len - half_step, half_step)], alpha=0.5, color='k') axLb.set_ylabel("Log number of reads\nper genomic position") axLb.set_yscale('log') axLb.grid() axLb.set_xlabel('Distance between mapping position of the two ends\n' '(averaged in windows of 20 nucleotides)') if full_step: for d in range(4): axRp.plot([sum(dirs[d][i:i + full_step]) / full_step for i in range(half_len, full_len + full_step, full_step)], alpha=0.7, label=names[d]) axRp.spines['left'].set_visible(False) axRp.set_xlim(0, full_len / full_step - 2000 / full_step) axRp.set_xticks(range((10000 - half_step) / full_step, (full_len + full_step) / full_step, 20)) axRp.set_xticklabels([int(i) for i in range(10000, full_len + full_step, full_step * 20)]) plt.setp(axRp.get_xticklabels(), visible=False) axRp.legend(title='Strand on which each read-end is mapped\n(first read-end is always smaller than second)') axRp.yaxis.tick_right() axRp.tick_params(labelleft=False) axRp.tick_params(labelright=False) axRp.grid() axRb.bar(range(0, full_len / full_step - half_len / full_step + 1), [sum(sum_dirs[i:i + full_step]) / full_step for i in range(half_len, full_len + full_step, full_step)], alpha=0.5, color='k') axRb.set_ylim(0, max(sum_dirs) * 1.1) axRb.spines['left'].set_visible(False) axRb.yaxis.tick_right() axRb.tick_params(labelleft=False) axRb.tick_params(labelright=False) axRb.set_xlabel('Distance between mapping position of the two ends\n' '(averaged in windows of 500 nucleotide)') axRb.set_yscale('log') axRb.grid() # decorate... d = .015 # how big to make the diagonal lines in axes coordinates # arguments to pass to plot, just so we don't keep repeating them kwargs = dict(transform=axLp.transAxes, color='k', clip_on=False) axLp.plot((1 - d, 1 + d), (1-d, 1+d), **kwargs) # top-left diagonal axLp.plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal kwargs.update(transform=axRp.transAxes) # switch to the bottom axes axRp.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal axRp.plot((-d, +d), (-d, +d), **kwargs) # bottom-right diagonal w = .015 h = .030 # arguments to pass to plot, just so we don't keep repeating them kwargs = dict(transform=axLb.transAxes, color='k', clip_on=False) axLb.plot((1 - w, 1 + w), (1 - h, 1 + h), **kwargs) # top-left diagonal axLb.plot((1 - w, 1 + w), ( - h, + h), **kwargs) # top-right diagonal kwargs.update(transform=axRb.transAxes) # switch to the bottom axes axRb.plot((- w, + w), (1 - h, 1 + h), **kwargs) # bottom-left diagonal axRb.plot((- w, + w), ( - h, + h), **kwargs) # bottom-right diagonal plt.subplots_adjust(wspace=0.05) plt.subplots_adjust(hspace=0.1) else: axLp.legend(title='Strand on which each read-end is mapped\n(first read-end is always smaller than second)') if savefig: tadbit_savefig(savefig) else: plt.show() # For back compatibility def insert_sizes(fnam, savefig=None, nreads=None, max_size=99.9, axe=None, show=False, xlog=False, stats=('median', 'perc_max'), too_large=10000): """ Deprecated function, use fragment_size """ warn("WARNING: function has been replaced by fragment_size", category=DeprecationWarning,) return fragment_size(fnam, savefig=savefig, nreads=nreads, max_size=max_size, axe=axe, show=show, xlog=xlog, stats=stats, too_large=too_large)
gpl-3.0
-8,409,796,578,718,925,000
39.094194
124
0.531199
false
3.317435
false
false
false
opennode/nodeconductor
waldur_core/monitoring/serializers.py
1
1672
from collections import defaultdict from rest_framework import serializers from .models import ResourceItem, ResourceSla from .utils import get_period, to_list class ResourceSlaStateTransitionSerializer(serializers.Serializer): timestamp = serializers.IntegerField() state = serializers.SerializerMethodField() def get_state(self, obj): return obj.state and 'U' or 'D' class MonitoringSerializerMixin(serializers.Serializer): sla = serializers.SerializerMethodField() monitoring_items = serializers.SerializerMethodField() class Meta: fields = ('sla', 'monitoring_items') def get_sla(self, resource): if not hasattr(self, 'sla_map_cache'): self.sla_map_cache = {} request = self.context['request'] items = ResourceSla.objects.filter(scope__in=to_list(self.instance)) items = items.filter(period=get_period(request)) for item in items: self.sla_map_cache[item.object_id] = dict( value=item.value, agreed_value=item.agreed_value, period=item.period ) return self.sla_map_cache.get(resource.id) def get_monitoring_items(self, resource): if not hasattr(self, 'monitoring_items_map'): self.monitoring_items_map = {} items = ResourceItem.objects.filter(scope__in=to_list(self.instance)) self.monitoring_items_map = defaultdict(dict) for item in items: self.monitoring_items_map[item.object_id][item.name] = item.value return self.monitoring_items_map.get(resource.id)
mit
9,157,306,062,313,611,000
33.122449
81
0.641746
false
4.098039
false
false
false
Bdanilko/EdPy
src/lib/token_bits.py
1
2356
#!/usr/bin/env python2 # * **************************************************************** ** # File: token_bits.py # Requires: Python 2.7+ (but not Python 3.0+) # Note: For history, changes and dates for this file, consult git. # Author: Brian Danilko, Likeable Software (brian@likeablesoftware.com) # Copyright 2015-2017 Microbric Pty Ltd. # # 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 (in the doc/licenses directory) # for more details. # # * **************************************************************** */ """Contains definitions for bits in the token modules. Typically STATUS bits are masks, and CONTROL bits are bit numbers (to be used with setbit) """ STATUS_LINE_OVER_LINE = 1 STATUS_LINE_CHANGED = 2 CONTROL_LINE_POWER = 1 CONTROL_LED_POWER = 1 STATUS_MOTOR_STRAIN = 1 STATUS_MOTOR_DISTANCE = 2 CONTROL_MOTOR_SPEED_MASK = 0x0f CONTROL_MOTOR_REMAIN_GOING = 4 CONTROL_MOTOR_CMD_MASK = 0xe0 STATUS_IRX_BILL_RECEIVED = 0x01 STATUS_IRX_MATCHED = 0x02 STATUX_IRX_CHECK_VALID = 0x04 STATUS_IRX_OBS_RIGHT = 0x08 STATUS_IRX_OBS_CENTRE = 0x10 STATUS_IRX_OBS_LEFT = 0x20 STATUS_IRX_OBS_DETECTED = 0x40 CONTROL_IRX_DO_CHECK = 0 STATUS_BEEP_TUNE_DONE = 0x01 STATUS_BEEP_TONE_DONE = 0x02 STATUS_BEEP_CLAP_DETECTED = 0x04 STATUS_BEEP_TS_ERROR = 0x08 CONTROL_BEEP_PLAY_CODED_TUNE = 0 CONTROL_BEEP_PLAY_TONE = 1 CONTROL_BEEP_PLAY_BEEP = 2 CONTROL_BEEP_PLAY_STRING_TUNE = 3 CONTROL_ITX_TRANSMIT_CHAR = 0 CONTROL_ITX_DO_OBSTACLE_DETECT = 1 CONTROL_INDEX_WRITE_16BIT = 1 CONTROL_INDEX_READ_16BIT = 2 CONTROL_INDEX_WRITE_8BIT = 5 CONTROL_INDEX_READ_8BIT = 6 STATUS_DEVICE_BUTTON_1 = 0x08 STATUS_DEVICE_BUTTON_2 = 0x04 STATUS_DEVICE_BUTTON_3 = 0x02 STATUS_DEVICE_BUTTON_4 = 0x01 STATUS_TIMER_ONE_SHOT_EXPIRED = 0x01 STATUS_TIMER_ONE_SHOT_RUNNING = 0x02 CONTROL_TIMER_TRIGGER_ONE_SHOT = 0 CONTROL_TIMER_TRIGGER_PAUSE = 1 CONTROL_TIMER_ENABLE_SLEEP = 2
gpl-2.0
-8,631,692,526,637,044,000
30.837838
71
0.688879
false
2.959799
false
false
false
andy-sweet/fcdiff
doc/drawio.py
1
1945
#!/usr/bin/python import os import subprocess as sp import shutil as sh import argparse parser = argparse.ArgumentParser( description = 'Copies and converts drawio XML and PDF files from Dropbox' ) parser.add_argument('-s', '--src_dir', help = 'The src directory containing the drawio XML and PDF files', default = '/Users/sweet/Dropbox/Apps/drawio' ) parser.add_argument('-v', '--verbose', help = 'Specify this to get verbose output', action = 'store_true', default = False ) args = parser.parse_args() if not os.path.isdir(args.src_dir): raise IOError('Source directory ' + args.src_dir + ' is not a directory') # top level destination is the same as this file dst_dir = os.path.dirname(os.path.realpath(__file__)) # edit these to copy/convert files file_pre = 'fcdiff' file_dict = { 'methods' : ( 'graphical_model', 'graphical_model_rt', 'graphical_model_all', ), } for sub_dir, sub_files in file_dict.items(): sub_dst_dir = os.path.join(dst_dir, sub_dir) for fs in sub_files: src_stem = os.path.join(args.src_dir, file_pre + '-' + sub_dir + '-' + fs) dst_stem = os.path.join(sub_dst_dir, fs) if args.verbose: print('Copying XMl source to destination') xml_src = src_stem + '.xml' xml_dst = dst_stem + '.xml' if not os.path.isfile(xml_src): raise IOError('Could not find drawio XML file ' + xml_src) sh.copy2(xml_src, xml_dst) if args.verbose: print('Copying PDF source to destination') pdf_src = src_stem + '.pdf' pdf_dst = dst_stem + '.pdf' if not os.path.isfile(pdf_src): raise IOError('Could not find drawio PDF file ' + pdf_src) sh.copy2(pdf_src, pdf_dst) if args.verbose: print('Converting PDF to SVG') svg_dst = dst_stem + '.svg' sp.check_call(['pdf2svg', pdf_dst, svg_dst])
mit
-1,236,257,339,607,147,800
28.469697
82
0.60874
false
3.330479
false
false
false
sillvan/hyperspy
hyperspy/model.py
1
78500
# -*- coding: utf-8 -*- # Copyright 2007-2011 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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. # # HyperSpy 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 HyperSpy. If not, see <http://www.gnu.org/licenses/>. import copy import os import tempfile import warnings import numbers import numpy as np import scipy.odr as odr from scipy.optimize import (leastsq, fmin, fmin_cg, fmin_ncg, fmin_bfgs, fmin_l_bfgs_b, fmin_tnc, fmin_powell) from traits.trait_errors import TraitError from hyperspy import messages import hyperspy.drawing.spectrum from hyperspy.drawing.utils import on_figure_window_close from hyperspy.misc import progressbar from hyperspy._signals.eels import Spectrum from hyperspy.defaults_parser import preferences from hyperspy.axes import generate_axis from hyperspy.exceptions import WrongObjectError from hyperspy.decorators import interactive_range_selector from hyperspy.misc.mpfit.mpfit import mpfit from hyperspy.axes import AxesManager from hyperspy.drawing.widgets import (DraggableVerticalLine, DraggableLabel) from hyperspy.gui.tools import ComponentFit from hyperspy.component import Component from hyperspy.signal import Signal class Model(list): """One-dimensional model and data fitting. A model is constructed as a linear combination of :mod:`components` that are added to the model using :meth:`append` or :meth:`extend`. There are many predifined components available in the in the :mod:`components` module. If needed, new components can easyly created using the code of existing components as a template. Once defined, the model can be fitted to the data using :meth:`fit` or :meth:`multifit`. Once the optimizer reaches the convergence criteria or the maximum number of iterations the new value of the component parameters are stored in the components. It is possible to access the components in the model by their name or by the index in the model. An example is given at the end of this docstring. Attributes ---------- spectrum : Spectrum instance It contains the data to fit. chisq : A Signal of floats Chi-squared of the signal (or np.nan if not yet fit) dof : A Signal of integers Degrees of freedom of the signal (0 if not yet fit) red_chisq Methods ------- append Append one component to the model. extend Append multiple components to the model. remove Remove component from model. as_signal Generate a Spectrum instance (possible multidimensional) from the model. store_current_values Store the value of the parameters at the current position. fetch_stored_values Fetch stored values of the parameters. update_plot Force a plot update. (In most cases the plot should update automatically.) set_signal_range, remove_signal range, reset_signal_range, add signal_range. Customize the signal range to fit. fit, multifit Fit the model to the data at the current position or the full dataset. save_parameters2file, load_parameters_from_file Save/load the parameter values to/from a file. plot Plot the model and the data. enable_plot_components, disable_plot_components Plot each component separately. (Use after `plot`.) set_current_values_to Set the current value of all the parameters of the given component as the value for all the dataset. export_results Save the value of the parameters in separate files. plot_results Plot the value of all parameters at all positions. print_current_values Print the value of the parameters at the current position. enable_adjust_position, disable_adjust_position Enable/disable interactive adjustment of the position of the components that have a well defined position. (Use after `plot`). fit_component Fit just the given component in the given signal range, that can be set interactively. set_parameters_not_free, set_parameters_free Fit the `free` status of several components and parameters at once. set_parameters_value Set the value of a parameter in components in a model to a specified value. Examples -------- In the following example we create a histogram from a normal distribution and fit it with a gaussian component. It demonstrates how to create a model from a :class:`~._signals.spectrum.Spectrum` instance, add components to it, adjust the value of the parameters of the components, fit the model to the data and access the components in the model. >>> s = signals.Spectrum( np.random.normal(scale=2, size=10000)).get_histogram() >>> g = components.Gaussian() >>> m = s.create_model() >>> m.append(g) >>> m.print_current_values() Components Parameter Value Gaussian sigma 1.000000 A 1.000000 centre 0.000000 >>> g.centre.value = 3 >>> m.print_current_values() Components Parameter Value Gaussian sigma 1.000000 A 1.000000 centre 3.000000 >>> g.sigma.value 1.0 >>> m.fit() >>> g.sigma.value 1.9779042300856682 >>> m[0].sigma.value 1.9779042300856682 >>> m["Gaussian"].centre.value -0.072121936813224569 """ _firstimetouch = True def __hash__(self): # This is needed to simulate a hashable object so that PySide does not # raise an exception when using windows.connect return id(self) def __init__(self, spectrum): self.convolved = False self.spectrum = spectrum self.axes_manager = self.spectrum.axes_manager self.axis = self.axes_manager.signal_axes[0] self.axes_manager.connect(self.fetch_stored_values) self.free_parameters_boundaries = None self.channel_switches = np.array([True] * len(self.axis.axis)) self._low_loss = None self._position_widgets = [] self._plot = None self._model_line = None self.chisq = spectrum._get_navigation_signal() self.chisq.change_dtype("float") self.chisq.data.fill(np.nan) self.chisq.metadata.General.title = \ self.spectrum.metadata.General.title + ' chi-squared' self.dof = self.chisq._deepcopy_with_new_data( np.zeros_like( self.chisq.data, dtype='int')) self.dof.metadata.General.title = \ self.spectrum.metadata.General.title + ' degrees of freedom' self._suspend_update = False self._adjust_position_all = None self._plot_components = False def __repr__(self): return u"<Model %s>".encode('utf8') % super(Model, self).__repr__() def _get_component(self, object): if isinstance(object, int) or isinstance(object, basestring): object = self[object] elif not isinstance(object, Component): raise ValueError("Not a component or component id.") if object in self: return object else: raise ValueError("The component is not in the model.") def insert(self): raise NotImplementedError @property def spectrum(self): return self._spectrum @spectrum.setter def spectrum(self, value): if isinstance(value, Spectrum): self._spectrum = value else: raise WrongObjectError(str(type(value)), 'Spectrum') @property def low_loss(self): return self._low_loss @low_loss.setter def low_loss(self, value): if value is not None: if (value.axes_manager.navigation_shape != self.spectrum.axes_manager.navigation_shape): raise ValueError('The low-loss does not have ' 'the same navigation dimension as the ' 'core-loss') self._low_loss = value self.set_convolution_axis() self.convolved = True else: self._low_loss = value self.convolution_axis = None self.convolved = False # Extend the list methods to call the _touch when the model is modified def append(self, object): # Check if any of the other components in the model has the same name if object in self: raise ValueError("Component already in model") component_name_list = [] for component in self: component_name_list.append(component.name) name_string = "" if object.name: name_string = object.name else: name_string = object._id_name if name_string in component_name_list: temp_name_string = name_string index = 0 while temp_name_string in component_name_list: temp_name_string = name_string + "_" + str(index) index += 1 name_string = temp_name_string object.name = name_string object._axes_manager = self.axes_manager object._create_arrays() list.append(self, object) object.model = self self._touch() if self._plot_components: self._plot_component(object) if self._adjust_position_all is not None: self._make_position_adjuster(object, self._adjust_position_all[0], self._adjust_position_all[1]) def extend(self, iterable): for object in iterable: self.append(object) def __delitem__(self, object): list.__delitem__(self, object) object.model = None self._touch() def remove(self, object, touch=True): """Remove component from model. Examples -------- >>> s = signals.Spectrum(np.empty(1)) >>> m = s.create_model() >>> g = components.Gaussian() >>> m.append(g) You could remove `g` like this >>> m.remove(g) Like this: >>> m.remove("Gaussian") Or like this: >>> m.remove(0) """ object = self._get_component(object) for pw in self._position_widgets: if hasattr(pw, 'component') and pw.component is object: pw.component._position.twin = None del pw.component pw.close() del pw if hasattr(object, '_model_plot_line'): line = object._model_plot_line line.close() del line idx = self.index(object) self.spectrum._plot.signal_plot.ax_lines.remove( self.spectrum._plot.signal_plot.ax_lines[2 + idx]) list.remove(self, object) object.model = None if touch is True: self._touch() if self._plot_active: self.update_plot() def _touch(self): """Run model setup tasks This function is called everytime that we add or remove components from the model. """ if self._plot_active is True: self._connect_parameters2update_plot() __touch = _touch def set_convolution_axis(self): """ Creates an axis to use to generate the data of the model in the precise scale to obtain the correct axis and origin after convolution with the lowloss spectrum. """ ll_axis = self.low_loss.axes_manager.signal_axes[0] dimension = self.axis.size + ll_axis.size - 1 step = self.axis.scale knot_position = ll_axis.size - ll_axis.value2index(0) - 1 self.convolution_axis = generate_axis(self.axis.offset, step, dimension, knot_position) def _connect_parameters2update_plot(self): if self._plot_active is False: return for i, component in enumerate(self): component.connect( self._model_line.update) for parameter in component.parameters: parameter.connect(self._model_line.update) if self._plot_components is True: self._connect_component_lines() def _disconnect_parameters2update_plot(self): if self._model_line is None: return for component in self: component.disconnect(self._model_line.update) for parameter in component.parameters: parameter.disconnect(self._model_line.update) if self._plot_components is True: self._disconnect_component_lines() def as_signal(self, component_list=None, out_of_range_to_nan=True, show_progressbar=None): """Returns a recreation of the dataset using the model. the spectral range that is not fitted is filled with nans. Parameters ---------- component_list : list of hyperspy components, optional If a list of components is given, only the components given in the list is used in making the returned spectrum. The components can be specified by name, index or themselves. out_of_range_to_nan : bool If True the spectral range that is not fitted is filled with nans. show_progressbar : None or bool If True, display a progress bar. If None the default is set in `preferences`. Returns ------- spectrum : An instance of the same class as `spectrum`. Examples -------- >>> s = signals.Spectrum(np.random.random((10,100))) >>> m = s.create_model() >>> l1 = components.Lorentzian() >>> l2 = components.Lorentzian() >>> m.append(l1) >>> m.append(l2) >>> s1 = m.as_signal() >>> s2 = m.as_signal(component_list=[l1]) """ # change actual values to whatever except bool _multi_on_ = '_multi_on_' _multi_off_ = '_multi_off_' if show_progressbar is None: show_progressbar = preferences.General.show_progressbar if component_list: component_list = [self._get_component(x) for x in component_list] active_state = [] for component_ in self: if component_.active_is_multidimensional: if component_ not in component_list: active_state.append(_multi_off_) component_._toggle_connect_active_array(False) component_.active = False else: active_state.append(_multi_on_) else: active_state.append(component_.active) if component_ in component_list: component_.active = True else: component_.active = False data = np.empty(self.spectrum.data.shape, dtype='float') data.fill(np.nan) if out_of_range_to_nan is True: channel_switches_backup = copy.copy(self.channel_switches) self.channel_switches[:] = True maxval = self.axes_manager.navigation_size pbar = progressbar.progressbar(maxval=maxval, disabled=not show_progressbar) i = 0 for index in self.axes_manager: self.fetch_stored_values(only_fixed=False) data[self.axes_manager._getitem_tuple][ self.channel_switches] = self.__call__( non_convolved=not self.convolved, onlyactive=True) i += 1 if maxval > 0: pbar.update(i) pbar.finish() if out_of_range_to_nan is True: self.channel_switches[:] = channel_switches_backup spectrum = self.spectrum.__class__( data, axes=self.spectrum.axes_manager._get_axes_dicts()) spectrum.metadata.General.title = ( self.spectrum.metadata.General.title + " from fitted model") spectrum.metadata.Signal.binned = self.spectrum.metadata.Signal.binned if component_list: for component_ in self: active_s = active_state.pop(0) if isinstance(active_s, bool): component_.active = active_s else: if active_s == _multi_off_: component_._toggle_connect_active_array(True) return spectrum @property def _plot_active(self): if self._plot is not None and self._plot.is_active() is True: return True else: return False def _set_p0(self): self.p0 = () for component in self: if component.active: for parameter in component.free_parameters: self.p0 = (self.p0 + (parameter.value,) if parameter._number_of_elements == 1 else self.p0 + parameter.value) def set_boundaries(self): """Generate the boundary list. Necessary before fitting with a boundary aware optimizer. """ self.free_parameters_boundaries = [] for component in self: if component.active: for param in component.free_parameters: if param._number_of_elements == 1: self.free_parameters_boundaries.append(( param._bounds)) else: self.free_parameters_boundaries.extend(( param._bounds)) def set_mpfit_parameters_info(self): self.mpfit_parinfo = [] for component in self: if component.active: for param in component.free_parameters: limited = [False, False] limits = [0, 0] if param.bmin is not None: limited[0] = True limits[0] = param.bmin if param.bmax is not None: limited[1] = True limits[1] = param.bmax if param._number_of_elements == 1: self.mpfit_parinfo.append( {'limited': limited, 'limits': limits}) else: self.mpfit_parinfo.extend(( {'limited': limited, 'limits': limits},) * param._number_of_elements) def store_current_values(self): """ Store the parameters of the current coordinates into the parameters array. If the parameters array has not being defined yet it creates it filling it with the current parameters.""" for component in self: if component.active: component.store_current_parameters_in_map() def fetch_stored_values(self, only_fixed=False): """Fetch the value of the parameters that has been previously stored. Parameters ---------- only_fixed : bool If True, only the fixed parameters are fetched. See Also -------- store_current_values """ switch_aap = self._plot_active is not False if switch_aap is True: self._disconnect_parameters2update_plot() for component in self: component.fetch_stored_values(only_fixed=only_fixed) if switch_aap is True: self._connect_parameters2update_plot() self.update_plot() def update_plot(self, *args, **kwargs): """Update model plot. The updating can be suspended using `suspend_update`. See Also -------- suspend_update resume_update """ if self._plot_active is True and self._suspend_update is False: try: self._update_model_line() for component in [component for component in self if component.active is True]: self._update_component_line(component) except: self._disconnect_parameters2update_plot() def suspend_update(self): """Prevents plot from updating until resume_update() is called See Also -------- resume_update update_plot """ if self._suspend_update is False: self._suspend_update = True self._disconnect_parameters2update_plot() else: warnings.warn("Update already suspended, does nothing.") def resume_update(self, update=True): """Resumes plot update after suspension by suspend_update() Parameters ---------- update : bool, optional If True, also updates plot after resuming (default). See Also -------- suspend_update update_plot """ if self._suspend_update is True: self._suspend_update = False self._connect_parameters2update_plot() if update is True: # Ideally, the update flag should in stead work like this: # If update is true, update_plot is called if any action # would have called it while updating was suspended. # However, this is prohibitively difficult to track, so # in stead it is simply assume that a change has happened # between suspend and resume, and therefore that the plot # needs to update. As we do not know what has changed, # all components need to update. This can however be # suppressed by setting update to false self.update_plot() else: warnings.warn("Update not suspended, nothing to resume.") def _update_model_line(self): if (self._plot_active is True and self._model_line is not None): self._model_line.update() def _fetch_values_from_p0(self, p_std=None): """Fetch the parameter values from the output of the optimzer `self.p0` Parameters ---------- p_std : array array containing the corresponding standard deviatio n """ comp_p_std = None counter = 0 for component in self: # Cut the parameters list if component.active is True: if p_std is not None: comp_p_std = p_std[ counter: counter + component._nfree_param] component.fetch_values_from_array( self.p0[counter: counter + component._nfree_param], comp_p_std, onlyfree=True) counter += component._nfree_param # Defines the functions for the fitting process ------------------------- def _model2plot(self, axes_manager, out_of_range2nans=True): old_axes_manager = None if axes_manager is not self.axes_manager: old_axes_manager = self.axes_manager self.axes_manager = axes_manager self.fetch_stored_values() s = self.__call__(non_convolved=False, onlyactive=True) if old_axes_manager is not None: self.axes_manager = old_axes_manager self.fetch_stored_values() if out_of_range2nans is True: ns = np.empty((self.axis.axis.shape)) ns.fill(np.nan) ns[self.channel_switches] = s s = ns return s def __call__(self, non_convolved=False, onlyactive=False): """Returns the corresponding model for the current coordinates Parameters ---------- non_convolved : bool If True it will return the deconvolved model only_active : bool If True, only the active components will be used to build the model. cursor: 1 or 2 Returns ------- numpy array """ if self.convolved is False or non_convolved is True: axis = self.axis.axis[self.channel_switches] sum_ = np.zeros(len(axis)) if onlyactive is True: for component in self: # Cut the parameters list if component.active: np.add(sum_, component.function(axis), sum_) else: for component in self: # Cut the parameters list np.add(sum_, component.function(axis), sum_) to_return = sum_ else: # convolved counter = 0 sum_convolved = np.zeros(len(self.convolution_axis)) sum_ = np.zeros(len(self.axis.axis)) for component in self: # Cut the parameters list if onlyactive: if component.active: if component.convolved: np.add(sum_convolved, component.function( self.convolution_axis), sum_convolved) else: np.add(sum_, component.function(self.axis.axis), sum_) counter += component._nfree_param else: if component.convolved: np.add(sum_convolved, component.function(self.convolution_axis), sum_convolved) else: np.add(sum_, component.function(self.axis.axis), sum_) counter += component._nfree_param to_return = sum_ + np.convolve( self.low_loss(self.axes_manager), sum_convolved, mode="valid") to_return = to_return[self.channel_switches] if self.spectrum.metadata.Signal.binned is True: to_return *= self.spectrum.axes_manager[-1].scale return to_return # TODO: the way it uses the axes def _set_signal_range_in_pixels(self, i1=None, i2=None): """Use only the selected spectral range in the fitting routine. Parameters ---------- i1 : Int i2 : Int Notes ----- To use the full energy range call the function without arguments. """ self.backup_channel_switches = copy.copy(self.channel_switches) self.channel_switches[:] = False self.channel_switches[i1:i2] = True self.update_plot() @interactive_range_selector def set_signal_range(self, x1=None, x2=None): """Use only the selected spectral range defined in its own units in the fitting routine. Parameters ---------- E1 : None or float E2 : None or float Notes ----- To use the full energy range call the function without arguments. """ i1, i2 = self.axis.value_range_to_indices(x1, x2) self._set_signal_range_in_pixels(i1, i2) def _remove_signal_range_in_pixels(self, i1=None, i2=None): """Removes the data in the given range from the data range that will be used by the fitting rountine Parameters ---------- x1 : None or float x2 : None or float """ self.channel_switches[i1:i2] = False self.update_plot() @interactive_range_selector def remove_signal_range(self, x1=None, x2=None): """Removes the data in the given range from the data range that will be used by the fitting rountine Parameters ---------- x1 : None or float x2 : None or float """ i1, i2 = self.axis.value_range_to_indices(x1, x2) self._remove_signal_range_in_pixels(i1, i2) def reset_signal_range(self): '''Resets the data range''' self._set_signal_range_in_pixels() def _add_signal_range_in_pixels(self, i1=None, i2=None): """Adds the data in the given range from the data range that will be used by the fitting rountine Parameters ---------- x1 : None or float x2 : None or float """ self.channel_switches[i1:i2] = True self.update_plot() @interactive_range_selector def add_signal_range(self, x1=None, x2=None): """Adds the data in the given range from the data range that will be used by the fitting rountine Parameters ---------- x1 : None or float x2 : None or float """ i1, i2 = self.axis.value_range_to_indices(x1, x2) self._add_signal_range_in_pixels(i1, i2) def reset_the_signal_range(self): self.channel_switches[:] = True self.update_plot() def _model_function(self, param): if self.convolved is True: counter = 0 sum_convolved = np.zeros(len(self.convolution_axis)) sum = np.zeros(len(self.axis.axis)) for component in self: # Cut the parameters list if component.active: if component.convolved is True: np.add(sum_convolved, component.__tempcall__(param[ counter:counter + component._nfree_param], self.convolution_axis), sum_convolved) else: np.add( sum, component.__tempcall__( param[ counter:counter + component._nfree_param], self.axis.axis), sum) counter += component._nfree_param to_return = (sum + np.convolve(self.low_loss(self.axes_manager), sum_convolved, mode="valid"))[ self.channel_switches] else: axis = self.axis.axis[self.channel_switches] counter = 0 first = True for component in self: # Cut the parameters list if component.active: if first is True: sum = component.__tempcall__( param[ counter:counter + component._nfree_param], axis) first = False else: sum += component.__tempcall__( param[ counter:counter + component._nfree_param], axis) counter += component._nfree_param to_return = sum if self.spectrum.metadata.Signal.binned is True: to_return *= self.spectrum.axes_manager[-1].scale return to_return def _jacobian(self, param, y, weights=None): if self.convolved is True: counter = 0 grad = np.zeros(len(self.axis.axis)) for component in self: # Cut the parameters list if component.active: component.fetch_values_from_array( param[ counter:counter + component._nfree_param], onlyfree=True) if component.convolved: for parameter in component.free_parameters: par_grad = np.convolve( parameter.grad(self.convolution_axis), self.low_loss(self.axes_manager), mode="valid") if parameter._twins: for parameter in parameter._twins: np.add(par_grad, np.convolve( parameter.grad( self.convolution_axis), self.low_loss(self.axes_manager), mode="valid"), par_grad) grad = np.vstack((grad, par_grad)) counter += component._nfree_param else: for parameter in component.free_parameters: par_grad = parameter.grad(self.axis.axis) if parameter._twins: for parameter in parameter._twins: np.add(par_grad, parameter.grad( self.axis.axis), par_grad) grad = np.vstack((grad, par_grad)) counter += component._nfree_param if weights is None: to_return = grad[1:, self.channel_switches] else: to_return = grad[1:, self.channel_switches] * weights else: axis = self.axis.axis[self.channel_switches] counter = 0 grad = axis for component in self: # Cut the parameters list if component.active: component.fetch_values_from_array( param[ counter:counter + component._nfree_param], onlyfree=True) for parameter in component.free_parameters: par_grad = parameter.grad(axis) if parameter._twins: for parameter in parameter._twins: np.add(par_grad, parameter.grad( axis), par_grad) grad = np.vstack((grad, par_grad)) counter += component._nfree_param if weights is None: to_return = grad[1:, :] else: to_return = grad[1:, :] * weights if self.spectrum.metadata.Signal.binned is True: to_return *= self.spectrum.axes_manager[-1].scale return to_return def _function4odr(self, param, x): return self._model_function(param) def _jacobian4odr(self, param, x): return self._jacobian(param, x) def _poisson_likelihood_function(self, param, y, weights=None): """Returns the likelihood function of the model for the given data and parameters """ mf = self._model_function(param) with np.errstate(invalid='ignore'): return -(y * np.log(mf) - mf).sum() def _gradient_ml(self, param, y, weights=None): mf = self._model_function(param) return -(self._jacobian(param, y) * (y / mf - 1)).sum(1) def _errfunc(self, param, y, weights=None): errfunc = self._model_function(param) - y if weights is None: return errfunc else: return errfunc * weights def _errfunc2(self, param, y, weights=None): if weights is None: return ((self._errfunc(param, y)) ** 2).sum() else: return ((weights * self._errfunc(param, y)) ** 2).sum() def _gradient_ls(self, param, y, weights=None): gls = (2 * self._errfunc(param, y, weights) * self._jacobian(param, y)).sum(1) return gls def _errfunc4mpfit(self, p, fjac=None, x=None, y=None, weights=None): if fjac is None: errfunc = self._model_function(p) - y if weights is not None: errfunc *= weights status = 0 return [status, errfunc] else: return [0, self._jacobian(p, y).T] def _calculate_chisq(self): if self.spectrum.metadata.has_item('Signal.Noise_properties.variance'): variance = self.spectrum.metadata.Signal.Noise_properties.variance if isinstance(variance, Signal): variance = variance.data.__getitem__( self.spectrum.axes_manager._getitem_tuple )[self.channel_switches] else: variance = 1.0 d = self(onlyactive=True) - self.spectrum()[self.channel_switches] d *= d / (1. * variance) # d = difference^2 / variance. self.chisq.data[self.spectrum.axes_manager.indices[::-1]] = sum(d) def _set_current_degrees_of_freedom(self): self.dof.data[self.spectrum.axes_manager.indices[::-1]] = len(self.p0) @property def red_chisq(self): """Reduced chi-squared. Calculated from self.chisq and self.dof """ tmp = self.chisq / (- self.dof + sum(self.channel_switches) - 1) tmp.metadata.General.title = self.spectrum.metadata.General.title + \ ' reduced chi-squared' return tmp def fit(self, fitter=None, method='ls', grad=False, bounded=False, ext_bounding=False, update_plot=False, **kwargs): """Fits the model to the experimental data. The chi-squared, reduced chi-squared and the degrees of freedom are computed automatically when fitting. They are stored as signals, in the `chisq`, `red_chisq` and `dof`. Note that, unless ``metadata.Signal.Noise_properties.variance`` contains an accurate estimation of the variance of the data, the chi-squared and reduced chi-squared cannot be computed correctly. This is also true for homocedastic noise. Parameters ---------- fitter : {None, "leastsq", "odr", "mpfit", "fmin"} The optimizer to perform the fitting. If None the fitter defined in `preferences.Model.default_fitter` is used. "leastsq" performs least squares using the Levenberg–Marquardt algorithm. "mpfit" performs least squares using the Levenberg–Marquardt algorithm and, unlike "leastsq", support bounded optimization. "fmin" performs curve fitting using a downhill simplex algorithm. It is less robust than the Levenberg-Marquardt based optimizers, but, at present, it is the only one that support maximum likelihood optimization for poissonian noise. "odr" performs the optimization using the orthogonal distance regression algorithm. It does not support bounds. "leastsq", "odr" and "mpfit" can estimate the standard deviation of the estimated value of the parameters if the "metada.Signal.Noise_properties.variance" attribute is defined. Note that if it is not defined the standard deviation is estimated using variance equal 1, what, if the noise is heterocedatic, will result in a biased estimation of the parameter values and errors.i If `variance` is a `Signal` instance of the same `navigation_dimension` as the spectrum, and `method` is "ls" weighted least squares is performed. method : {'ls', 'ml'} Choose 'ls' (default) for least squares and 'ml' for poissonian maximum-likelihood estimation. The latter is only available when `fitter` is "fmin". grad : bool If True, the analytical gradient is used if defined to speed up the optimization. bounded : bool If True performs bounded optimization if the fitter supports it. Currently only "mpfit" support it. update_plot : bool If True, the plot is updated during the optimization process. It slows down the optimization but it permits to visualize the optimization progress. ext_bounding : bool If True, enforce bounding by keeping the value of the parameters constant out of the defined bounding area. **kwargs : key word arguments Any extra key word argument will be passed to the chosen fitter. For more information read the docstring of the optimizer of your choice in `scipy.optimize`. See Also -------- multifit """ if fitter is None: fitter = preferences.Model.default_fitter switch_aap = (update_plot != self._plot_active) if switch_aap is True and update_plot is False: self._disconnect_parameters2update_plot() self.p_std = None self._set_p0() if ext_bounding: self._enable_ext_bounding() if grad is False: approx_grad = True jacobian = None odr_jacobian = None grad_ml = None grad_ls = None else: approx_grad = False jacobian = self._jacobian odr_jacobian = self._jacobian4odr grad_ml = self._gradient_ml grad_ls = self._gradient_ls if bounded is True and fitter not in ("mpfit", "tnc", "l_bfgs_b"): raise NotImplementedError("Bounded optimization is only available " "for the mpfit optimizer.") if method == 'ml': weights = None if fitter != "fmin": raise NotImplementedError("Maximum likelihood estimation " 'is only implemented for the "fmin" ' 'optimizer') elif method == "ls": if ("Signal.Noise_properties.variance" not in self.spectrum.metadata): variance = 1 else: variance = self.spectrum.metadata.Signal.\ Noise_properties.variance if isinstance(variance, Signal): if (variance.axes_manager.navigation_shape == self.spectrum.axes_manager.navigation_shape): variance = variance.data.__getitem__( self.axes_manager._getitem_tuple)[ self.channel_switches] else: raise AttributeError( "The `navigation_shape` of the variance signals " "is not equal to the variance shape of the " "spectrum") elif not isinstance(variance, numbers.Number): raise AttributeError( "Variance must be a number or a `Signal` instance but " "currently it is a %s" % type(variance)) weights = 1. / np.sqrt(variance) else: raise ValueError( 'method must be "ls" or "ml" but %s given' % method) args = (self.spectrum()[self.channel_switches], weights) # Least squares "dedicated" fitters if fitter == "leastsq": output = \ leastsq(self._errfunc, self.p0[:], Dfun=jacobian, col_deriv=1, args=args, full_output=True, **kwargs) self.p0, pcov = output[0:2] if (self.axis.size > len(self.p0)) and pcov is not None: pcov *= ((self._errfunc(self.p0, *args) ** 2).sum() / (len(args[0]) - len(self.p0))) self.p_std = np.sqrt(np.diag(pcov)) self.fit_output = output elif fitter == "odr": modelo = odr.Model(fcn=self._function4odr, fjacb=odr_jacobian) mydata = odr.RealData( self.axis.axis[ self.channel_switches], self.spectrum()[ self.channel_switches], sx=None, sy=( 1 / weights if weights is not None else None)) myodr = odr.ODR(mydata, modelo, beta0=self.p0[:]) myoutput = myodr.run() result = myoutput.beta self.p_std = myoutput.sd_beta self.p0 = result self.fit_output = myoutput elif fitter == 'mpfit': autoderivative = 1 if grad is True: autoderivative = 0 if bounded is True: self.set_mpfit_parameters_info() elif bounded is False: self.mpfit_parinfo = None m = mpfit(self._errfunc4mpfit, self.p0[:], parinfo=self.mpfit_parinfo, functkw={ 'y': self.spectrum()[self.channel_switches], 'weights': weights}, autoderivative=autoderivative, quiet=1) self.p0 = m.params if (self.axis.size > len(self.p0)) and m.perror is not None: self.p_std = m.perror * np.sqrt( (self._errfunc(self.p0, *args) ** 2).sum() / (len(args[0]) - len(self.p0))) self.fit_output = m else: # General optimizers (incluiding constrained ones(tnc,l_bfgs_b) # Least squares or maximum likelihood if method == 'ml': tominimize = self._poisson_likelihood_function fprime = grad_ml elif method in ['ls', "wls"]: tominimize = self._errfunc2 fprime = grad_ls # OPTIMIZERS # Simple (don't use gradient) if fitter == "fmin": self.p0 = fmin( tominimize, self.p0, args=args, **kwargs) elif fitter == "powell": self.p0 = fmin_powell(tominimize, self.p0, args=args, **kwargs) # Make use of the gradient elif fitter == "cg": self.p0 = fmin_cg(tominimize, self.p0, fprime=fprime, args=args, **kwargs) elif fitter == "ncg": self.p0 = fmin_ncg(tominimize, self.p0, fprime=fprime, args=args, **kwargs) elif fitter == "bfgs": self.p0 = fmin_bfgs( tominimize, self.p0, fprime=fprime, args=args, **kwargs) # Constrainded optimizers # Use gradient elif fitter == "tnc": if bounded is True: self.set_boundaries() elif bounded is False: self.self.free_parameters_boundaries = None self.p0 = fmin_tnc( tominimize, self.p0, fprime=fprime, args=args, bounds=self.free_parameters_boundaries, approx_grad=approx_grad, **kwargs)[0] elif fitter == "l_bfgs_b": if bounded is True: self.set_boundaries() elif bounded is False: self.self.free_parameters_boundaries = None self.p0 = fmin_l_bfgs_b(tominimize, self.p0, fprime=fprime, args=args, bounds=self.free_parameters_boundaries, approx_grad=approx_grad, **kwargs)[0] else: print \ """ The %s optimizer is not available. Available optimizers: Unconstrained: -------------- Only least Squares: leastsq and odr General: fmin, powell, cg, ncg, bfgs Cosntrained: ------------ tnc and l_bfgs_b """ % fitter if np.iterable(self.p0) == 0: self.p0 = (self.p0,) self._fetch_values_from_p0(p_std=self.p_std) self.store_current_values() self._calculate_chisq() self._set_current_degrees_of_freedom() if ext_bounding is True: self._disable_ext_bounding() if switch_aap is True and update_plot is False: self._connect_parameters2update_plot() self.update_plot() def multifit(self, mask=None, fetch_only_fixed=False, autosave=False, autosave_every=10, show_progressbar=None, **kwargs): """Fit the data to the model at all the positions of the navigation dimensions. Parameters ---------- mask : {None, numpy.array} To mask (do not fit) at certain position pass a numpy.array of type bool where True indicates that the data will not be fitted at the given position. fetch_only_fixed : bool If True, only the fixed parameters values will be updated when changing the positon. autosave : bool If True, the result of the fit will be saved automatically with a frequency defined by autosave_every. autosave_every : int Save the result of fitting every given number of spectra. show_progressbar : None or bool If True, display a progress bar. If None the default is set in `preferences`. **kwargs : key word arguments Any extra key word argument will be passed to the fit method. See the fit method documentation for a list of valid arguments. See Also -------- fit """ if show_progressbar is None: show_progressbar = preferences.General.show_progressbar if autosave is not False: fd, autosave_fn = tempfile.mkstemp( prefix='hyperspy_autosave-', dir='.', suffix='.npz') os.close(fd) autosave_fn = autosave_fn[:-4] messages.information( "Autosaving each %s pixels to %s.npz" % (autosave_every, autosave_fn)) messages.information( "When multifit finishes its job the file will be deleted") if mask is not None and ( mask.shape != tuple( self.axes_manager._navigation_shape_in_array)): messages.warning_exit( "The mask must be a numpy array of boolen type with " " shape: %s" + str(self.axes_manager._navigation_shape_in_array)) masked_elements = 0 if mask is None else mask.sum() maxval = self.axes_manager.navigation_size - masked_elements if maxval > 0: pbar = progressbar.progressbar(maxval=maxval, disabled=not show_progressbar) if 'bounded' in kwargs and kwargs['bounded'] is True: if kwargs['fitter'] == 'mpfit': self.set_mpfit_parameters_info() kwargs['bounded'] = None elif kwargs['fitter'] in ("tnc", "l_bfgs_b"): self.set_boundaries() kwargs['bounded'] = None else: messages.information( "The chosen fitter does not suppport bounding." "If you require bounding please select one of the " "following fitters instead: mpfit, tnc, l_bfgs_b") kwargs['bounded'] = False i = 0 self.axes_manager.disconnect(self.fetch_stored_values) for index in self.axes_manager: if mask is None or not mask[index[::-1]]: self.fetch_stored_values(only_fixed=fetch_only_fixed) self.fit(**kwargs) i += 1 if maxval > 0: pbar.update(i) if autosave is True and i % autosave_every == 0: self.save_parameters2file(autosave_fn) if maxval > 0: pbar.finish() self.axes_manager.connect(self.fetch_stored_values) if autosave is True: messages.information( 'Deleting the temporary file %s pixels' % ( autosave_fn + 'npz')) os.remove(autosave_fn + '.npz') def save_parameters2file(self, filename): """Save the parameters array in binary format. The data is saved to a single file in numpy's uncompressed ``.npz`` format. Parameters ---------- filename : str See Also -------- load_parameters_from_file, export_results Notes ----- This method can be used to save the current state of the model in a way that can be loaded back to recreate the it using `load_parameters_from file`. Actually, as of HyperSpy 0.8 this is the only way to do so. However, this is known to be brittle. For example see https://github.com/hyperspy/hyperspy/issues/341. """ kwds = {} i = 0 for component in self: cname = component.name.lower().replace(' ', '_') for param in component.parameters: pname = param.name.lower().replace(' ', '_') kwds['%s_%s.%s' % (i, cname, pname)] = param.map i += 1 np.savez(filename, **kwds) def load_parameters_from_file(self, filename): """Loads the parameters array from a binary file written with the 'save_parameters2file' function. Parameters --------- filename : str See Also -------- save_parameters2file, export_results Notes ----- In combination with `save_parameters2file`, this method can be used to recreate a model stored in a file. Actually, before HyperSpy 0.8 this is the only way to do so. However, this is known to be brittle. For example see https://github.com/hyperspy/hyperspy/issues/341. """ f = np.load(filename) i = 0 for component in self: # Cut the parameters list cname = component.name.lower().replace(' ', '_') for param in component.parameters: pname = param.name.lower().replace(' ', '_') param.map = f['%s_%s.%s' % (i, cname, pname)] i += 1 self.fetch_stored_values() def plot(self, plot_components=False): """Plots the current spectrum to the screen and a map with a cursor to explore the SI. Parameters ---------- plot_components : bool If True, add a line per component to the signal figure. """ # If new coordinates are assigned self.spectrum.plot() _plot = self.spectrum._plot l1 = _plot.signal_plot.ax_lines[0] color = l1.line.get_color() l1.set_line_properties(color=color, type='scatter') l2 = hyperspy.drawing.spectrum.SpectrumLine() l2.data_function = self._model2plot l2.set_line_properties(color='blue', type='line') # Add the line to the figure _plot.signal_plot.add_line(l2) l2.plot() on_figure_window_close(_plot.signal_plot.figure, self._close_plot) self._model_line = l2 self._plot = self.spectrum._plot self._connect_parameters2update_plot() if plot_components is True: self.enable_plot_components() def _connect_component_line(self, component): if hasattr(component, "_model_plot_line"): component.connect(component._model_plot_line.update) for parameter in component.parameters: parameter.connect(component._model_plot_line.update) def _disconnect_component_line(self, component): if hasattr(component, "_model_plot_line"): component.disconnect(component._model_plot_line.update) for parameter in component.parameters: parameter.disconnect(component._model_plot_line.update) def _connect_component_lines(self): for component in [component for component in self if component.active]: self._connect_component_line(component) def _disconnect_component_lines(self): for component in [component for component in self if component.active]: self._disconnect_component_line(component) def _plot_component(self, component): line = hyperspy.drawing.spectrum.SpectrumLine() line.data_function = component._component2plot # Add the line to the figure self._plot.signal_plot.add_line(line) line.plot() component._model_plot_line = line self._connect_component_line(component) def _update_component_line(self, component): if hasattr(component, "_model_plot_line"): component._model_plot_line.update() def _disable_plot_component(self, component): self._disconnect_component_line(component) if hasattr(component, "_model_plot_line"): component._model_plot_line.close() del component._model_plot_line self._plot_components = False def _close_plot(self): if self._plot_components is True: self.disable_plot_components() self._disconnect_parameters2update_plot() self._model_line = None def enable_plot_components(self): if self._plot is None or self._plot_components: return self._plot_components = True for component in [component for component in self if component.active]: self._plot_component(component) def disable_plot_components(self): if self._plot is None: return for component in self: self._disable_plot_component(component) self._plot_components = False def assign_current_values_to_all(self, components_list=None, mask=None): """Set parameter values for all positions to the current ones. Parameters ---------- component_list : list of components, optional If a list of components is given, the operation will be performed only in the value of the parameters of the given components. The components can be specified by name, index or themselves. mask : boolean numpy array or None, optional The operation won't be performed where mask is True. """ if components_list is None: components_list = [] for comp in self: if comp.active: components_list.append(comp) else: components_list = [self._get_component(x) for x in components_list] for comp in components_list: for parameter in comp.parameters: parameter.assign_current_value_to_all(mask=mask) def _enable_ext_bounding(self, components=None): """ """ if components is None: components = self for component in components: for parameter in component.parameters: parameter.ext_bounded = True def _disable_ext_bounding(self, components=None): """ """ if components is None: components = self for component in components: for parameter in component.parameters: parameter.ext_bounded = False def export_results(self, folder=None, format=None, save_std=False, only_free=True, only_active=True): """Export the results of the parameters of the model to the desired folder. Parameters ---------- folder : str or None The path to the folder where the file will be saved. If `None` the current folder is used by default. format : str The format to which the data will be exported. It must be the extension of any format supported by HyperSpy. If None, the default format for exporting as defined in the `Preferences` will be used. save_std : bool If True, also the standard deviation will be saved. only_free : bool If True, only the value of the parameters that are free will be exported. only_active : bool If True, only the value of the active parameters will be exported. Notes ----- The name of the files will be determined by each the Component and each Parameter name attributes. Therefore, it is possible to customise the file names modify the name attributes. """ for component in self: if only_active is False or component.active: component.export(folder=folder, format=format, save_std=save_std, only_free=only_free) def plot_results(self, only_free=True, only_active=True): """Plot the value of the parameters of the model Parameters ---------- only_free : bool If True, only the value of the parameters that are free will be plotted. only_active : bool If True, only the value of the active parameters will be plotted. Notes ----- The name of the files will be determined by each the Component and each Parameter name attributes. Therefore, it is possible to customise the file names modify the name attributes. """ for component in self: if only_active is False or component.active: component.plot(only_free=only_free) def print_current_values(self, only_free=True): """Print the value of each parameter of the model. Parameters ---------- only_free : bool If True, only the value of the parameters that are free will be printed. """ print "Components\tParameter\tValue" for component in self: if component.active: if component.name: print(component.name) else: print(component._id_name) parameters = component.free_parameters if only_free \ else component.parameters for parameter in parameters: if not hasattr(parameter.value, '__iter__'): print("\t\t%s\t%g" % ( parameter.name, parameter.value)) def enable_adjust_position( self, components=None, fix_them=True, show_label=True): """Allow changing the *x* position of component by dragging a vertical line that is plotted in the signal model figure Parameters ---------- components : {None, list of components} If None, the position of all the active components of the model that has a well defined *x* position with a value in the axis range will get a position adjustment line. Otherwise the feature is added only to the given components. The components can be specified by name, index or themselves. fix_them : bool If True the position parameter of the components will be temporarily fixed until adjust position is disable. This can be useful to iteratively adjust the component positions and fit the model. show_label : bool, optional If True, a label showing the component name is added to the plot next to the vertical line. See also -------- disable_adjust_position """ if (self._plot is None or self._plot.is_active() is False): self.plot() if self._position_widgets: self.disable_adjust_position() on_figure_window_close(self._plot.signal_plot.figure, self.disable_adjust_position) if components: components = [self._get_component(x) for x in components] else: self._adjust_position_all = (fix_them, show_label) components = components if components else self if not components: # The model does not have components so we do nothing return components = [ component for component in components if component.active] for component in components: self._make_position_adjuster(component, fix_them, show_label) def _make_position_adjuster(self, component, fix_it, show_label): if (component._position is not None and not component._position.twin): set_value = component._position._set_value get_value = component._position._get_value else: return # Create an AxesManager for the widget axis_dict = self.axes_manager.signal_axes[0].get_axis_dictionary() am = AxesManager([axis_dict, ]) am._axes[0].navigate = True try: am._axes[0].value = get_value() except TraitError: # The value is outside of the axis range return # Create the vertical line and labels if show_label: self._position_widgets.extend(( DraggableVerticalLine(am), DraggableLabel(am),)) # Store the component for bookkeeping, and to reset # its twin when disabling adjust position self._position_widgets[-2].component = component self._position_widgets[-1].component = component w = self._position_widgets[-1] w.string = component._get_short_description().replace( ' component', '') w.set_mpl_ax(self._plot.signal_plot.ax) self._position_widgets[-2].set_mpl_ax( self._plot.signal_plot.ax) else: self._position_widgets.extend(( DraggableVerticalLine(am),)) # Store the component for bookkeeping, and to reset # its twin when disabling adjust position self._position_widgets[-1].component = component self._position_widgets[-1].set_mpl_ax( self._plot.signal_plot.ax) # Create widget -> parameter connection am._axes[0].continuous_value = True am._axes[0].on_trait_change(set_value, 'value') # Create parameter -> widget connection # This is done with a duck typing trick # We disguise the AxesManager axis of Parameter by adding # the _twin attribute am._axes[0]._twins = set() component._position.twin = am._axes[0] def disable_adjust_position(self): """Disables the interactive adjust position feature See also -------- enable_adjust_position """ self._adjust_position_all = False while self._position_widgets: pw = self._position_widgets.pop() if hasattr(pw, 'component'): pw.component._position.twin = None del pw.component pw.close() del pw def fit_component( self, component, signal_range="interactive", estimate_parameters=True, fit_independent=False, **kwargs): """Fit just the given component in the given signal range. This method is useful to obtain starting parameters for the components. Any keyword arguments are passed to the fit method. Parameters ---------- component : component instance The component must be in the model, otherwise an exception is raised. The component can be specified by name, index or itself. signal_range : {'interactive', (left_value, right_value), None} If 'interactive' the signal range is selected using the span selector on the spectrum plot. The signal range can also be manually specified by passing a tuple of floats. If None the current signal range is used. estimate_parameters : bool, default True If True will check if the component has an estimate_parameters function, and use it to estimate the parameters in the component. fit_independent : bool, default False If True, all other components are disabled. If False, all other component paramemeters are fixed. Examples -------- Signal range set interactivly >>> g1 = components.Gaussian() >>> m.append(g1) >>> m.fit_component(g1) Signal range set through direct input >>> m.fit_component(g1, signal_range=(50,100)) """ component = self._get_component(component) cf = ComponentFit(self, component, signal_range, estimate_parameters, fit_independent, **kwargs) if signal_range == "interactive": cf.edit_traits() else: cf.apply() def set_parameters_not_free(self, component_list=None, parameter_name_list=None): """ Sets the parameters in a component in a model to not free. Parameters ---------- component_list : None, or list of hyperspy components, optional If None, will apply the function to all components in the model. If list of components, will apply the functions to the components in the list. The components can be specified by name, index or themselves. parameter_name_list : None or list of strings, optional If None, will set all the parameters to not free. If list of strings, will set all the parameters with the same name as the strings in parameter_name_list to not free. Examples -------- >>> v1 = components.Voigt() >>> m.append(v1) >>> m.set_parameters_not_free() >>> m.set_parameters_not_free(component_list=[v1], parameter_name_list=['area','centre']) See also -------- set_parameters_free hyperspy.component.Component.set_parameters_free hyperspy.component.Component.set_parameters_not_free """ if not component_list: component_list = [] for _component in self: component_list.append(_component) else: component_list = [self._get_component(x) for x in component_list] for _component in component_list: _component.set_parameters_not_free(parameter_name_list) def set_parameters_free(self, component_list=None, parameter_name_list=None): """ Sets the parameters in a component in a model to free. Parameters ---------- component_list : None, or list of hyperspy components, optional If None, will apply the function to all components in the model. If list of components, will apply the functions to the components in the list. The components can be specified by name, index or themselves. parameter_name_list : None or list of strings, optional If None, will set all the parameters to not free. If list of strings, will set all the parameters with the same name as the strings in parameter_name_list to not free. Examples -------- >>> v1 = components.Voigt() >>> m.append(v1) >>> m.set_parameters_free() >>> m.set_parameters_free(component_list=[v1], parameter_name_list=['area','centre']) See also -------- set_parameters_not_free hyperspy.component.Component.set_parameters_free hyperspy.component.Component.set_parameters_not_free """ if not component_list: component_list = [] for _component in self: component_list.append(_component) else: component_list = [self._get_component(x) for x in component_list] for _component in component_list: _component.set_parameters_free(parameter_name_list) def set_parameters_value( self, parameter_name, value, component_list=None, only_current=False): """ Sets the value of a parameter in components in a model to a specified value Parameters ---------- parameter_name : string Name of the parameter whos value will be changed value : number The new value of the parameter component_list : list of hyperspy components, optional A list of components whos parameters will changed. The components can be specified by name, index or themselves. only_current : bool, default False If True, will only change the parameter value at the current position in the model. If False, will change the parameter value for all the positions. Examples -------- >>> v1 = components.Voigt() >>> v2 = components.Voigt() >>> m.extend([v1,v2]) >>> m.set_parameters_value('area', 5) >>> m.set_parameters_value('area', 5, component_list=[v1]) >>> m.set_parameters_value('area', 5, component_list=[v1], only_current=True) """ if not component_list: component_list = [] for _component in self: component_list.append(_component) else: component_list = [self._get_component(x) for x in component_list] for _component in component_list: for _parameter in _component.parameters: if _parameter.name == parameter_name: if only_current: _parameter.value = value _parameter.store_current_value_in_array() else: _parameter.value = value _parameter.assign_current_value_to_all() def set_component_active_value( self, value, component_list=None, only_current=False): """ Sets the component 'active' parameter to a specified value Parameters ---------- value : bool The new value of the 'active' parameter component_list : list of hyperspy components, optional A list of components whos parameters will changed. The components can be specified by name, index or themselves. only_current : bool, default False If True, will only change the parameter value at the current position in the model. If False, will change the parameter value for all the positions. Examples -------- >>> v1 = components.Voigt() >>> v2 = components.Voigt() >>> m.extend([v1,v2]) >>> m.set_component_active_value(False) >>> m.set_component_active_value(True, component_list=[v1]) >>> m.set_component_active_value(False, component_list=[v1], only_current=True) """ if not component_list: component_list = [] for _component in self: component_list.append(_component) else: component_list = [self._get_component(x) for x in component_list] for _component in component_list: _component.active = value if _component.active_is_multidimensional: if only_current: _component._active_array[ self.axes_manager.indices[ ::- 1]] = value else: _component._active_array.fill(value) def __getitem__(self, value): """x.__getitem__(y) <==> x[y]""" if isinstance(value, basestring): component_list = [] for component in self: if component.name: if component.name == value: component_list.append(component) elif component._id_name == value: component_list.append(component) if component_list: if len(component_list) == 1: return(component_list[0]) else: raise ValueError( "There are several components with " "the name \"" + str(value) + "\"") else: raise ValueError( "Component name \"" + str(value) + "\" not found in model") else: return list.__getitem__(self, value)
gpl-3.0
-5,660,573,258,302,874,000
37.328125
79
0.546257
false
4.614697
false
false
false
torresj/practica-3
Código/tiposCafes.py
1
18836
/* Esta archivo pertenece a la aplicación "practica 3" bajo licencia GPLv2. Copyright (C) 2014 Jaime Torres Benavente. Este programa es software libre. Puede redistribuirlo y/o modificarlo bajo los términos de la Licencia Pública General de GNU según es publicada por la Free Software Foundation, bien de la versión 2 de dicha Licencia o bien (según su elección) de cualquier versión posterior. Este programa se distribuye con la esperanza de que sea útil, pero SIN NINGUNA GARANTÍA, incluso sin la garantía MERCANTIL implícita o sin garantizar la CONVENIENCIA PARA UN PROPÓSITO PARTICULAR. Véase la Licencia Pública General de GNU para más detalles. Debería haber recibido una copia de la Licencia Pública General junto con este programa. Si no ha sido así, escriba a la Free Software Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, EEUU. */ # -*- coding: utf-8 -*- """ Created on Wed Oct 30 12:07:52 2013 @author: jaime """ import web from web.contrib.template import render_mako from web import form import pymongo import feedparser import time render = render_mako( directories=['plantillas'], input_encoding='utf-8', output_encoding='utf-8', ) ''' Esta funcion sirve para actualizar el tiempo del ultimo acceso al rss, si fuera necesario. Comprobara si han pasado mas de 10 minutos desde la ultima vez, y si es asi, volverá a descargar el rss ''' def actualiza_tiempo(): conn=pymongo.MongoClient() db=conn.mydb cache=db.cache tiempo1=time.time() t=cache.find_one({"rss":"el pais"}) tiempo2=t[u'ult_act'] if((tiempo2- tiempo1)>600): cache.update({"rss": "el pais"}, {"$set": {"ult_act": time.time()}}) rss=feedparser.parse('http://ep00.epimg.net/rss/tags/ultimas_noticias.xml') conn.close() #Variable para RSS, también almacenamos el momento en que se descargo el rss rss=feedparser.parse('http://ep00.epimg.net/rss/tags/ultimas_noticias.xml') actualiza_tiempo() #Validadores vpass=form.regexp(r'.{7,20}$',"La contrasenia debe tener mas de 7 caracteres") #Formulario Para el login formul = form.Form( form.Textbox("user",form.notnull,description = "Usuario:"), form.Password("password",form.notnull,vpass,description = "Contraseña:"), form.Button("Login") ) #Clases para manejar las paginas de los tipos de cafes class Cafe1: def GET(self): s=web.ctx.session try: if s.usuario!='': log=True user=s.usuario else: log=False user='' except AttributeError: s.usuario='' log=False user='' #Variables para rellenar la pagina web login=formul() registro="" titulo="CAFE DEL MAR" subtitulo1="Oferta de cafes" cafes=[["Cafe1","Descripcion del cafe 1"],["Cafe2","Descripcion del cafe 2"],["Cafe3","Descripcion del cafe 3"],["Cafe4","Descripcion del cafe 4"]] cafeEspecial=["Cafe especial de la casa","Descripcion cafe especial de la casa"] piepagina="Copyright &copy; 2013 Jaime Torres Benavente" subtitulo2="Cafe 1" cuerpo="Descripcion detallada del cafe 1" subtitulo3="" subtitulo4="" servicios=[] reg=False modo="index" error='' actualiza_tiempo() return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) def POST(self): login=formul() registro="" titulo="CAFE DEL MAR" subtitulo1="Oferta de cafes" cafes=[["Cafe1","Descripcion del cafe 1"],["Cafe2","Descripcion del cafe 2"],["Cafe3","Descripcion del cafe 3"],["Cafe4","Descripcion del cafe 4"]] cafeEspecial=["Cafe especial de la casa","Descripcion cafe especial de la casa"] piepagina="Copyright &copy; 2013 Jaime Torres Benavente" subtitulo2="Cafe 1" cuerpo="Descripcion del cafe 1" subtitulo3="" subtitulo4="" servicios=[] reg=False error='' modo="index" if not login.validates(): log=False user='' return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) else: s=web.ctx.session #buscamos al usuario en la base de datos conn=pymongo.MongoClient() db=conn.mydb usuarios=db.usuarios us=usuarios.find_one({"user":login['user'].value}) conn.close() try: if login['password'].value==us[u'pass']: log=True user=login['user'].value s.usuario=user else: log=False user='' error='contras&ntilde;a erronea' except TypeError: log=False; user='' error='El usuario no existe' return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) class Cafe2: def GET(self): s=web.ctx.session try: if s.usuario!='': log=True user=s.usuario else: log=False user='' except AttributeError: s.usuario='' log=False user='' #Variables para rellenar la pagina web login=formul() registro="" titulo="CAFE DEL MAR" subtitulo1="Oferta de cafes" cafes=[["Cafe1","Descripcion del cafe 1"],["Cafe2","Descripcion del cafe 2"],["Cafe3","Descripcion del cafe 3"],["Cafe4","Descripcion del cafe 4"]] cafeEspecial=["Cafe especial de la casa","Descripcion cafe especial de la casa"] piepagina="Copyright &copy; 2013 Jaime Torres Benavente" subtitulo2="Cafe 2" cuerpo="Descripcion detallada del cafe 2" subtitulo3="" subtitulo4="" servicios=[] reg=False error='' modo="index" actualiza_tiempo() return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) def POST(self): login=formul() registro="" titulo="CAFE DEL MAR" subtitulo1="Oferta de cafes" cafes=[["Cafe1","Descripcion del cafe 1"],["Cafe2","Descripcion del cafe 2"],["Cafe3","Descripcion del cafe 3"],["Cafe4","Descripcion del cafe 4"]] cafeEspecial=["Cafe especial de la casa","Descripcion cafe especial de la casa"] piepagina="Copyright &copy; 2013 Jaime Torres Benavente" subtitulo2="Cafe 2" cuerpo="Descripcion del cafe 2" subtitulo3="" subtitulo4="" servicios=[] reg=False error='' modo="index" if not login.validates(): log=False user='' return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) else: s=web.ctx.session #buscamos al usuario en la base de datos conn=pymongo.MongoClient() db=conn.mydb usuarios=db.usuarios us=usuarios.find_one({"user":login['user'].value}) conn.close() try: if login['password'].value==us[u'pass']: log=True user=login['user'].value s.usuario=user else: log=False user='' error='contras&ntilde;a erronea' except TypeError: log=False; user='' error='El usuario no existe' return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) class Cafe3: def GET(self): s=web.ctx.session try: if s.usuario!='': log=True user=s.usuario else: log=False user='' except AttributeError: s.usuario='' log=False user='' #Variables para rellenar la pagina web login=formul() registro="" titulo="CAFE DEL MAR" subtitulo1="Oferta de cafes" cafes=[["Cafe1","Descripcion del cafe 1"],["Cafe2","Descripcion del cafe 2"],["Cafe3","Descripcion del cafe 3"],["Cafe4","Descripcion del cafe 4"]] cafeEspecial=["Cafe especial de la casa","Descripcion cafe especial de la casa"] piepagina="Copyright &copy; 2013 Jaime Torres Benavente" subtitulo2="Cafe 1" cuerpo="Descripcion detallada del cafe 3" subtitulo3="" subtitulo4="" servicios=[] reg=False error='' modo="index" actualiza_tiempo() return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) def POST(self): login=formul() registro="" titulo="CAFE DEL MAR" subtitulo1="Oferta de cafes" cafes=[["Cafe1","Descripcion del cafe 1"],["Cafe2","Descripcion del cafe 2"],["Cafe3","Descripcion del cafe 3"],["Cafe4","Descripcion del cafe 4"]] cafeEspecial=["Cafe especial de la casa","Descripcion cafe especial de la casa"] piepagina="Copyright &copy; 2013 Jaime Torres Benavente" subtitulo2="Cafe 3" cuerpo="Descripcion del cafe 3" subtitulo3="" subtitulo4="" servicios=[] reg=False error='' modo="index" if not login.validates(): log=False user='' return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) else: s=web.ctx.session #buscamos al usuario en la base de datos conn=pymongo.MongoClient() db=conn.mydb usuarios=db.usuarios us=usuarios.find_one({"user":login['user'].value}) conn.close() try: if login['password'].value==us[u'pass']: log=True user=login['user'].value s.usuario=user else: log=False user='' error='contras&ntilde;a erronea' except TypeError: log=False; user='' error='El usuario no existe' return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) class Cafe4: def GET(self): s=web.ctx.session try: if s.usuario!='': log=True user=s.usuario else: log=False user='' except AttributeError: s.usuario='' log=False user='' #Variables para rellenar la pagina web login=formul() registro="" titulo="CAFE DEL MAR" subtitulo1="Oferta de cafes" cafes=[["Cafe1","Descripcion del cafe 1"],["Cafe2","Descripcion del cafe 2"],["Cafe3","Descripcion del cafe 3"],["Cafe4","Descripcion del cafe 4"]] cafeEspecial=["Cafe especial de la casa","Descripcion cafe especial de la casa"] piepagina="Copyright &copy; 2013 Jaime Torres Benavente" subtitulo2="Cafe 4" cuerpo="Descripcion detallada del cafe 4" subtitulo3="" subtitulo4="" servicios=[] reg=False error='' modo="index" actualiza_tiempo() return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) def POST(self): login=formul() registro="" titulo="CAFE DEL MAR" subtitulo1="Oferta de cafes" cafes=[["Cafe1","Descripcion del cafe 1"],["Cafe2","Descripcion del cafe 2"],["Cafe3","Descripcion del cafe 3"],["Cafe4","Descripcion del cafe 4"]] cafeEspecial=["Cafe especial de la casa","Descripcion cafe especial de la casa"] piepagina="Copyright &copy; 2013 Jaime Torres Benavente" subtitulo2="Cafe 4" cuerpo="Descripcion del cafe 4" subtitulo3="" subtitulo4="" servicios=[] reg=False error='' modo="index" if not login.validates(): log=False user='' return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss) else: s=web.ctx.session #buscamos al usuario en la base de datos conn=pymongo.MongoClient() db=conn.mydb usuarios=db.usuarios us=usuarios.find_one({"user":login['user'].value}) conn.close() try: if login['password'].value==us[u'pass']: log=True user=login['user'].value s.usuario=user else: log=False user='' error='contras&ntilde;a erronea' except TypeError: log=False; user='' error='El usuario no existe' return render.plantilla( titulo=titulo, login=login, log=log, user=user, subtitulo1=subtitulo1, cafes=cafes, cafeEspecial=cafeEspecial, subtitulo2=subtitulo2, cuerpo=cuerpo, registro=registro, subtitulo3=subtitulo3, subtitulo4=subtitulo4, servicios=servicios, piepagina=piepagina, reg=reg, modo=modo, error=error, rss=rss)
gpl-2.0
-8,106,485,634,979,966,000
29.345161
155
0.523015
false
3.551151
false
false
false
sleepinghungry/wwif
basic_game/basic_game_engine.py
1
5705
from basic_game.descriptors import Descriptor from basic_game.directions import directions from basic_game.language import list_prefix, normalize_input, get_noun, prepositions from basic_game.objects import Container from basic_game.writer import DEBUG, ConsoleWriter from basic_game.verbs import BaseVerb class BasicGameEngine(object): """Given a completed GameWorld, starts a game.""" def __init__(self, basic_game_world): self.writer = ConsoleWriter() self.descriptor = Descriptor(self.writer) self.game = basic_game_world self.player = basic_game_world.player self.animals = basic_game_world.animals self.done = False self.turn_count = 0 self.points = 0 basic_game_world.writer = self.writer basic_game_world.engine = self def run(self): """Run the main loop until game is done. """ while not self.done: self._describe_setting() if self.player.location.game_end: if self.player.location.game_end.check(self.game, self.player.location): self.writer.output(self.player.location.game_end.text) break if self.player.game_end: if self.player.game_end.check(self.game, self.player): self.writer.output(self.player.game_end.text) break if self.player.health < 0: self.writer.output("Better luck next time!") break command = self._get_input() if command == 'q' or command == 'quit': break self._do_action(command) self.writer.output("\ngoodbye!\n") def _describe_setting(self): """Describe the new setting and actors that the player has encountered. """ actor = self.player # if the actor moved, describe the room if actor.check_if_moved(): self.descriptor.output_title(actor.location) self.descriptor.output_stats(self.turn_count, self.points) self.descriptor.output_location_description(actor.location) # See if the animals want to do anything for animal in self.animals.values(): # first check that it is not dead if animal.health >= 0: animal.act_autonomously(actor.location) def _get_input(self): """ Request and parse out player input.""" self.writer.clear_text() self.writer.output("") user_input = input("> ") # remove punctuation and unecessary words command = normalize_input(user_input) return command def _do_action(self, command): actor = self.player words = command.split() if not words: return # following the Infocom convention commands are decomposed into # VERB(verb), OBJECT(noun), INDIRECT_OBJECT(indirect). # For example: "hit zombie with hammer" = HIT(verb) ZOMBIE(noun) WITH HAMMER(indirect). things = list(actor.inventory.values()) + \ list(actor.location.contents.values()) + \ list(actor.location.exits.values()) + \ list(actor.location.actors.values()) + \ [actor.location] + \ [actor] for c in actor.location.contents.values(): if isinstance(c, Container) and c.is_open: things += c.contents.values() potential_verbs = [] for t in things: potential_verbs += t.verbs.keys() # extract the VERB verb = None potential_verbs.sort(key=lambda key : -len(key)) for v in potential_verbs: vv = v.split() if list_prefix(vv, words): verb = v words = words[len(vv):] if not verb: verb = words[0] words = words[1:] # extract the OBJECT noun = None if words: (noun, words) = get_noun(words, things) # extract INDIRECT (object) in phrase of the form VERB OBJECT PREPOSITION INDIRECT indirect = None if len(words) > 1 and words[0].lower() in prepositions: (indirect, words) = get_noun(words[1:], things) self.turn_count += 1 # first check phrases for thing in things: f = thing.get_phrase(command, things) if f: if isinstance(f, BaseVerb): if f.act(actor, noun, words): return else: f(self.game, thing) return # if we have an INDIRECT object, try it's handle first # e.g. "hit cat with hammer" -> hammer.hit(actor, 'cat', []) if indirect: # try inventory and room contents things = list(actor.inventory.values()) + \ list(actor.location.contents.values()) for thing in things: if indirect == thing.name: v = thing.get_verb(verb) if v: if v.act(actor, noun, words): return for a in actor.location.actors.values(): if indirect == a.name: v = a.get_verb(verb) if v: if v.act(a, noun, words): return # if we have a NOUN, try it's handler next if noun: for thing in things: if noun == thing.name: v = thing.get_verb(verb) if v: if v.act(actor, None, words): return for a in actor.location.actors.values(): if noun == a.name: v = a.get_verb(verb) if v: if v.act(a, None, words): return # location specific VERB v = actor.location.get_verb(verb) if v: if v.act(actor, noun, words): return # handle directional moves of the actor if not noun: if verb in directions: actor.act_go1(actor, verb, None) return # general actor VERB v = actor.get_verb(verb) if v: if v.act(actor, noun, words): return # not understood self.writer.output("Huh?") self.turn_count -= 1 return
mit
-2,709,970,980,162,616,300
27.242574
91
0.603856
false
3.706953
false
false
false
desihub/desitarget
py/desitarget/train/data_collection/sweep_meta.py
1
2600
#!/usr/bin/env python import sys import subprocess import numpy as np import astropy.io.fits as fits def sweep_meta(release, outfits): if (release == 'dr3'): sweepdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr3/sweep/3.1' if (release == 'dr4'): sweepdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr4/sweep/4.0' if (release == 'dr5'): sweepdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr5/sweep/5.0' if (release == 'dr6'): sweepdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr6/sweep/6.0' if (release == 'dr7'): sweepdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr7/sweep/7.1' if (release == 'dr8n'): # BASS/MzLS sweepdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr8/north/sweep/8.0' if (release == 'dr8s'): # DECaLS sweepdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr8/south/sweep/8.0' if (release == 'dr9n'): sweepdir = '/global/cscratch1/sd/adamyers/dr9m/north/sweep/' if (release == 'dr9s'): sweepdir = '/global/cscratch1/sd/adamyers/dr9m/south/sweep/' # listing the sweep files tmpstr = "ls " + sweepdir + "/sweep-???[pm]???-???[pm]???.fits | awk -F \"/\" \"{print $NF}\"" p1 = subprocess.Popen(tmpstr, stdout=subprocess.PIPE, shell=True) sweeplist = np.array(p1.communicate()[0].decode('ascii').split('\n'))[:-1] nsweep = len(sweeplist) ramin, ramax, decmin, decmax = np.zeros(nsweep), np.zeros(nsweep), np.zeros(nsweep), np.zeros(nsweep) for i in range(nsweep): sweeplist[i] = sweeplist[i][-26:] sweep = sweeplist[i] ramin[i] = float(sweep[6:9]) ramax[i] = float(sweep[14:17]) if (sweep[9] == 'm'): decmin[i] = -1. * float(sweep[10:13]) else: decmin[i] = float(sweep[10:13]) if (sweep[17] == 'm'): decmax[i] = -1. * float(sweep[18:21]) else: decmax[i] = float(sweep[18:21]) collist = [] collist.append(fits.Column(name='sweepname', format='26A', array=sweeplist)) collist.append(fits.Column(name='ramin', format='E', array=ramin)) collist.append(fits.Column(name='ramax', format='E', array=ramax)) collist.append(fits.Column(name='decmin', format='E', array=decmin)) collist.append(fits.Column(name='decmax', format='E', array=decmax)) cols = fits.ColDefs(collist) hdu = fits.BinTableHDU.from_columns(cols) hdu.writeto(outfits, overwrite=True)
bsd-3-clause
-4,179,563,077,889,233,000
42.067797
105
0.609615
false
2.84153
false
false
false
generia/plugin.video.zdf_de_2016
de/generia/kodi/plugin/frontend/zdf/AbstractPage.py
1
3319
from de.generia.kodi.plugin.frontend.base.Pagelet import Item from de.generia.kodi.plugin.frontend.base.Pagelet import Action from de.generia.kodi.plugin.frontend.base.Pagelet import Pagelet from de.generia.kodi.plugin.frontend.zdf.Constants import Constants class AbstractPage(Pagelet): def _createItem(self, teaser): settings = self.settings item = None genre = '' sep = '' if teaser.genre: genre += sep + teaser.genre sep = ' | ' if teaser.category: genre += sep + teaser.category title = teaser.title #self.log.info("settings.mergeCategoryAndTitle: {} - cat: {}, title: {}, starts: {}.", self.settings.mergeCategoryAndTitle, teaser.category, title, title.startswith(teaser.category)) if settings.mergeCategoryAndTitle and settings.showGenreInTitle: if teaser.category is not None and title.startswith(teaser.category): title = title[len(teaser.category):].strip() #self.log.info("settings.mergeCategoryAndTitle: {} - cat: {}, title: {}, starts: {}.", settings.mergeCategoryAndTitle, teaser.category, title, title.startswith(teaser.category)) if teaser.label is not None and teaser.label != "" and settings.showTagsInTitle: label = teaser.label if teaser.type is not None: label = teaser.type.capitalize() + ": " + label title = '[' + label + '] ' + title title.strip() if teaser.season is not None and teaser.episode is not None and settings.showEpisodeInTitle: title = str(self._(32047, teaser.season, teaser.episode)) + " - " + title if teaser.playable and settings.showPlayableInTitle: title = '(>) ' + title if genre is not None and genre != "" and settings.showGenreInTitle: title = '[' + genre + '] ' + title title = title.strip() if teaser.date is not None and settings.showDateInTitle: title = teaser.date + " " + title isFolder = False #self.log.info("_createItem: title='{}' contentName='{}' playable='{}'", title, teaser.contentName, teaser.playable) if teaser.contentName is not None and teaser.playable: params = {'contentName': teaser.contentName, 'title': title} if teaser.apiToken is not None: params['apiToken'] = teaser.apiToken if teaser.url is not None: params['videoUrl'] = teaser.url if teaser.date is not None: params['date'] = teaser.date if teaser.duration is not None: params['duration'] = teaser.duration if genre is not None: params['genre'] = genre action = Action(pagelet='PlayVideo', params=params) isFolder = False else: action = Action(pagelet='RubricPage', params={'rubricUrl': teaser.url}) self.info("redirecting to rubric-url '{}' and teaser-title '{}' ...", teaser.url, title) isFolder = True #return None item = Item(title, action, teaser.image, teaser.text, genre, teaser.date, teaser.duration, isFolder, teaser.playable) return item
gpl-2.0
3,053,792,430,717,883,400
46.414286
190
0.597168
false
3.74605
false
false
false
jinzekid/codehub
python/test_gui/TaskManager/TaskManager.py
1
2820
# Author: Jason Lu import _thread as thread, time import threading from MyWindow import Ui_MainWindow as MainWindow from PyQt5.QtCore import QThread, pyqtSignal, QObject, QDateTime import LYUtils as utils # 单例模式 # 使用__new__方法 class Singleton(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kwargs) return cls._instance # 装饰器版本 def singleton(cls, *args, **kwargs): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return getinstance @singleton class TaskManager(QObject): listOfTasks = [] timer = None mainWindow = None # 通过类成员对象定义信号 update_date = pyqtSignal(int, str) def init_taskManager(self, func_refresh_del_task): self.timer = None self.listOfTasks = [] self.removeTasks= [] self.refresh_del_task = func_refresh_del_task # 开启新线程 #thread.start_new_thread(self.do_task, ()) pass def enqueue(self, task): if not task:return self.listOfTasks.append(task) print(">>新任务入队列 ") def dequeue(self, task): pass def get_list_of_tasks(self): return self.listOfTasks def destory_task(self, taskToken): # 倒序循环删除 for i in range(len(self.listOfTasks)-1, -1, -1): task = self.listOfTasks[i] if task.taskToken == taskToken: self.refresh_del_task(i, task) self.listOfTasks.pop(i) def run(self): while True: curTime = int(time.time()) # 获取时间戳 """ print("cur time:" + str(curTime) + ", 任务数量: " + str(len( self.listOfTasks))) """ time.sleep(1) # 倒序循环删除 for i in range(len(self.listOfTasks)-1, -1, -1): task = self.listOfTasks[i] """ print('task token:' + task.taskToken + ', left time:' + str(utils.format_time(task.leftTime))) """ # 循环更新任务剩余时间 task.update_task_info(curTime) if task.is_ready(): if task.is_start(curTime): task.do_task() else: self.update_date.emit(i, str(utils.format_time(task.leftTime))) elif task.is_done(): self.refresh_del_task(i, task) self.listOfTasks.pop(i)
gpl-3.0
-6,348,898,284,641,424,000
25.613861
79
0.519345
false
3.43295
false
false
false
judaba13/GenrePredictor
hdf5_descriptors.py
1
3890
""" This file is used to define classes that hold data for reading from the HDF5 files for MSD This code was provided by the MSD distributors to read the data. Thierry Bertin-Mahieux (2010) Columbia University tb2332@columbia.edu This code contains descriptors used to create HDF5 files for the Million Song Database Project. What information gets in the database should be decided here. This is part of the Million Song Dataset project from LabROSA (Columbia University) and The Echo Nest. Copyright 2010, Thierry Bertin-Mahieux 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/>. """ # code relies on pytables, see http://www.pytables.org import tables MAXSTRLEN = 1024 class SongMetaData(tables.IsDescription): """ Class to hold the metadata of one song """ artist_name = tables.StringCol(MAXSTRLEN) artist_id = tables.StringCol(32) artist_mbid = tables.StringCol(40) artist_playmeid = tables.IntCol() artist_7digitalid = tables.IntCol() analyzer_version = tables.StringCol(32) genre = tables.StringCol(MAXSTRLEN) release = tables.StringCol(MAXSTRLEN) release_7digitalid = tables.IntCol() title = tables.StringCol(MAXSTRLEN) artist_familiarity = tables.Float64Col() artist_hotttnesss = tables.Float64Col() song_id = tables.StringCol(32) song_hotttnesss = tables.Float64Col() artist_latitude = tables.Float64Col() artist_longitude = tables.Float64Col() artist_location = tables.StringCol(MAXSTRLEN) track_7digitalid = tables.IntCol() # ARRAY INDICES idx_similar_artists = tables.IntCol() idx_artist_terms = tables.IntCol() # TO ADD # song mbid # album mbid # url # preview url, 7digital, release_image class SongAnalysis(tables.IsDescription): """ Class to hold the analysis of one song """ analysis_sample_rate = tables.IntCol() audio_md5 = tables.StringCol(32) danceability = tables.Float64Col() duration = tables.Float64Col() end_of_fade_in = tables.Float64Col() energy = tables.Float64Col() key = tables.IntCol() key_confidence = tables.Float64Col() loudness = tables.Float64Col() mode = tables.IntCol() mode_confidence = tables.Float64Col() start_of_fade_out = tables.Float64Col() tempo = tables.Float64Col() time_signature = tables.IntCol() time_signature_confidence = tables.Float64Col() track_id = tables.StringCol(32) # ARRAY INDICES idx_segments_start = tables.IntCol() idx_segments_confidence = tables.IntCol() idx_segments_pitches = tables.IntCol() idx_segments_timbre = tables.IntCol() idx_segments_loudness_max = tables.IntCol() idx_segments_loudness_max_time = tables.IntCol() idx_segments_loudness_start = tables.IntCol() idx_sections_start = tables.IntCol() idx_sections_confidence = tables.IntCol() idx_beats_start = tables.IntCol() idx_beats_confidence = tables.IntCol() idx_bars_start = tables.IntCol() idx_bars_confidence = tables.IntCol() idx_tatums_start = tables.IntCol() idx_tatums_confidence = tables.IntCol() class SongMusicBrainz(tables.IsDescription): """ Class to hold information coming from MusicBrainz for one song """ year = tables.IntCol() # ARRAY INDEX idx_artist_mbtags = tables.IntCol()
apache-2.0
-8,598,590,883,223,135,000
34.697248
90
0.717995
false
3.542805
false
false
false
tobegit3hub/cinder_docker
cinder/brick/local_dev/lvm.py
1
30594
# Copyright 2013 OpenStack Foundation. # 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. """ LVM class for performing LVM operations. """ import math import os import re from os_brick import executor from oslo_concurrency import processutils as putils from oslo_log import log as logging from oslo_utils import excutils from six import moves from cinder import exception from cinder.i18n import _LE, _LI from cinder import utils LOG = logging.getLogger(__name__) class LVM(executor.Executor): """LVM object to enable various LVM related operations.""" LVM_CMD_PREFIX = ['env', 'LC_ALL=C'] def __init__(self, vg_name, root_helper, create_vg=False, physical_volumes=None, lvm_type='default', executor=putils.execute, lvm_conf=None): """Initialize the LVM object. The LVM object is based on an LVM VolumeGroup, one instantiation for each VolumeGroup you have/use. :param vg_name: Name of existing VG or VG to create :param root_helper: Execution root_helper method to use :param create_vg: Indicates the VG doesn't exist and we want to create it :param physical_volumes: List of PVs to build VG on :param lvm_type: VG and Volume type (default, or thin) :param executor: Execute method to use, None uses common/processutils """ super(LVM, self).__init__(execute=executor, root_helper=root_helper) self.vg_name = vg_name self.pv_list = [] self.vg_size = 0.0 self.vg_free_space = 0.0 self.vg_lv_count = 0 self.vg_uuid = None self.vg_thin_pool = None self.vg_thin_pool_size = 0.0 self.vg_thin_pool_free_space = 0.0 self._supports_snapshot_lv_activation = None self._supports_lvchange_ignoreskipactivation = None self.vg_provisioned_capacity = 0.0 # Ensure LVM_SYSTEM_DIR has been added to LVM.LVM_CMD_PREFIX # before the first LVM command is executed, and use the directory # where the specified lvm_conf file is located as the value. if lvm_conf and os.path.isfile(lvm_conf): lvm_sys_dir = os.path.dirname(lvm_conf) LVM.LVM_CMD_PREFIX = ['env', 'LC_ALL=C', 'LVM_SYSTEM_DIR=' + lvm_sys_dir] if create_vg and physical_volumes is not None: self.pv_list = physical_volumes try: self._create_vg(physical_volumes) except putils.ProcessExecutionError as err: LOG.exception(_LE('Error creating Volume Group')) LOG.error(_LE('Cmd :%s'), err.cmd) LOG.error(_LE('StdOut :%s'), err.stdout) LOG.error(_LE('StdErr :%s'), err.stderr) raise exception.VolumeGroupCreationFailed(vg_name=self.vg_name) if self._vg_exists() is False: LOG.error(_LE('Unable to locate Volume Group %s'), vg_name) raise exception.VolumeGroupNotFound(vg_name=vg_name) # NOTE: we assume that the VG has been activated outside of Cinder if lvm_type == 'thin': pool_name = "%s-pool" % self.vg_name if self.get_volume(pool_name) is None: try: self.create_thin_pool(pool_name) except putils.ProcessExecutionError: # Maybe we just lost the race against another copy of # this driver being in init in parallel - e.g. # cinder-volume and cinder-backup starting in parallel if self.get_volume(pool_name) is None: raise self.vg_thin_pool = pool_name self.activate_lv(self.vg_thin_pool) self.pv_list = self.get_all_physical_volumes(root_helper, vg_name) def _vg_exists(self): """Simple check to see if VG exists. :returns: True if vg specified in object exists, else False """ exists = False cmd = LVM.LVM_CMD_PREFIX + ['vgs', '--noheadings', '-o', 'name', self.vg_name] (out, _err) = self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) if out is not None: volume_groups = out.split() if self.vg_name in volume_groups: exists = True return exists def _create_vg(self, pv_list): cmd = ['vgcreate', self.vg_name, ','.join(pv_list)] self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) def _get_vg_uuid(self): cmd = LVM.LVM_CMD_PREFIX + ['vgs', '--noheadings', '-o', 'uuid', self.vg_name] (out, _err) = self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) if out is not None: return out.split() else: return [] def _get_thin_pool_free_space(self, vg_name, thin_pool_name): """Returns available thin pool free space. :param vg_name: the vg where the pool is placed :param thin_pool_name: the thin pool to gather info for :returns: Free space in GB (float), calculated using data_percent """ cmd = LVM.LVM_CMD_PREFIX +\ ['lvs', '--noheadings', '--unit=g', '-o', 'size,data_percent', '--separator', ':', '--nosuffix'] # NOTE(gfidente): data_percent only applies to some types of LV so we # make sure to append the actual thin pool name cmd.append("/dev/%s/%s" % (vg_name, thin_pool_name)) free_space = 0.0 try: (out, err) = self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) if out is not None: out = out.strip() data = out.split(':') pool_size = float(data[0]) data_percent = float(data[1]) consumed_space = pool_size / 100 * data_percent free_space = pool_size - consumed_space free_space = round(free_space, 2) except putils.ProcessExecutionError as err: LOG.exception(_LE('Error querying thin pool about data_percent')) LOG.error(_LE('Cmd :%s'), err.cmd) LOG.error(_LE('StdOut :%s'), err.stdout) LOG.error(_LE('StdErr :%s'), err.stderr) return free_space @staticmethod def get_lvm_version(root_helper): """Static method to get LVM version from system. :param root_helper: root_helper to use for execute :returns: version 3-tuple """ cmd = LVM.LVM_CMD_PREFIX + ['vgs', '--version'] (out, _err) = putils.execute(*cmd, root_helper=root_helper, run_as_root=True) lines = out.split('\n') for line in lines: if 'LVM version' in line: version_list = line.split() # NOTE(gfidente): version is formatted as follows: # major.minor.patchlevel(library API version)[-customisation] version = version_list[2] version_filter = r"(\d+)\.(\d+)\.(\d+).*" r = re.search(version_filter, version) version_tuple = tuple(map(int, r.group(1, 2, 3))) return version_tuple @staticmethod def supports_thin_provisioning(root_helper): """Static method to check for thin LVM support on a system. :param root_helper: root_helper to use for execute :returns: True if supported, False otherwise """ return LVM.get_lvm_version(root_helper) >= (2, 2, 95) @property def supports_snapshot_lv_activation(self): """Property indicating whether snap activation changes are supported. Check for LVM version >= 2.02.91. (LVM2 git: e8a40f6 Allow to activate snapshot) :returns: True/False indicating support """ if self._supports_snapshot_lv_activation is not None: return self._supports_snapshot_lv_activation self._supports_snapshot_lv_activation = ( self.get_lvm_version(self._root_helper) >= (2, 2, 91)) return self._supports_snapshot_lv_activation @property def supports_lvchange_ignoreskipactivation(self): """Property indicating whether lvchange can ignore skip activation. Check for LVM version >= 2.02.99. (LVM2 git: ab789c1bc add --ignoreactivationskip to lvchange) """ if self._supports_lvchange_ignoreskipactivation is not None: return self._supports_lvchange_ignoreskipactivation self._supports_lvchange_ignoreskipactivation = ( self.get_lvm_version(self._root_helper) >= (2, 2, 99)) return self._supports_lvchange_ignoreskipactivation @staticmethod def get_lv_info(root_helper, vg_name=None, lv_name=None): """Retrieve info about LVs (all, in a VG, or a single LV). :param root_helper: root_helper to use for execute :param vg_name: optional, gathers info for only the specified VG :param lv_name: optional, gathers info for only the specified LV :returns: List of Dictionaries with LV info """ cmd = LVM.LVM_CMD_PREFIX + ['lvs', '--noheadings', '--unit=g', '-o', 'vg_name,name,size', '--nosuffix'] if lv_name is not None and vg_name is not None: cmd.append("%s/%s" % (vg_name, lv_name)) elif vg_name is not None: cmd.append(vg_name) try: (out, _err) = putils.execute(*cmd, root_helper=root_helper, run_as_root=True) except putils.ProcessExecutionError as err: with excutils.save_and_reraise_exception(reraise=True) as ctx: if "not found" in err.stderr or "Failed to find" in err.stderr: ctx.reraise = False LOG.info(_LI("Logical Volume not found when querying " "LVM info. (vg_name=%(vg)s, lv_name=%(lv)s"), {'vg': vg_name, 'lv': lv_name}) out = None lv_list = [] if out is not None: volumes = out.split() iterator = moves.zip(*[iter(volumes)] * 3) # pylint: disable=E1101 for vg, name, size in iterator: lv_list.append({"vg": vg, "name": name, "size": size}) return lv_list def get_volumes(self, lv_name=None): """Get all LV's associated with this instantiation (VG). :returns: List of Dictionaries with LV info """ return self.get_lv_info(self._root_helper, self.vg_name, lv_name) def get_volume(self, name): """Get reference object of volume specified by name. :returns: dict representation of Logical Volume if exists """ ref_list = self.get_volumes(name) for r in ref_list: if r['name'] == name: return r return None @staticmethod def get_all_physical_volumes(root_helper, vg_name=None): """Static method to get all PVs on a system. :param root_helper: root_helper to use for execute :param vg_name: optional, gathers info for only the specified VG :returns: List of Dictionaries with PV info """ field_sep = '|' cmd = LVM.LVM_CMD_PREFIX + ['pvs', '--noheadings', '--unit=g', '-o', 'vg_name,name,size,free', '--separator', field_sep, '--nosuffix'] (out, _err) = putils.execute(*cmd, root_helper=root_helper, run_as_root=True) pvs = out.split() if vg_name is not None: pvs = [pv for pv in pvs if vg_name == pv.split(field_sep)[0]] pv_list = [] for pv in pvs: fields = pv.split(field_sep) pv_list.append({'vg': fields[0], 'name': fields[1], 'size': float(fields[2]), 'available': float(fields[3])}) return pv_list def get_physical_volumes(self): """Get all PVs associated with this instantiation (VG). :returns: List of Dictionaries with PV info """ self.pv_list = self.get_all_physical_volumes(self._root_helper, self.vg_name) return self.pv_list @staticmethod def get_all_volume_groups(root_helper, vg_name=None): """Static method to get all VGs on a system. :param root_helper: root_helper to use for execute :param vg_name: optional, gathers info for only the specified VG :returns: List of Dictionaries with VG info """ cmd = LVM.LVM_CMD_PREFIX + ['vgs', '--noheadings', '--unit=g', '-o', 'name,size,free,lv_count,uuid', '--separator', ':', '--nosuffix'] if vg_name is not None: cmd.append(vg_name) (out, _err) = putils.execute(*cmd, root_helper=root_helper, run_as_root=True) vg_list = [] if out is not None: vgs = out.split() for vg in vgs: fields = vg.split(':') vg_list.append({'name': fields[0], 'size': float(fields[1]), 'available': float(fields[2]), 'lv_count': int(fields[3]), 'uuid': fields[4]}) return vg_list def update_volume_group_info(self): """Update VG info for this instantiation. Used to update member fields of object and provide a dict of info for caller. :returns: Dictionaries of VG info """ vg_list = self.get_all_volume_groups(self._root_helper, self.vg_name) if len(vg_list) != 1: LOG.error(_LE('Unable to find VG: %s'), self.vg_name) raise exception.VolumeGroupNotFound(vg_name=self.vg_name) self.vg_size = float(vg_list[0]['size']) self.vg_free_space = float(vg_list[0]['available']) self.vg_lv_count = int(vg_list[0]['lv_count']) self.vg_uuid = vg_list[0]['uuid'] total_vols_size = 0.0 if self.vg_thin_pool is not None: # NOTE(xyang): If providing only self.vg_name, # get_lv_info will output info on the thin pool and all # individual volumes. # get_lv_info(self._root_helper, 'stack-vg') # sudo lvs --noheadings --unit=g -o vg_name,name,size # --nosuffix stack-vg # stack-vg stack-pool 9.51 # stack-vg volume-13380d16-54c3-4979-9d22-172082dbc1a1 1.00 # stack-vg volume-629e13ab-7759-46a5-b155-ee1eb20ca892 1.00 # stack-vg volume-e3e6281c-51ee-464c-b1a7-db6c0854622c 1.00 # # If providing both self.vg_name and self.vg_thin_pool, # get_lv_info will output only info on the thin pool, but not # individual volumes. # get_lv_info(self._root_helper, 'stack-vg', 'stack-pool') # sudo lvs --noheadings --unit=g -o vg_name,name,size # --nosuffix stack-vg/stack-pool # stack-vg stack-pool 9.51 # # We need info on both the thin pool and the volumes, # therefore we should provide only self.vg_name, but not # self.vg_thin_pool here. for lv in self.get_lv_info(self._root_helper, self.vg_name): lvsize = lv['size'] # get_lv_info runs "lvs" command with "--nosuffix". # This removes "g" from "1.00g" and only outputs "1.00". # Running "lvs" command without "--nosuffix" will output # "1.00g" if "g" is the unit. # Remove the unit if it is in lv['size']. if not lv['size'][-1].isdigit(): lvsize = lvsize[:-1] if lv['name'] == self.vg_thin_pool: self.vg_thin_pool_size = lvsize tpfs = self._get_thin_pool_free_space(self.vg_name, self.vg_thin_pool) self.vg_thin_pool_free_space = tpfs else: total_vols_size = total_vols_size + float(lvsize) total_vols_size = round(total_vols_size, 2) self.vg_provisioned_capacity = total_vols_size def _calculate_thin_pool_size(self): """Calculates the correct size for a thin pool. Ideally we would use 100% of the containing volume group and be done. But the 100%VG notation to lvcreate is not implemented and thus cannot be used. See https://bugzilla.redhat.com/show_bug.cgi?id=998347 Further, some amount of free space must remain in the volume group for metadata for the contained logical volumes. The exact amount depends on how much volume sharing you expect. :returns: An lvcreate-ready string for the number of calculated bytes. """ # make sure volume group information is current self.update_volume_group_info() # leave 5% free for metadata return "%sg" % (self.vg_free_space * 0.95) def create_thin_pool(self, name=None, size_str=None): """Creates a thin provisioning pool for this VG. The syntax here is slightly different than the default lvcreate -T, so we'll just write a custom cmd here and do it. :param name: Name to use for pool, default is "<vg-name>-pool" :param size_str: Size to allocate for pool, default is entire VG :returns: The size string passed to the lvcreate command """ if not self.supports_thin_provisioning(self._root_helper): LOG.error(_LE('Requested to setup thin provisioning, ' 'however current LVM version does not ' 'support it.')) return None if name is None: name = '%s-pool' % self.vg_name vg_pool_name = '%s/%s' % (self.vg_name, name) if not size_str: size_str = self._calculate_thin_pool_size() cmd = ['lvcreate', '-T', '-L', size_str, vg_pool_name] LOG.debug("Creating thin pool '%(pool)s' with size %(size)s of " "total %(free)sg", {'pool': vg_pool_name, 'size': size_str, 'free': self.vg_free_space}) self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) self.vg_thin_pool = name return size_str def create_volume(self, name, size_str, lv_type='default', mirror_count=0): """Creates a logical volume on the object's VG. :param name: Name to use when creating Logical Volume :param size_str: Size to use when creating Logical Volume :param lv_type: Type of Volume (default or thin) :param mirror_count: Use LVM mirroring with specified count """ if lv_type == 'thin': pool_path = '%s/%s' % (self.vg_name, self.vg_thin_pool) cmd = ['lvcreate', '-T', '-V', size_str, '-n', name, pool_path] else: cmd = ['lvcreate', '-n', name, self.vg_name, '-L', size_str] if mirror_count > 0: cmd.extend(['-m', mirror_count, '--nosync', '--mirrorlog', 'mirrored']) terras = int(size_str[:-1]) / 1024.0 if terras >= 1.5: rsize = int(2 ** math.ceil(math.log(terras) / math.log(2))) # NOTE(vish): Next power of two for region size. See: # http://red.ht/U2BPOD cmd.extend(['-R', str(rsize)]) try: self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) except putils.ProcessExecutionError as err: LOG.exception(_LE('Error creating Volume')) LOG.error(_LE('Cmd :%s'), err.cmd) LOG.error(_LE('StdOut :%s'), err.stdout) LOG.error(_LE('StdErr :%s'), err.stderr) raise @utils.retry(putils.ProcessExecutionError) def create_lv_snapshot(self, name, source_lv_name, lv_type='default'): """Creates a snapshot of a logical volume. :param name: Name to assign to new snapshot :param source_lv_name: Name of Logical Volume to snapshot :param lv_type: Type of LV (default or thin) """ source_lvref = self.get_volume(source_lv_name) if source_lvref is None: LOG.error(_LE("Trying to create snapshot by non-existent LV: %s"), source_lv_name) raise exception.VolumeDeviceNotFound(device=source_lv_name) cmd = ['lvcreate', '--name', name, '--snapshot', '%s/%s' % (self.vg_name, source_lv_name)] if lv_type != 'thin': size = source_lvref['size'] cmd.extend(['-L', '%sg' % (size)]) try: self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) except putils.ProcessExecutionError as err: LOG.exception(_LE('Error creating snapshot')) LOG.error(_LE('Cmd :%s'), err.cmd) LOG.error(_LE('StdOut :%s'), err.stdout) LOG.error(_LE('StdErr :%s'), err.stderr) raise def _mangle_lv_name(self, name): # Linux LVM reserves name that starts with snapshot, so that # such volume name can't be created. Mangle it. if not name.startswith('snapshot'): return name return '_' + name def deactivate_lv(self, name): lv_path = self.vg_name + '/' + self._mangle_lv_name(name) cmd = ['lvchange', '-a', 'n'] cmd.append(lv_path) try: self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) except putils.ProcessExecutionError as err: LOG.exception(_LE('Error deactivating LV')) LOG.error(_LE('Cmd :%s'), err.cmd) LOG.error(_LE('StdOut :%s'), err.stdout) LOG.error(_LE('StdErr :%s'), err.stderr) raise def activate_lv(self, name, is_snapshot=False, permanent=False): """Ensure that logical volume/snapshot logical volume is activated. :param name: Name of LV to activate :param is_snapshot: whether LV is a snapshot :param permanent: whether we should drop skipactivation flag :raises: putils.ProcessExecutionError """ # This is a no-op if requested for a snapshot on a version # of LVM that doesn't support snapshot activation. # (Assume snapshot LV is always active.) if is_snapshot and not self.supports_snapshot_lv_activation: return lv_path = self.vg_name + '/' + self._mangle_lv_name(name) # Must pass --yes to activate both the snap LV and its origin LV. # Otherwise lvchange asks if you would like to do this interactively, # and fails. cmd = ['lvchange', '-a', 'y', '--yes'] if self.supports_lvchange_ignoreskipactivation: cmd.append('-K') # If permanent=True is specified, drop the skipactivation flag in # order to make this LV automatically activated after next reboot. if permanent: cmd += ['-k', 'n'] cmd.append(lv_path) try: self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) except putils.ProcessExecutionError as err: LOG.exception(_LE('Error activating LV')) LOG.error(_LE('Cmd :%s'), err.cmd) LOG.error(_LE('StdOut :%s'), err.stdout) LOG.error(_LE('StdErr :%s'), err.stderr) raise @utils.retry(putils.ProcessExecutionError) def delete(self, name): """Delete logical volume or snapshot. :param name: Name of LV to delete """ def run_udevadm_settle(): self._execute('udevadm', 'settle', root_helper=self._root_helper, run_as_root=True, check_exit_code=False) # LV removal seems to be a race with other writers or udev in # some cases (see LP #1270192), so we enable retry deactivation LVM_CONFIG = 'activation { retry_deactivation = 1} ' try: self._execute( 'lvremove', '--config', LVM_CONFIG, '-f', '%s/%s' % (self.vg_name, name), root_helper=self._root_helper, run_as_root=True) except putils.ProcessExecutionError as err: LOG.debug('Error reported running lvremove: CMD: %(command)s, ' 'RESPONSE: %(response)s', {'command': err.cmd, 'response': err.stderr}) LOG.debug('Attempting udev settle and retry of lvremove...') run_udevadm_settle() # The previous failing lvremove -f might leave behind # suspended devices; when lvmetad is not available, any # further lvm command will block forever. # Therefore we need to skip suspended devices on retry. LVM_CONFIG += 'devices { ignore_suspended_devices = 1}' self._execute( 'lvremove', '--config', LVM_CONFIG, '-f', '%s/%s' % (self.vg_name, name), root_helper=self._root_helper, run_as_root=True) LOG.debug('Successfully deleted volume: %s after ' 'udev settle.', name) def revert(self, snapshot_name): """Revert an LV from snapshot. :param snapshot_name: Name of snapshot to revert """ self._execute('lvconvert', '--merge', snapshot_name, root_helper=self._root_helper, run_as_root=True) def lv_has_snapshot(self, name): cmd = LVM.LVM_CMD_PREFIX + ['lvdisplay', '--noheading', '-C', '-o', 'Attr', '%s/%s' % (self.vg_name, name)] out, _err = self._execute(*cmd, root_helper=self._root_helper, run_as_root=True) if out: out = out.strip() if (out[0] == 'o') or (out[0] == 'O'): return True return False def extend_volume(self, lv_name, new_size): """Extend the size of an existing volume.""" # Volumes with snaps have attributes 'o' or 'O' and will be # deactivated, but Thin Volumes with snaps have attribute 'V' # and won't be deactivated because the lv_has_snapshot method looks # for 'o' or 'O' if self.lv_has_snapshot(lv_name): self.deactivate_lv(lv_name) try: self._execute('lvextend', '-L', new_size, '%s/%s' % (self.vg_name, lv_name), root_helper=self._root_helper, run_as_root=True) except putils.ProcessExecutionError as err: LOG.exception(_LE('Error extending Volume')) LOG.error(_LE('Cmd :%s'), err.cmd) LOG.error(_LE('StdOut :%s'), err.stdout) LOG.error(_LE('StdErr :%s'), err.stderr) raise def vg_mirror_free_space(self, mirror_count): free_capacity = 0.0 disks = [] for pv in self.pv_list: disks.append(float(pv['available'])) while True: disks = sorted([a for a in disks if a > 0.0], reverse=True) if len(disks) <= mirror_count: break # consume the smallest disk disk = disks[-1] disks = disks[:-1] # match extents for each mirror on the largest disks for index in list(range(mirror_count)): disks[index] -= disk free_capacity += disk return free_capacity def vg_mirror_size(self, mirror_count): return (self.vg_free_space / (mirror_count + 1)) def rename_volume(self, lv_name, new_name): """Change the name of an existing volume.""" try: self._execute('lvrename', self.vg_name, lv_name, new_name, root_helper=self._root_helper, run_as_root=True) except putils.ProcessExecutionError as err: LOG.exception(_LE('Error renaming logical volume')) LOG.error(_LE('Cmd :%s'), err.cmd) LOG.error(_LE('StdOut :%s'), err.stdout) LOG.error(_LE('StdErr :%s'), err.stderr) raise
apache-2.0
6,120,542,646,678,303,000
38.223077
79
0.532915
false
4.007598
false
false
false
halflings/receval
receval/metrics.py
1
6033
""" Metrics used to evaluate recommendations. Shamelessly copied from bwhite's gist: https://gist.github.com/bwhite/3726239 """ import numpy as np def reciprocal_rank(r): """Score is reciprocal of the rank of the first relevant item First element is 'rank 1'. Relevance is binary (nonzero is relevant). """ r = np.asarray(r).nonzero()[0] return 1. / (r[0] + 1) if r.size else 0. def mean_reciprocal_rank(rs): """Mean of the reciprocal rank Example from http://en.wikipedia.org/wiki/Mean_reciprocal_rank >>> rs = [[0, 0, 1], [0, 1, 0], [1, 0, 0]] >>> mean_reciprocal_rank(rs) 0.61111111111111105 >>> rs = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0]]) >>> mean_reciprocal_rank(rs) 0.5 >>> rs = [[0, 0, 0, 1], [1, 0, 0], [1, 0, 0]] >>> mean_reciprocal_rank(rs) 0.75 Args: rs: Iterator of relevance scores (list or numpy) in rank order (first element is the first item) Returns: Mean reciprocal rank """ return np.mean([reciprocal_rank(r) for r in rs]) def r_precision(r): """Score is precision after all relevant documents have been retrieved Relevance is binary (nonzero is relevant). >>> r = [0, 0, 1] >>> r_precision(r) 0.33333333333333331 >>> r = [0, 1, 0] >>> r_precision(r) 0.5 >>> r = [1, 0, 0] >>> r_precision(r) 1.0 Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) Returns: R Precision """ r = np.asarray(r) != 0 z = r.nonzero()[0] if not z.size: return 0. return np.mean(r[:z[-1] + 1]) def precision_at_k(r, k): """Score is precision @ k Relevance is binary (nonzero is relevant). >>> r = [0, 0, 1] >>> precision_at_k(r, 1) 0.0 >>> precision_at_k(r, 2) 0.0 >>> precision_at_k(r, 3) 0.33333333333333331 >>> precision_at_k(r, 4) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: Relevance score length < k Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) Returns: Precision @ k Raises: ValueError: len(r) must be >= k """ assert k >= 1 r = np.asarray(r)[:k] != 0 if r.size != k: raise ValueError('Relevance score length < k') return np.mean(r) def average_precision(r): """Score is average precision (area under PR curve) Relevance is binary (nonzero is relevant). >>> r = [1, 1, 0, 1, 0, 1, 0, 0, 0, 1] >>> delta_r = 1. / sum(r) >>> sum([sum(r[:x + 1]) / (x + 1.) * delta_r for x, y in enumerate(r) if y]) 0.7833333333333333 >>> average_precision(r) 0.78333333333333333 Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) Returns: Average precision """ r = np.asarray(r) != 0 out = [precision_at_k(r, k + 1) for k in range(r.size) if r[k]] if not out: return 0. return np.mean(out) def mean_average_precision(rs): """Score is mean average precision Relevance is binary (nonzero is relevant). >>> rs = [[1, 1, 0, 1, 0, 1, 0, 0, 0, 1]] >>> mean_average_precision(rs) 0.78333333333333333 >>> rs = [[1, 1, 0, 1, 0, 1, 0, 0, 0, 1], [0]] >>> mean_average_precision(rs) 0.39166666666666666 Args: rs: Iterator of relevance scores (list or numpy) in rank order (first element is the first item) Returns: Mean average precision """ return np.mean([average_precision(r) for r in rs]) def dcg_at_k(r, k, method=0): """Score is discounted cumulative gain (dcg) Relevance is positive real values. Can use binary as the previous methods. Example from http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf >>> r = [3, 2, 3, 0, 0, 1, 2, 2, 3, 0] >>> dcg_at_k(r, 1) 3.0 >>> dcg_at_k(r, 1, method=1) 3.0 >>> dcg_at_k(r, 2) 5.0 >>> dcg_at_k(r, 2, method=1) 4.2618595071429155 >>> dcg_at_k(r, 10) 9.6051177391888114 >>> dcg_at_k(r, 11) 9.6051177391888114 Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) k: Number of results to consider method: If 0 then weights are [1.0, 1.0, 0.6309, 0.5, 0.4307, ...] If 1 then weights are [1.0, 0.6309, 0.5, 0.4307, ...] Returns: Discounted cumulative gain """ r = np.asfarray(r)[:k] if r.size: if method == 0: return r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1))) elif method == 1: return np.sum(r / np.log2(np.arange(2, r.size + 2))) else: raise ValueError('method must be 0 or 1.') return 0. def ndcg_at_k(r, k, method=0): """Score is normalized discounted cumulative gain (ndcg) Relevance is positive real values. Can use binary as the previous methods. Example from http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf >>> r = [3, 2, 3, 0, 0, 1, 2, 2, 3, 0] >>> ndcg_at_k(r, 1) 1.0 >>> r = [2, 1, 2, 0] >>> ndcg_at_k(r, 4) 0.9203032077642922 >>> ndcg_at_k(r, 4, method=1) 0.96519546960144276 >>> ndcg_at_k([0], 1) 0.0 >>> ndcg_at_k([1], 2) 1.0 Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) k: Number of results to consider method: If 0 then weights are [1.0, 1.0, 0.6309, 0.5, 0.4307, ...] If 1 then weights are [1.0, 0.6309, 0.5, 0.4307, ...] Returns: Normalized discounted cumulative gain """ dcg_max = dcg_at_k(sorted(r, reverse=True), k, method) if not dcg_max: return 0. return dcg_at_k(r, k, method) / dcg_max if __name__ == "__main__": import doctest doctest.testmod()
apache-2.0
4,105,317,374,910,143,000
27.323944
80
0.557931
false
3.030136
false
false
false
zeroSteiner/AdvancedHTTPServer
examples/demo.py
1
3045
#!/usr/bin/env python # -*- coding: utf-8 -*- # # demo.py # # 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 project nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # import logging from advancedhttpserver import * from advancedhttpserver import __version__ class DemoHandler(RequestHandler): def on_init(self): self.handler_map['^redirect-to-google$'] = lambda handler, query: self.respond_redirect('http://www.google.com/') self.handler_map['^hello-world$'] = self.res_hello_world self.handler_map['^exception$'] = self.res_exception self.rpc_handler_map['/xor'] = self.rpc_xor def res_hello_world(self, query): message = b'Hello World!\r\n\r\n' self.send_response(200) self.send_header('Content-Type', 'text/plain') self.send_header('Content-Length', len(message)) self.end_headers() self.wfile.write(message) return def rpc_xor(self, key, data): return ''.join(map(lambda x: chr(ord(x) ^ key), data)) def res_exception(self, query): raise Exception('this is an exception, oh noes!') def main(): print("AdvancedHTTPServer version: {0}".format(__version__)) logging.getLogger('').setLevel(logging.DEBUG) console_log_handler = logging.StreamHandler() console_log_handler.setLevel(logging.INFO) console_log_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s")) logging.getLogger('').addHandler(console_log_handler) server = AdvancedHTTPServer(DemoHandler) #server.auth_add_creds('demouser', 'demopass') server.server_version = 'AdvancedHTTPServerDemo' try: server.serve_forever() except KeyboardInterrupt: server.shutdown() return 0 if __name__ == '__main__': main()
bsd-3-clause
-4,253,329,966,655,596,500
37.544304
115
0.741544
false
3.686441
false
false
false
nickgzzjr/sublime-gulp
cross_platform_codecs.py
1
1500
import sublime import sys import re class CrossPlaformCodecs(): @classmethod def decode_line(self, line): line = line.rstrip() decoded_line = self.force_decode(line) if sys.version_info >= (3, 0) else line decoded_line = re.sub(r'\033\[(\d{1,2}m|\d\w)', '', str(decoded_line)) return decoded_line + "\n" @classmethod def force_decode(self, text): try: text = text.decode('utf-8') except UnicodeDecodeError: if sublime.platform() == "windows": text = self.decode_windows_line(text) return text @classmethod def decode_windows_line(self, text): # Import only for Windows import locale, subprocess # STDERR gets the wrong encoding, use chcp to get the real one proccess = subprocess.Popen(["chcp"], shell=True, stdout=subprocess.PIPE) (chcp, _) = proccess.communicate() # Decode using the locale preferred encoding (for example 'cp1251') and remove newlines chcp = chcp.decode(locale.getpreferredencoding()).strip() # Get the actual number chcp = chcp.split(" ")[-1] # Actually decode return text.decode("cp" + chcp) @classmethod def encode_process_command(self, command): is_sublime_2_and_in_windows = sublime.platform() == "windows" and int(sublime.version()) < 3000 return command.encode(sys.getfilesystemencoding()) if is_sublime_2_and_in_windows else command
mit
-6,632,287,634,719,512,000
33.906977
103
0.624
false
3.856041
false
false
false
sylvan5/pygame
pyrpg/pyrpg24/pyrpg24.py
1
36082
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygame from pygame.locals import * import codecs import os import random import struct import sys SCR_RECT = Rect(0, 0, 640, 480) GS = 32 DOWN,LEFT,RIGHT,UP = 0,1,2,3 STOP, MOVE = 0, 1 # 移動タイプ PROB_MOVE = 0.005 # 移動確率 TRANS_COLOR = (190,179,145) # マップチップの透明色 sounds = {} # サウンド def main(): pygame.init() screen = pygame.display.set_mode(SCR_RECT.size) pygame.display.set_caption(u"PyRPG 24 町をつくる") # サウンドをロード load_sounds("data", "sound.dat") # キャラクターチップをロード load_charachips("data", "charachip.dat") # マップチップをロード load_mapchips("data", "mapchip.dat") # マップとプレイヤー作成 map = Map("field") player = Player("elf_female2", (1,1), DOWN) map.add_chara(player) # メッセージエンジン msg_engine = MessageEngine() # メッセージウィンドウ msgwnd = MessageWindow(Rect(140,334,360,140), msg_engine) # コマンドウィンドウ cmdwnd = CommandWindow(Rect(16,16,216,160), msg_engine) clock = pygame.time.Clock() while True: clock.tick(60) if not msgwnd.is_visible and not cmdwnd.is_visible: map.update() msgwnd.update() offset = calc_offset(player) map.draw(screen, offset) msgwnd.draw(screen) cmdwnd.draw(screen) show_info(screen, msg_engine, player, map) # デバッグ情報を画面に表示 pygame.display.update() for event in pygame.event.get(): if event.type == QUIT: sys.exit() if event.type == KEYDOWN and event.key == K_ESCAPE: sys.exit() # 表示されているウィンドウに応じてイベントハンドラを変更 if cmdwnd.is_visible: cmdwnd_handler(event, cmdwnd, msgwnd, player, map) elif msgwnd.is_visible: msgwnd.next() # 次ページへ else: if event.type == KEYDOWN and event.key == K_SPACE: sounds["pi"].play() cmdwnd.show() def cmdwnd_handler(event, cmdwnd, msgwnd, player, map): """コマンドウィンドウが開いているときのイベント処理""" # 矢印キーでコマンド選択 if event.type == KEYDOWN and event.key == K_LEFT: if cmdwnd.command <= 3: return cmdwnd.command -= 4 elif event.type == KEYDOWN and event.key == K_RIGHT: if cmdwnd.command >= 4: return cmdwnd.command += 4 elif event.type == KEYUP and event.key == K_UP: if cmdwnd.command == 0 or cmdwnd.command == 4: return cmdwnd.command -= 1 elif event.type == KEYDOWN and event.key == K_DOWN: if cmdwnd.command == 3 or cmdwnd.command == 7: return cmdwnd.command += 1 # スペースキーでコマンド実行 if event.type == KEYDOWN and event.key == K_SPACE: if cmdwnd.command == CommandWindow.TALK: # はなす sounds["pi"].play() cmdwnd.hide() chara = player.talk(map) if chara != None: msgwnd.set(chara.message) else: msgwnd.set(u"そのほうこうには だれもいない。") elif cmdwnd.command == CommandWindow.STATUS: # つよさ # TODO: ステータスウィンドウ表示 sounds["pi"].play() cmdwnd.hide() msgwnd.set(u"つよさウィンドウが ひらくよてい。") elif cmdwnd.command == CommandWindow.EQUIPMENT: # そうび # TODO: そうびウィンドウ表示 sounds["pi"].play() cmdwnd.hide() msgwnd.set(u"そうびウィンドウが ひらくよてい。") elif cmdwnd.command == CommandWindow.DOOR: # とびら sounds["pi"].play() cmdwnd.hide() door = player.open(map) if door != None: door.open() map.remove_event(door) else: msgwnd.set(u"そのほうこうに とびらはない。") elif cmdwnd.command == CommandWindow.SPELL: # じゅもん # TODO: じゅもんウィンドウ表示 sounds["pi"].play() cmdwnd.hide() msgwnd.set(u"じゅもんウィンドウが ひらくよてい。") elif cmdwnd.command == CommandWindow.ITEM: # どうぐ # TODO: どうぐウィンドウ表示 sounds["pi"].play() cmdwnd.hide() msgwnd.set(u"どうぐウィンドウが ひらくよてい。") elif cmdwnd.command == CommandWindow.TACTICS: # さくせん # TODO: さくせんウィンドウ表示 sounds["pi"].play() cmdwnd.hide() msgwnd.set(u"さくせんウィンドウが ひらくよてい。") elif cmdwnd.command == CommandWindow.SEARCH: # しらべる sounds["pi"].play() cmdwnd.hide() treasure = player.search(map) if treasure != None: treasure.open() msgwnd.set(u"%s をてにいれた。" % treasure.item) map.remove_event(treasure) else: msgwnd.set(u"しかし なにもみつからなかった。") def show_info(screen, msg_engine, player, map): """デバッグ情報を表示""" msg_engine.draw_string(screen, (300,10), map.name.upper()) # マップ名 msg_engine.draw_string(screen, (300,40), player.name.upper()) # プレイヤー名 msg_engine.draw_string(screen, (300,70), "%d_%d" % (player.x, player.y)) # プレイヤー座標 def load_sounds(dir, file): """サウンドをロードしてsoundsに格納""" file = os.path.join(dir, file) fp = open(file, "r") for line in fp: line = line.rstrip() data = line.split(",") se_name = data[0] se_file = os.path.join("se", data[1]) sounds[se_name] = pygame.mixer.Sound(se_file) fp.close() def load_charachips(dir, file): """キャラクターチップをロードしてCharacter.imagesに格納""" file = os.path.join(dir, file) fp = open(file, "r") for line in fp: line = line.rstrip() data = line.split(",") chara_id = int(data[0]) chara_name = data[1] Character.images[chara_name] = split_image(load_image("charachip", "%s.png" % chara_name)) fp.close() def load_mapchips(dir, file): """マップチップをロードしてMap.imagesに格納""" file = os.path.join(dir, file) fp = open(file, "r") for line in fp: line = line.rstrip() data = line.split(",") mapchip_id = int(data[0]) mapchip_name = data[1] movable = int(data[2]) # 移動可能か? transparent = int(data[3]) # 背景を透明にするか? if transparent == 0: Map.images.append(load_image("mapchip", "%s.png" % mapchip_name)) else: Map.images.append(load_image("mapchip", "%s.png" % mapchip_name, TRANS_COLOR)) Map.movable_type.append(movable) fp.close() def calc_offset(player): """オフセットを計算する""" offsetx = player.rect.topleft[0] - SCR_RECT.width/2 offsety = player.rect.topleft[1] - SCR_RECT.height/2 return offsetx, offsety def load_image(dir, file, colorkey=None): file = os.path.join(dir, file) try: image = pygame.image.load(file) except pygame.error, message: print "Cannot load image:", file raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image def split_image(image): """128x128のキャラクターイメージを32x32の16枚のイメージに分割 分割したイメージを格納したリストを返す""" imageList = [] for i in range(0, 128, GS): for j in range(0, 128, GS): surface = pygame.Surface((GS,GS)) surface.blit(image, (0,0), (j,i,GS,GS)) surface.set_colorkey(surface.get_at((0,0)), RLEACCEL) surface.convert() imageList.append(surface) return imageList class Map: # main()のload_mapchips()でセットされる images = [] # マップチップ(ID->イメージ) movable_type = [] # マップチップが移動可能か?(0:移動不可, 1:移動可) def __init__(self, name): self.name = name self.row = -1 # 行数 self.col = -1 # 列数 self.map = [] # マップデータ(2次元リスト) self.charas = [] # マップにいるキャラクターリスト self.events = [] # マップにあるイベントリスト self.load() # マップをロード self.load_event() # イベントをロード def create(self, dest_map): """dest_mapでマップを初期化""" self.name = dest_map self.charas = [] self.events = [] self.load() self.load_event() def add_chara(self, chara): """キャラクターをマップに追加する""" self.charas.append(chara) def update(self): """マップの更新""" # マップにいるキャラクターの更新 for chara in self.charas: chara.update(self) # mapを渡す def draw(self, screen, offset): """マップを描画する""" offsetx, offsety = offset # マップの描画範囲を計算 startx = offsetx / GS endx = startx + SCR_RECT.width/GS + 1 starty = offsety / GS endy = starty + SCR_RECT.height/GS + 1 # マップの描画 for y in range(starty, endy): for x in range(startx, endx): # マップの範囲外はデフォルトイメージで描画 # この条件がないとマップの端に行くとエラー発生 if x < 0 or y < 0 or x > self.col-1 or y > self.row-1: screen.blit(self.images[self.default], (x*GS-offsetx,y*GS-offsety)) else: screen.blit(self.images[self.map[y][x]], (x*GS-offsetx,y*GS-offsety)) # このマップにあるイベントを描画 for event in self.events: event.draw(screen, offset) # このマップにいるキャラクターを描画 for chara in self.charas: chara.draw(screen, offset) def is_movable(self, x, y): """(x,y)は移動可能か?""" # マップ範囲内か? if x < 0 or x > self.col-1 or y < 0 or y > self.row-1: return False # マップチップは移動可能か? if self.movable_type[self.map[y][x]] == 0: return False # キャラクターと衝突しないか? for chara in self.charas: if chara.x == x and chara.y == y: return False # イベントと衝突しないか? for event in self.events: if self.movable_type[event.mapchip] == 0: if event.x == x and event.y == y: return False return True def get_chara(self, x, y): """(x,y)にいるキャラクターを返す。いなければNone""" for chara in self.charas: if chara.x == x and chara.y == y: return chara return None def get_event(self, x, y): """(x,y)にあるイベントを返す。なければNone""" for event in self.events: if event.x == x and event.y == y: return event return None def remove_event(self, event): """eventを削除する""" self.events.remove(event) def load(self): """バイナリファイルからマップをロード""" file = os.path.join("data", self.name + ".map") fp = open(file, "rb") # unpack()はタプルが返されるので[0]だけ抽出 self.row = struct.unpack("i", fp.read(struct.calcsize("i")))[0] # 行数 self.col = struct.unpack("i", fp.read(struct.calcsize("i")))[0] # 列数 self.default = struct.unpack("B", fp.read(struct.calcsize("B")))[0] # デフォルトマップチップ # マップ self.map = [[0 for c in range(self.col)] for r in range(self.row)] for r in range(self.row): for c in range(self.col): self.map[r][c] = struct.unpack("B", fp.read(struct.calcsize("B")))[0] fp.close() def load_event(self): """ファイルからイベントをロード""" file = os.path.join("data", self.name + ".evt") # テキスト形式のイベントを読み込む fp = codecs.open(file, "r", "utf-8") for line in fp: line = line.rstrip() # 改行除去 if line.startswith("#"): continue # コメント行は無視 if line == "": continue # 空行は無視 data = line.split(",") event_type = data[0] if event_type == "BGM": # BGMイベント self.play_bgm(data) elif event_type == "CHARA": # キャラクターイベント self.create_chara(data) elif event_type == "MOVE": # 移動イベント self.create_move(data) elif event_type == "TREASURE": # 宝箱 self.create_treasure(data) elif event_type == "DOOR": # とびら self.create_door(data) elif event_type == "OBJECT": # 一般オブジェクト(玉座など) self.create_obj(data) fp.close() def play_bgm(self, data): """BGMを鳴らす""" bgm_file = "%s.mp3" % data[1] bgm_file = os.path.join("bgm", bgm_file) pygame.mixer.music.load(bgm_file) pygame.mixer.music.play(-1) def create_chara(self, data): """キャラクターを作成してcharasに追加する""" name = data[1] x, y = int(data[2]), int(data[3]) direction = int(data[4]) movetype = int(data[5]) message = data[6] chara = Character(name, (x,y), direction, movetype, message) self.charas.append(chara) def create_move(self, data): """移動イベントを作成してeventsに追加する""" x, y = int(data[1]), int(data[2]) mapchip = int(data[3]) dest_map = data[4] dest_x, dest_y = int(data[5]), int(data[6]) move = MoveEvent((x,y), mapchip, dest_map, (dest_x,dest_y)) self.events.append(move) def create_treasure(self, data): """宝箱を作成してeventsに追加する""" x, y = int(data[1]), int(data[2]) item = data[3] treasure = Treasure((x,y), item) self.events.append(treasure) def create_door(self, data): """とびらを作成してeventsに追加する""" x, y = int(data[1]), int(data[2]) door = Door((x,y)) self.events.append(door) def create_obj(self, data): """一般オブジェクトを作成してeventsに追加する""" x, y = int(data[1]), int(data[2]) mapchip = int(data[3]) obj = Object((x,y), mapchip) self.events.append(obj) class Character: """一般キャラクタークラス""" speed = 4 # 1フレームの移動ピクセル数 animcycle = 24 # アニメーション速度 frame = 0 # キャラクターイメージ(mainで初期化) # キャラクター名 -> 分割画像リストの辞書 images = {} def __init__(self, name, pos, dir, movetype, message): self.name = name # プレイヤー名(ファイル名と同じ) self.image = self.images[name][0] # 描画中のイメージ self.x, self.y = pos[0], pos[1] # 座標(単位:マス) self.rect = self.image.get_rect(topleft=(self.x*GS, self.y*GS)) self.vx, self.vy = 0, 0 # 移動速度 self.moving = False # 移動中か? self.direction = dir # 向き self.movetype = movetype # 移動タイプ self.message = message # メッセージ def update(self, map): """キャラクター状態を更新する。 mapは移動可能かの判定に必要。""" # プレイヤーの移動処理 if self.moving == True: # ピクセル移動中ならマスにきっちり収まるまで移動を続ける self.rect.move_ip(self.vx, self.vy) if self.rect.left % GS == 0 and self.rect.top % GS == 0: # マスにおさまったら移動完了 self.moving = False self.x = self.rect.left / GS self.y = self.rect.top / GS elif self.movetype == MOVE and random.random() < PROB_MOVE: # 移動中でないならPROB_MOVEの確率でランダム移動開始 self.direction = random.randint(0, 3) # 0-3のいずれか if self.direction == DOWN: if map.is_movable(self.x, self.y+1): self.vx, self.vy = 0, self.speed self.moving = True elif self.direction == LEFT: if map.is_movable(self.x-1, self.y): self.vx, self.vy = -self.speed, 0 self.moving = True elif self.direction == RIGHT: if map.is_movable(self.x+1, self.y): self.vx, self.vy = self.speed, 0 self.moving = True elif self.direction == UP: if map.is_movable(self.x, self.y-1): self.vx, self.vy = 0, -self.speed self.moving = True # キャラクターアニメーション(frameに応じて描画イメージを切り替える) self.frame += 1 self.image = self.images[self.name][self.direction*4+self.frame/self.animcycle%4] def draw(self, screen, offset): """オフセットを考慮してプレイヤーを描画""" offsetx, offsety = offset px = self.rect.topleft[0] py = self.rect.topleft[1] screen.blit(self.image, (px-offsetx, py-offsety)) def set_pos(self, x, y, dir): """キャラクターの位置と向きをセット""" self.x, self.y = x, y self.rect = self.image.get_rect(topleft=(self.x*GS, self.y*GS)) self.direction = dir def __str__(self): return "CHARA,%s,%d,%d,%d,%d,%s" % (self.name,self.x,self.y,self.direction,self.movetype,self.message) class Player(Character): """プレイヤークラス""" def __init__(self, name, pos, dir): Character.__init__(self, name, pos, dir, False, None) def update(self, map): """プレイヤー状態を更新する。 mapは移動可能かの判定に必要。""" # プレイヤーの移動処理 if self.moving == True: # ピクセル移動中ならマスにきっちり収まるまで移動を続ける self.rect.move_ip(self.vx, self.vy) if self.rect.left % GS == 0 and self.rect.top % GS == 0: # マスにおさまったら移動完了 self.moving = False self.x = self.rect.left / GS self.y = self.rect.top / GS # TODO: ここに接触イベントのチェックを入れる event = map.get_event(self.x, self.y) if isinstance(event, MoveEvent): # MoveEventなら sounds["step"].play() dest_map = event.dest_map dest_x = event.dest_x dest_y = event.dest_y map.create(dest_map) self.set_pos(dest_x, dest_y, DOWN) # プレイヤーを移動先座標へ map.add_chara(self) # マップに再登録 else: # プレイヤーの場合、キー入力があったら移動を開始する pressed_keys = pygame.key.get_pressed() if pressed_keys[K_DOWN]: self.direction = DOWN # 移動できるかに関係なく向きは変える if map.is_movable(self.x, self.y+1): self.vx, self.vy = 0, self.speed self.moving = True elif pressed_keys[K_LEFT]: self.direction = LEFT if map.is_movable(self.x-1, self.y): self.vx, self.vy = -self.speed, 0 self.moving = True elif pressed_keys[K_RIGHT]: self.direction = RIGHT if map.is_movable(self.x+1, self.y): self.vx, self.vy = self.speed, 0 self.moving = True elif pressed_keys[K_UP]: self.direction = UP if map.is_movable(self.x, self.y-1): self.vx, self.vy = 0, -self.speed self.moving = True # キャラクターアニメーション(frameに応じて描画イメージを切り替える) self.frame += 1 self.image = self.images[self.name][self.direction*4+self.frame/self.animcycle%4] def talk(self, map): """キャラクターが向いている方向のとなりにキャラクターがいるか調べる""" # 向いている方向のとなりの座標を求める nextx, nexty = self.x, self.y if self.direction == DOWN: nexty = self.y + 1 event = map.get_event(nextx, nexty) if isinstance(event, Object) and event.mapchip == 41: nexty += 1 # テーブルがあったらさらに隣 elif self.direction == LEFT: nextx = self.x - 1 event = map.get_event(nextx, nexty) if isinstance(event, Object) and event.mapchip == 41: nextx -= 1 elif self.direction == RIGHT: nextx = self.x + 1 event = map.get_event(nextx, nexty) if isinstance(event, Object) and event.mapchip == 41: nextx += 1 elif self.direction == UP: nexty = self.y - 1 event = map.get_event(nextx, nexty) if isinstance(event, Object) and event.mapchip == 41: nexty -= 1 # その方向にキャラクターがいるか? chara = map.get_chara(nextx, nexty) # キャラクターがいればプレイヤーの方向へ向ける if chara != None: if self.direction == DOWN: chara.direction = UP elif self.direction == LEFT: chara.direction = RIGHT elif self.direction == RIGHT: chara.direction = LEFT elif self.direction == UP: chara.direction = DOWN chara.update(map) # 向きを変えたので更新 return chara def search(self, map): """足もとに宝箱があるか調べる""" event = map.get_event(self.x, self.y) if isinstance(event, Treasure): return event return None def open(self, map): """目の前にとびらがあるか調べる""" # 向いている方向のとなりの座標を求める nextx, nexty = self.x, self.y if self.direction == DOWN: nexty = self.y + 1 elif self.direction == LEFT: nextx = self.x - 1 elif self.direction == RIGHT: nextx = self.x + 1 elif self.direction == UP: nexty = self.y - 1 # その場所にとびらがあるか? event = map.get_event(nextx, nexty) if isinstance(event, Door): return event return None class MessageEngine: FONT_WIDTH = 16 FONT_HEIGHT = 22 WHITE, RED, GREEN, BLUE = 0, 160, 320, 480 def __init__(self): self.image = load_image("data", "font.png", -1) self.color = self.WHITE self.kana2rect = {} self.create_hash() def set_color(self, color): """文字色をセット""" self.color = color # 変な値だったらWHITEにする if not self.color in [self.WHITE,self.RED,self.GREEN,self.BLUE]: self.color = self.WHITE def draw_character(self, screen, pos, ch): """1文字だけ描画する""" x, y = pos try: rect = self.kana2rect[ch] screen.blit(self.image, (x,y), (rect.x+self.color,rect.y,rect.width,rect.height)) except KeyError: print "描画できない文字があります:%s" % ch return def draw_string(self, screen, pos, str): """文字列を描画""" x, y = pos for i, ch in enumerate(str): dx = x + self.FONT_WIDTH * i self.draw_character(screen, (dx,y), ch) def create_hash(self): """文字から座標への辞書を作成""" filepath = os.path.join("data", "kana2rect.dat") fp = codecs.open(filepath, "r", "utf-8") for line in fp.readlines(): line = line.rstrip() d = line.split(" ") kana, x, y, w, h = d[0], int(d[1]), int(d[2]), int(d[3]), int(d[4]) self.kana2rect[kana] = Rect(x, y, w, h) fp.close() class Window: """ウィンドウの基本クラス""" EDGE_WIDTH = 4 # 白枠の幅 def __init__(self, rect): self.rect = rect # 一番外側の白い矩形 self.inner_rect = self.rect.inflate(-self.EDGE_WIDTH*2, -self.EDGE_WIDTH*2) # 内側の黒い矩形 self.is_visible = False # ウィンドウを表示中か? def draw(self, screen): """ウィンドウを描画""" if self.is_visible == False: return pygame.draw.rect(screen, (255,255,255), self.rect, 0) pygame.draw.rect(screen, (0,0,0), self.inner_rect, 0) def show(self): """ウィンドウを表示""" self.is_visible = True def hide(self): """ウィンドウを隠す""" self.is_visible = False class MessageWindow(Window): """メッセージウィンドウ""" MAX_CHARS_PER_LINE = 20 # 1行の最大文字数 MAX_LINES_PER_PAGE = 3 # 1行の最大行数(4行目は▼用) MAX_CHARS_PER_PAGE = 20*3 # 1ページの最大文字数 MAX_LINES = 30 # メッセージを格納できる最大行数 LINE_HEIGHT = 8 # 行間の大きさ animcycle = 24 def __init__(self, rect, msg_engine): Window.__init__(self, rect) self.text_rect = self.inner_rect.inflate(-32, -32) # テキストを表示する矩形 self.text = [] # メッセージ self.cur_page = 0 # 現在表示しているページ self.cur_pos = 0 # 現在ページで表示した最大文字数 self.next_flag = False # 次ページがあるか? self.hide_flag = False # 次のキー入力でウィンドウを消すか? self.msg_engine = msg_engine # メッセージエンジン self.cursor = load_image("data", "cursor.png", -1) # カーソル画像 self.frame = 0 def set(self, message): """メッセージをセットしてウィンドウを画面に表示する""" self.cur_pos = 0 self.cur_page = 0 self.next_flag = False self.hide_flag = False # 全角スペースで初期化 self.text = [u' '] * (self.MAX_LINES*self.MAX_CHARS_PER_LINE) # メッセージをセット p = 0 for i in range(len(message)): ch = message[i] if ch == "/": # /は改行文字 self.text[p] = "/" p += self.MAX_CHARS_PER_LINE p = (p/self.MAX_CHARS_PER_LINE)*self.MAX_CHARS_PER_LINE elif ch == "%": # \fは改ページ文字 self.text[p] = "%" p += self.MAX_CHARS_PER_PAGE p = (p/self.MAX_CHARS_PER_PAGE)*self.MAX_CHARS_PER_PAGE else: self.text[p] = ch p += 1 self.text[p] = "$" # 終端文字 self.show() def update(self): """メッセージウィンドウを更新する メッセージが流れるように表示する""" if self.is_visible: if self.next_flag == False: self.cur_pos += 1 # 1文字流す # テキスト全体から見た現在位置 p = self.cur_page * self.MAX_CHARS_PER_PAGE + self.cur_pos if self.text[p] == "/": # 改行文字 self.cur_pos += self.MAX_CHARS_PER_LINE self.cur_pos = (self.cur_pos/self.MAX_CHARS_PER_LINE) * self.MAX_CHARS_PER_LINE elif self.text[p] == "%": # 改ページ文字 self.cur_pos += self.MAX_CHARS_PER_PAGE self.cur_pos = (self.cur_pos/self.MAX_CHARS_PER_PAGE) * self.MAX_CHARS_PER_PAGE elif self.text[p] == "$": # 終端文字 self.hide_flag = True # 1ページの文字数に達したら▼を表示 if self.cur_pos % self.MAX_CHARS_PER_PAGE == 0: self.next_flag = True self.frame += 1 def draw(self, screen): """メッセージを描画する メッセージウィンドウが表示されていないときは何もしない""" Window.draw(self, screen) if self.is_visible == False: return # 現在表示しているページのcur_posまでの文字を描画 for i in range(self.cur_pos): ch = self.text[self.cur_page*self.MAX_CHARS_PER_PAGE+i] if ch == "/" or ch == "%" or ch == "$": continue # 制御文字は表示しない dx = self.text_rect[0] + MessageEngine.FONT_WIDTH * (i % self.MAX_CHARS_PER_LINE) dy = self.text_rect[1] + (self.LINE_HEIGHT+MessageEngine.FONT_HEIGHT) * (i / self.MAX_CHARS_PER_LINE) self.msg_engine.draw_character(screen, (dx,dy), ch) # 最後のページでない場合は▼を表示 if (not self.hide_flag) and self.next_flag: if self.frame / self.animcycle % 2 == 0: dx = self.text_rect[0] + (self.MAX_CHARS_PER_LINE/2) * MessageEngine.FONT_WIDTH - MessageEngine.FONT_WIDTH/2 dy = self.text_rect[1] + (self.LINE_HEIGHT + MessageEngine.FONT_HEIGHT) * 3 screen.blit(self.cursor, (dx,dy)) def next(self): """メッセージを先に進める""" # 現在のページが最後のページだったらウィンドウを閉じる if self.hide_flag: self.hide() # ▼が表示されてれば次のページへ if self.next_flag: self.cur_page += 1 self.cur_pos = 0 self.next_flag = False class CommandWindow(Window): LINE_HEIGHT = 8 # 行間の大きさ TALK, STATUS, EQUIPMENT, DOOR, SPELL, ITEM, TACTICS, SEARCH = range(0, 8) COMMAND = [u"はなす", u"つよさ", u"そうび", u"とびら", u"じゅもん", u"どうぐ", u"さくせん", u"しらべる"] def __init__(self, rect, msg_engine): Window.__init__(self, rect) self.text_rect = self.inner_rect.inflate(-32, -32) self.command = self.TALK # 選択中のコマンド self.msg_engine = msg_engine self.cursor = load_image("data", "cursor2.png", -1) self.frame = 0 def draw(self, screen): Window.draw(self, screen) if self.is_visible == False: return # はなす、つよさ、そうび、とびらを描画 for i in range(0, 4): dx = self.text_rect[0] + MessageEngine.FONT_WIDTH dy = self.text_rect[1] + (self.LINE_HEIGHT+MessageEngine.FONT_HEIGHT) * (i % 4) self.msg_engine.draw_string(screen, (dx,dy), self.COMMAND[i]) # じゅもん、どうぐ、さくせん、しらべるを描画 for i in range(4, 8): dx = self.text_rect[0] + MessageEngine.FONT_WIDTH * 6 dy = self.text_rect[1] + (self.LINE_HEIGHT+MessageEngine.FONT_HEIGHT) * (i % 4) self.msg_engine.draw_string(screen, (dx,dy), self.COMMAND[i]) # 選択中のコマンドの左側に▶を描画 dx = self.text_rect[0] + MessageEngine.FONT_WIDTH * 5 * (self.command / 4) dy = self.text_rect[1] + (self.LINE_HEIGHT+MessageEngine.FONT_HEIGHT) * (self.command % 4) screen.blit(self.cursor, (dx,dy)) def show(self): """オーバーライド""" self.command = self.TALK # 追加 self.is_visible = True class MoveEvent(): """移動イベント""" def __init__(self, pos, mapchip, dest_map, dest_pos): self.x, self.y = pos[0], pos[1] # イベント座標 self.mapchip = mapchip # マップチップ self.dest_map = dest_map # 移動先マップ名 self.dest_x, self.dest_y = dest_pos[0], dest_pos[1] # 移動先座標 self.image = Map.images[self.mapchip] self.rect = self.image.get_rect(topleft=(self.x*GS, self.y*GS)) def draw(self, screen, offset): """オフセットを考慮してイベントを描画""" offsetx, offsety = offset px = self.rect.topleft[0] py = self.rect.topleft[1] screen.blit(self.image, (px-offsetx, py-offsety)) def __str__(self): return "MOVE,%d,%d,%d,%s,%d,%d" % (self.x, self.y, self.mapchip, self.dest_map, self.dest_x, self.dest_y) class Treasure(): """宝箱""" def __init__(self, pos, item): self.x, self.y = pos[0], pos[1] # 宝箱座標 self.mapchip = 46 # 宝箱は46 self.image = Map.images[self.mapchip] self.rect = self.image.get_rect(topleft=(self.x*GS, self.y*GS)) self.item = item # アイテム名 def open(self): """宝箱をあける""" sounds["treasure"].play() # TODO: アイテムを追加する処理 def draw(self, screen, offset): """オフセットを考慮してイベントを描画""" offsetx, offsety = offset px = self.rect.topleft[0] py = self.rect.topleft[1] screen.blit(self.image, (px-offsetx, py-offsety)) def __str__(self): return "TREASURE,%d,%d,%s" % (self.x, self.y, self.item) class Door: """とびら""" def __init__(self, pos): self.x, self.y = pos[0], pos[1] self.mapchip = 45 self.image = Map.images[self.mapchip] self.rect = self.image.get_rect(topleft=(self.x*GS, self.y*GS)) def open(self): """とびらをあける""" sounds["door"].play() def draw(self, screen, offset): """オフセットを考慮してイベントを描画""" offsetx, offsety = offset px = self.rect.topleft[0] py = self.rect.topleft[1] screen.blit(self.image, (px-offsetx, py-offsety)) def __str__(self): return "DOOR,%d,%d" % (self.x, self.y) class Object: """一般オブジェクト""" def __init__(self, pos, mapchip): self.x, self.y = pos[0], pos[1] self.mapchip = mapchip self.image = Map.images[self.mapchip] self.rect = self.image.get_rect(topleft=(self.x*GS, self.y*GS)) def draw(self, screen, offset): """オフセットを考慮してイベントを描画""" offsetx, offsety = offset px = self.rect.topleft[0] py = self.rect.topleft[1] screen.blit(self.image, (px-offsetx, py-offsety)) def __str__(self): return "OBJECT,%d,%d,%d" % (self.x, self.y, mapchip) if __name__ == "__main__": main()
mit
6,963,601,677,123,207,000
36.736906
124
0.533536
false
2.4355
false
false
false
viz4biz/PyDataNYC2015
enaml/vtk_canvas.py
1
2430
#------------------------------------------------------------------------------ # Copyright (c) 2013, Nucleic 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 atom.api import ( List, Typed, ForwardTyped, ForwardInstance, observe, set_default ) from enaml.core.declarative import d_ from .control import Control, ProxyControl #: Delay the import of vtk until needed. This removes the hard dependecy #: on vtk for the rest of the Enaml code base. def vtkRenderer(): from vtk import vtkRenderer return vtkRenderer class ProxyVTKCanvas(ProxyControl): """ The abstract definition of a proxy VTKCanvas object. """ #: A reference to the VTKCanvas declaration. declaration = ForwardTyped(lambda: VTKCanvas) def set_renderer(self, renderer): raise NotImplementedError def set_renderers(self, renderers): raise NotImplementedError def render(self): raise NotImplementedError class VTKCanvas(Control): """ A control which can be used to embded vtk renderers. """ #: The vtk renderer to display in the window. This should be used #: if only a single renderer is required for the scene. renderer = d_(ForwardInstance(vtkRenderer)) #: The list of vtk renderers to display in the window. This should #: be used if multiple renderers are required for the scene. renderers = d_(List(ForwardInstance(vtkRenderer))) #: A VTKCanvas expands freely in height and width by default. hug_width = set_default('ignore') hug_height = set_default('ignore') #: A reference to the ProxyVTKCanvas object. proxy = Typed(ProxyVTKCanvas) def render(self): """ Request a render of the underlying scene. """ if self.proxy_is_active: self.proxy.render() #-------------------------------------------------------------------------- # Observers #-------------------------------------------------------------------------- @observe('renderer', 'renderers') def _update_proxy(self, change): """ An observer which sends state change to the proxy. """ # The superclass handler implementation is sufficient. super(VTKCanvas, self)._update_proxy(change)
apache-2.0
1,033,791,786,981,308,000
30.973684
79
0.6
false
4.727626
false
false
false